How can I format JS code in Vim?

Viewed 25438

I have this bit of JavaScript...

 15   $('.ajax_edit_address').each(function() {
 16     $(this).ajaxForm({
 17       target: $(this).parents('table.address').find('tr.address_header').children(':first'),
 18       success: function(response) {
 19         $('input, select, textarea', '.ajax_edit_address').removeClass('updating');
 20       }
 21     });
 22   });

That's formatted the way I like it. But let's say I had just finished typing something and I wanted to tidy it up. So I run the Vim code formatter on it...

=7j

The result is...

 15   $('.ajax_edit_address').each(function() {
 16       $(this).ajaxForm({
 17 target: $(this).parents('table.address').find('tr.address_header').children(':first'),
 18 success: function(response) {
 19 $('input, select, textarea', '.ajax_edit_address').removeClass('updating');
 20 }     
 21 }); 
 22       });

Vim seems to have trouble with functions as method arguments.

Here is what I think is the relevant part of my .vimrc...

:set cindent shiftwidth=2

" indent depends on filetype
:filetype indent on

:filetype plugin on

Is there something else that needs to be installed or configured to format JS code?

7 Answers

There is a far simpler solution that requires no vim plugins.

Install js-beautify to your system python:

pip install jsbeautifier

Then add this to your .vimrc:

autocmd FileType javascript setlocal equalprg=js-beautify\ --stdin

That's it.

Run :help equalprg to see why this works.

If you've got js-beautify installed (it's available for Python: pip install jsbeautifier, or Node: npm -g install js-beautify) then you can just run it directly from vim - to reformat the current file:

:%!js-beautify

Another alternative that do not need to configure anything inside vim is to run the format command manually at save like:

:w !js-beautify --stdin >%

After saving in this way the vim editor will ask you to reload the current file content:

W12: Warning: File "src/static/js/main.js" has changed and the buffer was changed in Vim as well
See ":help W12" for more info.
[O]K, (L)oad File: 

This works like the :w sudo tee % command used to save a file that you modified without privilege.

The command uses the standard input(STDIN) and write it to a variable file descriptor % used as source of current file.

PS: of course you need to install the js-beautify.

pip install jsbeautifier
Related