Search code examples
javascriptvimindentationauto-indent

How can I have Vim get this JS indenting right?


Emacs user here, giving Vim a go. :)

I like the quick keystrokes and the overall philosphy very much, but I've been hitting some trouble with the slightly more advanced stuff. One of my gripes is indenting (using the = command).

See this JS snippet. This is how Emacs' js2-mode indents it. I like this :

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

Now this is what Vim does with it. Friggin' hell :

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

All the code above this construction gets indented decently, but from there on it simply sucks. And I have this kind of construction a bit all over my code. I've checked :filetype and flipped those switches on. I've tried with and without plugins. Not getting it right. Vim is gVim 7.4, downloaded a couple of days ago. I've seen this question and the snippet shown there is indented correctly out of the box.

Does anybody have a clue what I could attempt here ? Thanks for any advice !


Solution

  • In your .vimrc:

    set  nocompatible " vi is decades old
    
    set expandtab     " use soft tabs set shiftwidth=2  # 2 spaces tabs for JS (?) set softtabstop=2
    
    filetype on 
    filetype plugin on 
    filetype plugin indent on " auto indent for supported languages (JS included)
    

    To reformat all the file, type gg=G

    gg -> go to top of file
    = -> indent 
    G -> until the end of the file