Configuring Vim to work with ClangD

Introduction

ClangD is a daemon which provides fast autocompletion for C and C++ projects by parsing a compile_commands.json file. This guide shows a basic method for setting up vim to be an IDE for C and C++ using this extension.

Basic Vim Config

The following shows a basic vim config file which I find useful for development

" Show absolute line numbers
set number

" Show relative line numbers (distance from current line)
set relativenumber

" Show a ruler at 80, 100, and 120 characters
set colorcolumn=80,100,120

" Highlight the current line
set cursorline

" Set a good colourscheme
colorscheme slate

" Ensure brackets are autocompleted
inoremap " ""<left>
inoremap ' ''<left>
inoremap ( ()<left>
inoremap [ []<left>

Installing YouCompleteMe

To get ClangD support we will use the YouCompleteMe extension. To install this, run the following commands

git clone --recurse-submodules https://github.com/ycm-core/YouCompleteMe.git ~/.vim/pack/YouCompleteMe/opt/YouCompleteMe
pushd ~/.vim/pack/YouCompleteMe/opt/YouCompleteMe
./install.py --all
popd

Then enable the extension by adding the following to you vimrc file:

packadd YouCompleteMe
" Let clangd fully control code completion
let g:ycm_clangd_uses_ycmd_caching = 0
" Use installed clangd, not YCM-bundled clangd which doesn't get updates.
let g:ycm_clangd_binary_path = exepath("clangd")