• +43 660 1453541
  • contact@germaniumhq.com

Navigating Structured Code With CTags


Navigating Structured Code With CTags

As we discussed last time, we have the basic commands for searching around random files. Before dwelling into IDEs, for files that have a more esoteric language, CTags is the answer.

CTags is a map of symbol names, to other files and (usually regex) expressions on matching the line where the symbol is defined. The nice thing about them is that they are trivial to build. Think about it as a dictionary of symbols with relative positions in the files

Let’s assume we have a shell script saved as test.sh:

#!/usr/bin/env bash

hello_world() {
    if [[ "$1" =="" ]]; then
        echo "hello world"
    else # not [[ "$1" =="" ]]
        echo "hello $1"
    fi   # else [[ "$1" =="" ]]
}

hello_world "planet"

We’ll use exuberant ctags to build the dictionary:

ctags-exuberant test.sh

Vim reads this file, and you can navigate inside the script using <ctrl>+]. Simply go on the hello_world planet line, and press <ctrl>+]. The cursor jumps to the file definition.

This works even if you add lines above or after the function, or edit the function content. How is this sorcery performed? It even goes across multiple files if we index folders not just files. So how?

In the ctags wile we see the rule:

hello_world	test.sh	/^hello_world() {$/;"	f

Now I hope all is clear. Our symbol hello_world, is in the test.sh file, and the line can be found with that regex.

Since CTags supports anything from C, C++ to COBOL, and Shell, it’s one of my first choices of navigation outside IDEs.