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.
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 =
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.
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?
© 2022 - 2024 — McMap. All rights reserved.
:%s/\([;}{]\)/\1\r/gc
is more convient. – Hyposensitize