Easy code navigation in vim with ctags

The Vim editor comes with a lot of powerful features. One of the very useful but lesser known feature of Vim is tag jumping. It allows you to quickly jump to the definition of an identifier and back. To achieve this, Vim takes the help of a tag file which can be generated with the help of a tool called ctags.

Ctags (AKA exuberant ctags) is tool which generates an index of tags in source code files. A tag can be any identifier like class name, function name or variable name. The index file can then be used by text editors to provide fast and easy navigation to the corresponding class, function or variable definition in your code base. Ctags already supports 41 languages and adding support for new languages is easy.

In this article we are going to see how to install it on Ubuntu and use it with Vim.

Installation

Installing ctags is straight forward. In most Linux distributions, it is available in the default repositories and can be installed using the built in package manager.

sudo apt install exuberant-ctags

Adding Support in Vim

There is actually nothing to do here. Ctags support comes built into Vim. You can read about the built in tag support in vim by running :help tags or :help ctags

Generating the tag file

Next step is to generate the tag file for your code base. From the base directory of your project, run

ctags -R

This will generate tags for all known source code files in your code base. The -R flag tell ctags to recursively scan directories. Files of unknown types will be ignored. If the command executes successfully, a file named tags will be created.

Navigating inside Vim

To navigate to a tag definition inside vim, open a source code file, place the cursor on the tag you want to find and press Ctrl+]. To move back to the previous position, press Ctrl+t.

That’s it. Make sure to re-generate the tags whenever new classes/functions are created.

Leave a comment

Your email address will not be published. Required fields are marked *