Search code examples
c++vimctagscscope

c++, cscope, ctags, and vim: Finding classes that inherit from this one


In a rather large code base with a few layers is there a way in vim or from the command line to find all classes that are derived from a base class? grep is an option but can be slow since grep does not index.


Solution

  • Neither cscope nor ctags allow us to deal with inheritance directly but it's relatively easy to work around that limitation because derived classes are also indexed.

    cscope

    In cscope, looking for "C symbol" Foobar usually lists the original class and classes inheriting from it. Since the search is done against a database, it is lightning fast.

    Alternatively, you could use cscope's egrep searching capabilities with a pattern like :.*Foobar to list only classes inheriting from Foobar.

    So, even if we don't have a dedicated "Find classes inheriting from this class" command, we can get the work done without much effort.

    ctags

    While ctags allows you to include inheritance information with --fields=+i, that information can't be used directly in Vim. The inherits field is parsed by Vim, though, so it might be possible to build a quick and dirty solution using taglist().

    ack, ag

    Those two programs work more or less like grep but they are targeted toward searching in source code so they are really faster than grep.

    In my Vim config, :grep is set to run the ag program instead of the default grep so, searching for classes derived from the class under the cursor would look like:

    :grep :.*<C-r><C-w><CR>
    

    Here are the relevant lines from my ~/.vimrc:

    if executable("ag")
      set grepprg=ag\ --nogroup\ --nocolor\ --ignore-case\ --column
      set grepformat=%f:%l:%c:%m,%f:%l:%m
    endif