I am not a Vim noob, but I'm not a pro either. If I have a segment of, in this case javascript, code like so
function foo(a,b,c,d) {
if (one||two) {
if (rhyme||reason) {
return true;
}
return false;
}
}
and I format it (gg=G
), I get the following code:
function foo(a,b,c,d) {
if (one||two) {
if (rhyme||reason) {
return true;
}
return false;
}
}
This is more aesthetically pleasing. However, what if instead I had wanted the below (or if I wanted to convert the above result into the below result):
function foo( a, b, c, d )
{
if ( one || two )
{
if ( rhyme || reason )
{
return true;
}
return false;
}
}
Is there a way to instruct Vim how to parse code? I can use a hack with regular expressions to find parantheses and pad spaces, but it falls apart when one also considers all the operators (!,%,*,-,+,=,/
)
Several different comments:
The =
operator only handles indentation; unless you override its behavior with :set equalprg=foo
. It won't change the content of each line. See :help =
.
The gq
operator will reformat text across lines. By default, it uses its internal formatter which it accepts options set via :set formatoptions
(see :help fo
and :help fo-table
). If you know of an external tool that will reformat code the way you want, you can set formatexpr
(per-buffer) or formatprg
(globally) to invoke that program when you do gq
. See :help gq
. Using this instead of gg=G
just becomes gggqG
.
There is a Javascript beautifier plugin on the vim site here. I haven't used it. It's just vimscript, so if you want to hack it up to format things exactly the way you want, it's all there for you to use.
Try this vim plugin: https://github.com/vim-autoformat/vim-autoformat
One button press, and you're done.
It uses gq
and sets external formatprograms in order to uses it properly.
So basically, if you install this plugin along with einars js-beautify, it is able to format javascript out of the box.
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