Vim:自动格式化长单行
我有一段 JavaScript 代码写成一长行,我想重新格式化它,以便每个语句都写在一行中。使用 Vim 可以吗?我尝试了 gqq 和 == 命令,但它们不起作用。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有一个 vim 插件,可以在 vim 中对代码进行格式化(只需按一下按钮)。它称为 vim-autoformat,您可以在此处下载:
https://github.com/vim- autoformat/vim-autoformat
它将外部代码格式化程序集成到 vim 中。
例如,如果你想格式化 javascript 代码,你只需要安装程序 js-beautifier (它在 repo 中进行了解释),一切都可以正常工作,而无需配置任何东西。
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.
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?
首先使用正则表达式重新格式化可能会更容易:
:%s/;/;\r/gc
:%s/}/}\r/gc
:%s/{/{\r/gc
等
在 ; 之后插入行 return或者 { }。
(如果您有足够的信心或文件太长,请不要使用
c
它会要求对每个匹配进行确认)一旦您的文件分成不同的行,您可以使用
gg =G
以获得正确的缩进。据我所知,不可能用 gq 或 = 将一行分成多行
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 =