在 Vim 中保存时缩进 JSON

Indent JSON on save in Vim

我将 elzr/vim-json 用于 JSON,效果非常好。 gg=G 缩进 JSON,并且如果它包含无效的 JSON.

也不会破坏我的缓冲区

有没有一种方法可以 运行 gg=G 保存,但仅限于 JSON 个文件?

我猜你正在寻找 autocmd:

:autocmd BufWritePre *.json :normal gg=G

您可以将此行添加到您的 vimrc,gg=G 将应用于保存时匹配 *.json 模式的每个文件。

或者,您可以使用 python -m json.tool 缩进您的 JSON 文件:

:autocmd BufWritePre *.json execute '%!python -m json.tool' | w

此命令将使用外部命令 (python -m json.tool) 对您的代码进行 lint 并将其保存到当前缓冲区 (w)。