Cscope with Vim for finding Java symbols

Cscope, like ctags, allow you to find symbols in your source from multiple files in your project easily. While it was originally developed for C (easily inferred by the name), the project has extended to cover a number of other languages as well, Java included.

Before you mistake cscope as a rehash of my tip on using exuberant-ctags, let me explain why scope is different. Cscope has semantic knowledge of the Java as a language, and understands when you are looking for a symbol (a variable or method definition), and other useful search functions, like finding out other methods that invoke method you want, or listing all the methods definition uses.

(Image of Cscope in Action)

The advantage of semantic knowledge is that when you are looking for a variable or method, you won’t be sent to some uncharted parts of your code, such as within your comments, just because there is a piece of text that matches the name.

To use it with vim as the default editor, you’ll have to set that in the environment in your shell (where the following is for bash) if it isn’t set already:

export EDITOR=/usr/bin/vim

You’ll need to generate a list of files for cscope to be able to generate cross references to. This is easily done by using the find command in the root directory where your java files are found:

find ./ -name *.java > cscope.files

cscope.files is the filename that cscope will read each time it starts up, so make sure you adhere to that.

There are ways to allow cscope to run within vim instead of the other way round, but while I managed to do it after a bit of experimentation, I did find that I’ve used it with cscope invoking vim more commonly, whenever I need to fire it up and look for the methods or variables that I want from time to time. Happy cscoping!

If you like reading this, you may also enjoy: