Vim插件之vim-autoformat

vim-autoformat是Vim的一款自动化格式代码工具,同类软件还有vim-clang-format
和Google开发的codefmt等,不过这些都只是一个框架,要使用它们还需要相应语言的格式化工具,对于vim-autoformat这里推荐几个常用的工具,分别是astyle(支持C, C++, C++/CLI, Objective‑C, C#和Java),clang-format(支持C, C++,和Objective-C ),python-pep8,python3-pep8,python-autopep8和yapf(Google开发的Python格式化工具),对于Debian系在终端执行下面命令即可完成安装

$ sudo aptitude install astyle clang-format python-pep8 python3-pep8 python-autopep8 yapf

    1

默认情况下,它会使用Google的风格来格式化C家族的代码,对于Python则使用PEP8的风格,配置如下

"auto-format
"F5自动格式化代码并保存
noremap <F5> :Autoformat<CR>:w<CR>
let g:autoformat_verbosemode=1

如果不想每次都按F5格式化代码,希望能在保存时自动格式化或者针对某种语言自动格式化,可以这样设置

"自动格式化代码,针对所有支持的文件
au BufWrite * :Autoformat
"自动格式化python代码
"au BufWrite *.py :Autoformat

在安装了yapf以后,还可以自定义python格式化的风格,

"默认情况下是pep8,还可以选择google,facebook和chromium
let g:formatter_yapf_style = 'pep8'

更进一步的,你还可以针对某种语言指定特定的格式化工具和相应的参数,比如设定以allman(ansi)的风格格式化C/C++代码同时在操作符两边加入空格(即--pad-oper参数),可以这样写

let g:formatdef_allman = '"astyle --style=allman --pad-oper"'
let g:formatters_cpp = ['allman']
let g:formatters_c = ['allman']

如果还需要对其他语言进行格式化或者修改配置可以参考github主页上的说明。
当然,格式化代码也不一定非要安装插件才能实现,因为Vim可以执行外部命令,因此你也可以写一个函数调用外部工具来实现代码格式化,比如下面就用函数调用astyle和autopep8来格式化代码

map <F2> :call FormatCode()<CR>
func! FormatCode()
    exec "w"
    if &filetype == 'c' || &filetype == 'h'
        exec "!astyle --style=allman --suffix=none %"
    elseif &filetype == 'cpp' || &filetype == 'cc' || &filetype == 'hpp'
        exec "!astyle --style=allman --suffix=none %"
    elseif &filetype == 'perl'
        exec "!astyle --style=gnu --suffix=none %"
    elseif &filetype == 'py'|| &filetype == 'python'
        exec "!autopep8 --in-place --aggressive %"
    elseif &filetype == 'java'
        exec "!astyle --style=java --suffix=none %"
    elseif &filetype == 'jsp'
        exec "!astyle --style=gnu --suffix=none %"
    elseif &filetype == 'xml'
        exec "!astyle --style=gnu --suffix=none %"
    else
        exec "normal gg=G"
        return
    endif
endfunc

上面astyle和autopep8参数的含义可以到相应网站查询,这里就不解释了。
 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值