Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto-indent javascript code in Vim on save

I am using the awesome vim-go plugin for coding in Go with vim. (https://github.com/fatih/vim-go)

The feature that I love is the auto-indent on save. I'd like to get the same behavior for javascript files. Do you know any way to easy replicate this in js?

Many thanks

like image 276
Spearfisher Avatar asked Feb 04 '26 05:02

Spearfisher


2 Answers

You don't even need a plugin to auto indent in vim. As soon as you open the file in vim, press these keys:

gg

Your cursor should move to the beginning of the file. And then type this:

=G

which is basically saying, "remove trailing spaces from the cursor position to the end of the file". Happy coding!

like image 115
Jim Avatar answered Feb 06 '26 18:02

Jim


There exists a general autoformatting plugin for vim called vim-autoformat which integrates the js-beautifier (the engine behind the online application http://jsbeautifier.org/) and more.

It provides an :Autoformat command, which you can bind to the BufWrite event like so

au BufWrite * :Autoformat

EDIT For if you're only interested in indenting your file (not full-fledged formatting): vim-autoformat falls back to auto indenting your file if js-beautify is not installed.

like image 39
chtenb Avatar answered Feb 06 '26 18:02

chtenb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!