I have this bit of JavaScript...
15 $(\'.ajax_edit_address\').each(function() {
16 $(this).ajaxForm({
17 target: $(this).parents(\'table.addre
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
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.
I'd recommend the CLI version of einars/jsbeautify, which you can find here: https://github.com/einars/js-beautify. It's the offline version of www.jsbeautifier.org.
Use this plugin https://github.com/Chiel92/vim-autoformat to run the formatter on your current buffer with one button press.
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
VIM plugin Jsbeautify could handle jQuery correctly. It's the vim plugin version of the online Jsbeautify.
The biggest issue seems to be the cindent doesn't recognize this type of syntax:
test({
var b = 2;
});
It will turn it into this:
test({
var b = 2;
});
If you handle that case I'd imagine the indent wouldn't be so awful for the jQuery syntax. But this would require you writing a custom javascript indent file. Also, you'd have to edit the html indent file to not use cindent for script tags with javascript content.
I don't think anyone has successfully created a jquery/prototype compatible indent file for javascript. The existing javascript indent scripts are all flawed.