1.安装astyle
sudo apt-get install astyle
2.第一种方式,vim执行外部命令
在.vimrc中添加如下代码: (.vimrc位于HOME目录下,如果不存在就新建一个)
map <F2> :call FormatCode()<CR> func! FormatCode() exec "w" if &filetype == 'C' || &filetype == 'h' exec "!astyle --style=google %" elseif &filetype == 'cpp' exec "!astyle --style=google %" return endif endfunc
3.第二种方式,astyle命令存储在单独文件中,在.vimrc中添加如下代码,astyle命令保存在.astylerc文件中
map <F2> :call FormatCode()<CR> func! FormatCode() exec "w" if &filetype == 'C' || &filetype == 'h' exec "!astyle --options=/home/simple/.astylerc %" elseif &filetype == 'cpp' exec "!astyle --options=/home/simple/.astylerc %" return endif endfunc
以上两种方式,按F2快捷键进行保存。