vim插件--代码格式化工具
2021-09-14 本文已影响0人
zlcook
配置参考
vim中代码格式化工具
- vim-autoformat
- 通过配置格式化文件,可以做到自动格式化代码的目的
- 也可以手动执行一些命令格式化代码
- 格式化操作包括:
- 自动缩进
gg=G
- 重新制表符
:retab
- 移除尾部空格
:RemoveTrailingSpaces
- 自动缩进
安装
前提
- 首先确定已经安装了python2或者python3,在vim命令状态下输入如下命令验证,如果得到1表示已经安装了。
:echo has("python3")
:echo has("python2").
- 没安装则安装如下安装
先 install pynvim
python3 -m pip install pynvim
在 .vimrc
中添加python3的执行文件路径
let g:python3_host_prog="/path/to/python/executable/"
通过Vundle安装
- 在
.vimrc
中添加插件信息,然后重启vim并执行:PluginInstall
命令
Plugin 'Chiel92/vim-autoformat'
使用
配置格式化程序
-
你可以下载一个针对某个编程语言的格式化程序,比如clang-format。
-
如果不指定特定语言的格式化程序,则使用默认的格式化程序。
-
格式化程序可以通过以下几种方式自动被vim检测到
- 通过包管理工具下载的格式程序
- 通过在
.vimrc
中配置let g:formatterpath
参数指向包含格式化程序的目录,如下所示
- 通过在
let g:formatterpath = ['/some/path/to/a/folder', '/home/superman/formatters']
使用
- 配置完成后,在vim中通过下面命令使用
:Autoformat
# 指定文件类型格式化
:Autoformat json
# 只格式化当前行
:AutoformatLine
- 在
.vimrc
配置每次保存文件时,自动格式化
au BufWrite * :Autoformat
clang-format配置
- 下载
# fedora
sudo yum install clang
- 配置路径: 在clang-format二进制所在的目录下,执行:
clang-format -dump-config -style=Google > .clang-format
会生成一个.clang-format文件,这个文件在.vimrc中可以配置为使用的格式:
let g:clang_format#command = 'clang-format'
nmap <F4> :ClangFormat<cr>
autocmd FileType c ClangFormatAutoEnable
let g:clang_format#detect_style_file = 1
- 验证配置成功与否
用vim打开任一文件,执行:echo executable('clang-format')看看输出是否为1,若是则代表clang-format在vim中是可执行的。
可以打开任一C/C++文件,直接按F4执行clang-format了。
批量格式化目录下的文件
经常需要对一个目录下所有指定后缀的文件做批量格式化处理,指令如下:
clang-format -style=file -i `find . -type f -regex ".*\.\(cpp\|h\)"`