Vim:自动格式化长单行

发布于 2024-10-10 13:30:32 字数 89 浏览 0 评论 0原文

我有一段 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

明媚如初 2024-10-17 13:30:34

有一个 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.

森林迷了鹿 2024-10-17 13:30:34

将这些操作放入一个函数中会很好,使得
工作更简单。

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

功能上的进一步改进是放置一个间隙,以便该函数作用于它,而不是作用于目前不记得的整个文件。我会看一下“帮助命令”,有人可以帮忙吗?

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?

冬天旳寂寞 2024-10-17 13:30:33

首先使用正则表达式重新格式化可能会更容易:

:%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 =

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文