Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim: Auto Formatting Long Single Lines

I have a JavaScript code written as a one long line and I want to re-format that so that each statement is written in one line. Is that possible using Vim? I tried the gqq and == commands and they didn't work.

like image 833
Rafid Avatar asked Jan 05 '11 08:01

Rafid


2 Answers

It will probably be easier to reformat using regexp first :

:%s/;/;\r/gc
:%s/}/}\r/gc
:%s/{/{\r/gc
etc

to insert line return after ; or { }.

(if you are confident enough or the file is to long, do not use c it will ask for a confirmation for each match)

Once your file is split on different lines, you can use gg=G to get the correct indentation.

As far as I know it is not possible to split a line on multiple lines with either gq or =

like image 75
Xavier T. Avatar answered Oct 06 '22 09:10

Xavier T.


There is a vim plugin that enables formatting on your code from within vim (with one button press). It's called vim-autoformat and you can dowload it here:

https://github.com/vim-autoformat/vim-autoformat

It integrates external code-formatting programs into vim. For example, if you want to format javascript code, you only need to install the program js-beautifier (it's explained in the repo), and everything works, without having to configure stuff.

like image 38
chtenb Avatar answered Oct 06 '22 07:10

chtenb