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?
Vim supports basic syntax highlighting for JavaScript but I found it suboptimal especially when it comes to modern ES2015+ syntax, and it doesn't support JSX when working with React. I found that vim-javascript and vim-jsx solved my problems in both instances.
The plugin vim-autoformat lets you format your buffer (or buffer selections) with a single command: https://github.com/vim-autoformat/vim-autoformat. It uses external format programs for that, with a fallback to vim's indentation functionality. Follow this answer to receive notifications.
VIM plugin Jsbeautify could handle jQuery correctly. It's the vim plugin version of the online Jsbeautify.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With