Adding C++ auto-completion to Vim
I recently started using Vim as my main editor for programming. After the initial learning curve, I really started enjoying it, however, there’s some things I really miss from more traditional IDEs. Two of these are auto-completion and semantic “tips”.
Auto-completion allows the developer to type only part of a function or attribute name, and a little menu will appear with a list of suggestions based on functions and classes defined in the code and standard libraries. This is really handy when working with large libraries like STL or Eigen, where you can’t quite remember the full name of the object in question. Instead of looking up each one, the developer can just type what he can remember and, most times, he’ll find what he is looking for.
Similarly, semantic “tips” show the programmer useful information based on code elsewhere in his project (or in a library) like parameter or return types, variable types, possible function overloads etc.
After a quick Internet search, I found a brilliant Vim plugin performing exactly what I wanted called YouCompleteMe. However, it required installing another plugin called Vundle first. Vundle is a sort of package manager for Vim plugins. It’s actually quite neat, and they have a very well-written guide for the simple installation process.
Vundle has the very neat feature of being able to independently access GitHub repositories. This means that installing YouCompleteMe with Vundle is as simple as adding
Plugin 'Valloric/YouCompleteMe' anywhere between
call vundle#begin() and
call vundle#end() (these should already be present since the Vundle installation) in the file
~/.vimrc. Then, go to
~/.vim/bundle/YouCompleteMe and run
./install.py --clang-completer (this requires CMake and Python to be installed). A more detailed explanation of dependencies and extra options can be found here.
Now we have basic completion functionality working!
Now for the semantic analysis. By pressing
Ctrl + Space when in Insert mode, YCM will show semantic completion tips, including argument types and such. In order for this to work, however, there’s one more step. For C-family languages, YCM uses the CLang compiler package
libclang (which was installed when we ran the installation script). But in order for CLang to work, it needs compilation flags! There are a few ways to pass these to CLang for each project, but the easiest for me (since I use CMake a lot) is adding
set( CMAKE_EXPORT_COMPILE_COMMANDS ON ) to my
CMakeLists.txt file. This will generate a file called
compile_commands.json in you build directory. YCM looks for this file in the directory of the opened file or in any directory above it in the hierarchy (recursively). This means that in order for this to take effect, you need to copy
compile_commands.json out of your build folder and into your main project directory.