Vim: Auto Formatting Long Single Lines
Asked Answered
T

3

6

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.

Trunk answered 5/1, 2011 at 8:25 Comment(0)
H
7

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 =

Harkins answered 5/1, 2011 at 8:38 Comment(1)
:%s/\([;}{]\)/\1\r/gc is more convient.Hyposensitize
N
3

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.

Nosebleed answered 3/12, 2012 at 20:26 Comment(0)
A
0

would be nice to put these actions into a function, making the job simpler.

function! FormatJavaScript()   
    :%s/;/;\r/gc
    :%s/}/}\r/gc
    :%s/{/{\r/gc
endfun
map <F2> <esc>:call FormatJavaScript()<cr>

a further improvement in function would be to put a gap, so that the function acts on it, instead of acting on the entire file, which does not remember at the moment. I'll take a look at "help command", could someone help with this?

Abnormality answered 5/1, 2011 at 10:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.