Vim与clang-format

前一段时间因工做须要参与了一个开源项目,在向github提交代码后提示格式校验失败。html

项目的管理者告知,要想修改的代码能入库须要使用Clang-Format校验。git

须要使用下面的命令对上次的修改从新格式化下:github

git show HEAD | clang-format-diff-3.9 -p 1 -style=file -i

经过调查了解到此开源项目是使用Clang Tools来管理代码的格式,可以使用ClangCheck来校验代码的格式问题,使用clang-format来格式化代码。vim

咱们为何不能够在IDE中直接集成Clang工具自动格式化代码吗?bash

我使用的IDE是VIM,我相信如此强大的工具必然能实现此功能,在官网http://clang.llvm.org/docs/ClangTools.html 我如愿的找到了资料。工具

首先须要安装clang-formatcode

sudo apt-get install clang-format-3.9
ln -s /usr/bin/clang-format-3.9 /usr/bin/clang-format

而后orm

cd ~/sbin;
wget https://raw.githubusercontent.com/llvm/llvm-project/master/clang/tools/clang-format/clang-format.py

再修改~/.vimrc来配置clang-format.py使用方法,增长如下内容htm

"""""""""""""""""""""""""""""""""""""""""""""""
" Seting clang-format
"""""""""""""""""""""""""""""""""""""""""""""""
map <C-F> :pyf ~/sbin/clang-format.py<cr>
imap <C-F> <c-o>:pyf ~/sbin/clang-format.py<cr>
function! Formatonsave()
    let l:formatdiff = 1
    pyf ~/sbin/clang-format.py
endfunction
autocmd BufWritePre *.c,*.h,*.cc,*.cpp call Formatonsave()

这样当编辑*.c,*.h,*.cc,*.cpp时,会自动格式化,也能够是使用ctrl+f格式化一行或者选中的区域。get

clang-format默认是使用llvm格式,用户也可根据须要配置格式化参数。

可行在工做路径的最上层路径,使用如下方式生成.clang-format文件,而后可根据须要修改参数。

clang-format -style=llvm -dump-config > .clang-format

-style=xxxx  可以使用LLVM, Google, Chromium, Mozilla, WebKit

相关文章
相关标签/搜索