用Youcompleteme打造VIM的IDE

来源:互联网 发布:康得新 财务 数据报表 编辑:程序博客网 时间:2024/05/21 10:24

一直习惯在Linux用VIM看代码,但VIM相比VisualStudio和SourceInsight易用性差很多

最需要给VIM添加的功能是

1) 代码跳转,浏览变量函数定义实现等

2)代码自动补全


网上找了一圈发现了这个大神级的插件YouCompleteMe,是Google的工程师Val Markovic开发的,项目地址https://github.com/Valloric/YouCompleteMe


安装Vundle和YouCompleteMe

首先安装VIM的插件管理器,https://github.com/VundleVim/Vundle.vim


mkdir ~/.vim/bundle/

cd ~/.vim/bundle

git clone https://github.com/VundleVim/Vundle.vim.git


编辑~/.vimrc,添加YouCompleteMe的地址



重新启动VIM,执行:PluginInstall,即可安装完成


启动vim,发现vim版本太老,我的ubuntu还是14.04,vim版本是7.4.52

Youcompleme提示需要至少7.4.1578+的版本


因此下载了最新的vim代码,重新编译安装vim8.0,步骤请参考Building Vim From source.


编译ycmd

YouCompleteMe依赖ycmd模块实现代码补全功能,ycmd又依赖clang实现C/C++代码的解析

用YouCompleteMe自带的install.sh脚本完成ycmd的安装


sudo apt-get install build-essential cmake
sudo apt-get install python-dev python3-dev
cd ~/.vim/bundle/YouCompleteMe
./install.py --clang-completer


配置YouCompleteMe


至此用vim打开c文件,可以实现单个文件内的补全

但是无法跳转,无法跨文件补全,原因是没有正确配置clang的编译flag


将~/.vim/bundle/YouCompleteMe/third_party/ycmd/cpp/ycm/.ycm_extra_conf.py复制到代码所在的目录(或上级目录,本级目录找不到ycmd会自动往上找)

在flags数组中添加c代码需要的头文件路径,编译开关等

flags = ['-Wall','-Wextra','-Werror','-fexceptions','-DNDEBUG',# THIS IS IMPORTANT! Without a "-std=<something>" flag, clang won't know which# language to use when compiling headers. So it will guess. Badly. So C++# headers will be compiled as C headers. You don't want that so ALWAYS specify# a "-std=<something>".# For a C project, you would set this to something like 'c99' instead of# 'c++11'.'-std=c++11',# ...and the same thing goes for the magic -x option which specifies the# language that the files to be compiled are written in. This is mostly# relevant for c++ headers.# For a C project, you would set this to 'c' instead of 'c++'.'-x','c++','-I.../include','-I.../utils',‘-D...''-D...']

再次打开c代码文件,会有红色的地方显示clang编译出错的代码行,可以根据提示慢慢修改.ycm_extra_conf 直至没有错误,如果有些错误行不需要跳转或者补全,可以不管


最后定义跳转快捷键

map <F2> :YcmCompleter GoTo<CR>

把光标移到某个函数位置,按F2,vim自动跳到了函数定义处,哈哈!


补充

2017-6-11

YcmCompleter只能实现单个编译上下文内的跳转,所以单个编译上下文指的是一个C/C++文件以及它包含的所有头文件

所以无法跳转到定义在另一个c/c++文件中的函数,这可能是YcmComplete跳转功能的硬伤

个人认为用YcmComplete实现代码补全非常合适,但是文件跳转还需要其他更强大的工具

原创粉丝点击