Vim Cmake integration

Viewed 6741

I have a cmake project. I want to do the following easily

  • search the declaration, definition and references of any variable, function, etc. under the cursor, which may be declared in an external header file whose path is added using INCLUDE_DIRECTORIES in CMakeLists.txt
  • rename a variable, function, etc. that is declared in the project

How can I set this up?

4 Answers

You can try to use vim plugin cmake4vim in order to integrate CMake to Vim. This plugin helps to work with cmake targets and allows to generate compilation database file (compile_commands.json). A lot of plugins use this file for code completion, jump to definition and etc. (for example YCM)

Also you can use vim lsp plugins (for example vim-lsp) these plugins use language servers for code completion, refactoring and another good features.

But CMake project integration (cmake cache generation, project compilation, etc.) and search the declaration, definition and etc are different tasks. And different plugins and tools solve these tasks.

  • You can tell Vim where to look for includes by adding entries to the path option. I don't have enough experience with Cmake to know how to pull paths from CMakeLists.txt, though.

    See :help 'path'.

  • Assuming a properly set path, it is possible to use the built-in :dsearch and related commands to search for definitions across includes.

    The define option has a prescriptive name but it could be used to find any specific pattern so you could alter it to match declarations, too, or really anything.

    See :help include-search and :help 'define'.

  • Vim has no built-in concept of "reference". :isearch and friends should work for that but they will probably be too noisy.

  • Renaming is usually done with something like:

    :grep foo paths
    :cwindow
    :cdo s/foo/bar/gc
    

YouCompleteMe will help you. It uses compilation_database.json, witch can be generated by cmake.

This plugin also provides autocompetion for many languages.

Related