What steps should I take to ensure that Vim properly formats the indentation for this JavaScript code?

Currently an Emacs user, but trying out Vim for a change. :)

I'm really enjoying the quick keystrokes and the overall philosophy of Vim, however I've been running into some issues with the more advanced features. One problem I'm having is with indenting, specifically when using the = command.

Take a look at this JS snippet. This is how Emacs' js2-mode indents it, which I prefer:

var MyClass = declare([], {
    constructor: function(params) {
        if(!params) {
            params = {};
    }

Now compare that to what Vim does. It's a mess:

       var MyClass = declare([], {
constructor: function(params) {
if(!params) {
params = {};
}

All the code above this block gets indented correctly, but from there on it's a disaster. And I have blocks like this all over my code. I've checked the :filetype settings and tried toggling those switches. I've experimented with plugins as well. Still can't seem to get it right. I'm using gVim 7.4, downloaded just a few days ago. I came across this question where the snippet shown there is perfectly indented straight away.

Does anyone have any suggestions on what I could try next? Appreciate any advice!

Answer №1

In your .vimrc:

set  nocompatible " vi has been around for many decades

set expandtab     " use soft tabs set shiftwidth=2  # 2 spaces tabs for JavaScript (?) set softtabstop=2

filetype on 
filetype plugin on 
filetype plugin indent on " enable auto indentation for supported languages (including JavaScript)

To reformat the entire file, enter gg=G

gg -> navigate to top of file
= -> apply proper indentation 
G -> all the way to the end of the file

Answer №2

For over a decade, I've been dedicated to using VIM as my primary text editor. I rely on this Javascript syntax plugin to enhance my coding experience. To test proper indentation in VIM, I follow these steps:

1: Begin by creating a new file and specifying the filetype for Javascript:

:set filetype=javascript

2: Paste your code (even if it may be malformatted)

3: Press gg=G to automatically format the entire buffer

After completing these steps, I find that the resulting code appears clean and well-structured:

var MyClass = declare([], {
  constructor: function(params) {
    if(!params) {
      params = {};
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Attempting to access a variable defined in one pipe results in it being undefined in a

Currently, I am utilizing gulp to process pages for a website. Some of these pages are PHP files, however, after going through the template engine, they all end up with a .html file extension. My intention is to add a property to each file indicating if it ...

The Navbar's Toggle Icon Causes Automatic Window Resize

I implemented a mobile navigation bar using React and JS that slides in from the left when clicked. However, I encountered two issues: whenever I click on a menu button in the navbar or when my ad carousel moves, the window resizes for some reason. Additio ...

Display a pleasant alert message when the file is not recognized as an image during the loading

Is there someone who can assist me? I have attempted multiple times but without success. How can I display a sweet alert when a file is selected that is not an image? <input type ="file" /> ...

Creating a fixed navigation bar that stays at the top of the page when scrolling

I am trying to create a navigation bar similar to the one seen on W3School's website. I would like the navigation bar to overlap the header when scrolling down, and for the header to appear above the nav bar when scrolling back to the top. Despite m ...

Reorganize code in JavaScript and TypeScript files using VSCode

Is there a way to efficiently organize the code within a .js / .ts file using Vscode? Specifically, when working inside a Class, my goal is to have static variables at the top, followed by variables, then methods, and so on automatically. I did some resea ...

Adjusting the color of a value in justGage requires a few simple steps to

Is it possible to modify the color and design of the text in the Value parameter of justGage after creating the gauge? My goal is to change the text color to blue with an underline to give it a link-like appearance. Appreciate your assistance. ...

What is the best way to substitute multiple substrings with strings from multiple interconnected arrays?

Looking for a way to manipulate a lengthy string in JS? Seeking to add new characters to each match within the string to create a fresh output? Need to handle multiple occurrences of a specific substring in the long text? Any strategies or suggestions? con ...

Efficiently Displaying Multiple HTML Elements in React Native WebView

I am currently working on developing an Epub reader in React Native and facing a challenge. I need to find a way to efficiently transfer multiple html content files from the Epub container to the webview in order to achieve seamless pagination. ...

Control the playback of individual HTML5 audio elements using jQuery for seamless user experience

How can I modify the code to ensure that only one HTML5 audio element plays at a time? Currently, all tracks are able to play simultaneously. I am using jQuery for play and pause functionalities. If one track is playing and another is clicked on, how can ...

Guide to adding an image with feathers.js and multer:

I am currently working on integrating feathers.js with React for my project and I am facing an issue with uploading images. I have tried using multer and busboy for handling the upload, but I am unable to successfully upload the image or access it through ...

Activate audio and trigger notification

I'm looking to incorporate a small beep sound into my web application before displaying an alert message. Here's what I currently have: if(_none_valid) { $.playSound('/static/wav/beep_error.wav').delay(300); alert('ERROR: ...

Having trouble with the page redirection issue? Here's how you can troubleshoot and resolve

My goal is to restrict access to both the user home and admin dashboard, allowing access only when logged in. Otherwise, I want to redirect users to the login or admin login page. import { NextResponse } from 'next/server' import { NextRequest } ...

Boost the scrolling velocity of my sidebar using Jquery

Hello there, I am completely new to the world of web development and particularly to using JavaScript and jQuery. I am interested in learning how to adjust the speed at which my Sidebar scrolls down as the user navigates through the page. Here is the jQue ...

Having trouble connecting the controller variable in AngularJS to the HTML page

I'm struggling with a simple query that doesn't seem to be working for me. When making an Ajax call and retrieving data from the backend, everything seems to be in order. Here's the code snippet: $.ajax({ type: "GET", url: service ...

Having trouble inputting text into input field using ReactJS

I am currently facing a challenge while attempting to modify the value of an input field using ReactJS. The issue I am encountering is the inability to input values into the field. After reviewing several other queries, it appears that simply changing the ...

What is the best way to retrieve a particular nested value from a fetch POST response?

I performed a POST request in this manner: var myHeaders = new fetch.Headers(); raw = "srvrwd-ui=useMe" var requestOptions = { method: 'POST', headers: myHeaders, body: raw, redirect: &a ...

The onSubmit event handler seems to be malfunctioning within a Reactjs form

I recently started using React and encountered an issue with my form: class CustomForm extends React.Component { handleFormSubmit = (e) => { e.preventDefault(); const title = e.target.elements.title.value; const content = e ...

What is preventing me from extracting the callback function from the app.get method in Node.js and Express?

In my server.js file, I'm attempting to do the following: // This code is not functioning as expected, and I am unsure why. var findBooks = function (err, books) { if (!err) { return response.send(books); } else { console.log( ...

How to dynamically add an input textbox after a selection change in YUI JavaScript?

Is there a way to add an extra input textbox after an onchange event in a selectbox using the YUI library? I need to utilize YUI and the form is generated with PEAR Quickforms lib. This is what I have so far: $form->addElement('select', &ap ...

What is the best way to link my PHP with MySQL in order to execute an AJAX query?

I am currently working on making this page sortable using a dropdown selection menu. At the moment, there are only two different car makes displayed and they are not sorting properly. My ultimate goal is to enable sorting by make, model, and year, but I ne ...