How do I fix incorrect inline Javascript indentation in Vim?

Viewed 27572

I can't seem to get inline Javascript indenting properly in Vim. Consider the following:

  $(document).ready(function() {

  // Closing brace correctly indented
    $("input").focus(function() {
      $(this).closest("li").addClass("cur-focus");
    }); // <-- I had to manually unindent this

  // Closing brace incorrectly indented
    $("input").blur(function() {
      $(this).closest("li").removeClass("cur-focus");
      }); // <-- This is what it does by default. Argh!

  });

Vim seems to insist on automatically indenting the closing brace shown in the second case there. It does the same if I re-indent the whole file. How do I get it to automatically indent using the more standard JS indenting style seen in the first case?

9 Answers

maybe some combination of these settings should be in your VIMRC file.

syntax on 
set syn=auto 
set showmatch 
filetype on 
filetype plugin on 
filetype indent on 
set tabstop=4 
set softtabstop=4 
set shiftwidth=4 
set expandtab

You don't have to install plugins specialised for Javascript, you can learn the built-in Vim options for indentation. Vim has quite a few options, and some of the indenting styles like cindent, smartindent and indentexpr have options of their own.

To check whether you are using cindent or smartindent or indentexpr, run:

:set cindent?
:set smartindent?
:set indentexpr?

Despite the name, cindent doesn't just apply to C programs, it can apply to a bunch of programming languages that share roughly the same syntax, including Javascript. Have a look at :help C-indenting for documentation about this. You can adjust the settings particularly with a line like this one, see :help 'cinoptions' and :help cinoptions-values. Here's an example configuration:

:au FileType js,javascript setlocal shiftwidth=2 softtabstop=2 cinoptions=j1,J1,(1s " see help cino-j cino-J cino-(

Assuming the syntax file has good indenting for java script, visually highlight the block and press =. This works for java so I would expect it to do something half decent for java script. The results probably also depend on the settings of tabstop, expandtab and maybe shiftwidth.

gq is useful too, it formats lines rather than indents them.

Related