Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tweaking formatting rules in Vim

Tags:

vim

formatting

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 (!,%,*,-,+,=,/)

like image 448
puk Avatar asked Jan 17 '23 02:01

puk


2 Answers

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.

like image 170
David Pope Avatar answered Jan 30 '23 08:01

David Pope


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.

like image 23
chtenb Avatar answered Jan 30 '23 08:01

chtenb