Using Ctags with Vim
An important feature that all modern IDEs have is the ability to go directly to the definition of a function, or class, from where it is used. This feature is naturally available in Vim as well.
Vim doesn’t have any built-in project feature, so an external program has to be used to create the function and class list used. The program used for this is ctags. As input it takes a bunch of source files, and it will output a tags file which can then be loaded by Vim. Ctags has support for a lot different languages as default, and when required the search patterns can be extended with regular expressions. In Ctags for PHP 5 I explain how to use these options to support PHP 5’s object oriented syntax.
The default use of ctags is as follows:
$ ctags -Ro project.tags *.py
The -R option tells ctags to search for files recursively while the -o option implies that the file name following is the output file. The last part, *.py, is a standard file search – which in this case will find all the python files.
Once the tag-file has been created we need to load it into Vim. This is done by issuing the :set tags=/path/to/project.tags. After that Vim knows which words are associated with already defined functions and classes, and where those definitions can be found.
Jumping from the usage to the definition is done with the CTRL-] command when you have the cursor over the word you which to search for. The opposite command of this that I recently found was the CTRL-T, which will take you back to the previous place you used the CTRL-] command.
So if you have three functions, a() which calls b(), which again calls c(). For instance:
1 2 3 4 5 6 7 8 | def a(): b() def b(): c() def c(): print "do fancy stuff!" |
With the cursor on b() on line 2 we can use CTRL-] to go to line 4, where b() is defined. Once there we can either use CTRL-T to go back to a() and line 2, or we can use move the cursor to the c() part of line 5 and press CTRL-] to find the definition of c(). When we have found c() in this manner we can use CTRL-T two times to return to a(), the first usage takes us to b() (line 5) and the second usage puts us back in a() (line 2) where we began.
As I had been programming for quite a while without using these features it took me a while for them to become second nature. But now that I’ve become to used them they save a lot of time, especially when jumping between different files in a large project.