Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I format JS code in Vim?

Tags:

vim

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?

like image 419
Ethan Avatar asked Oct 30 '09 23:10

Ethan


People also ask

Can I write JavaScript in Vim?

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.

What is Vim format?

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.


3 Answers

VIM plugin Jsbeautify could handle jQuery correctly. It's the vim plugin version of the online Jsbeautify.

like image 151
Jichao Avatar answered Oct 07 '22 09:10

Jichao


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.

like image 15
Nick Zalutskiy Avatar answered Oct 07 '22 09:10

Nick Zalutskiy


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
like image 10
Pierz Avatar answered Oct 07 '22 08:10

Pierz