Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim and Ctags tips and tricks [closed]

People also ask

How do you navigate with ctags?

Vim's built-in code navigation functionality using ctags is fantastically useful. Properly configured, it can allow you to jump from file to file in a project with one or two keypresses. Position the cursor over an object or function name, press C-] and Vim takes you directly to its definition; C-o takes you back.

Where are ctags stored?

Ctags is a very useful tool to navigate any source code of the programming language. Identifiers, methods, classes, etc. from the source code are parsed by using ctags and saved the index in a tag file. Each tag is stored in each line.


Ctrl+] - go to definition
Ctrl+T - Jump back from the definition.
Ctrl+W Ctrl+] - Open the definition in a horizontal split

Add these lines in vimrc
map <C-\> :tab split<CR>:exec("tag ".expand("<cword>"))<CR>
map <A-]> :vsp <CR>:exec("tag ".expand("<cword>"))<CR>

Ctrl+\ - Open the definition in a new tab
Alt+] - Open the definition in a vertical split

After the tags are generated. You can use the following keys to tag into and tag out of functions:

Ctrl+Left MouseClick - Go to definition
Ctrl+Right MouseClick - Jump back from definition


One line that always goes in my .vimrc:

set tags=./tags;/

This will look in the current directory for "tags", and work up the tree towards root until one is found. IOW, you can be anywhere in your source tree instead of just the root of it.


Another useful plugin for C development is cscope Just as Ctags lets you jump to definitions, Cscope jumps to the calling functions.

If you have cscope in your ~/bin/ directory, add the following to your .vimrc and use g^] to go to the calling function (see :help cscope).

if has("cscope")
    set csprg=~/bin/cscope
    set csto=0
    set cst
    set nocsverb
    " add any database in current directory
    if filereadable("cscope.out")
        cs add cscope.out
        " else add database pointed to by environment
    elseif $CSCOPE_DB != ""
        cs add $CSCOPE_DB
    endif
endif

Almost forgot... Just as ctags - you have to generate (and periodically update) the database. I use the following script

select_files > cscope.files
ctags -L cscope.files
ctags -e -L cscope.files
cscope -ub -i cscope.files

Where 'select_files' is another script that extracts the list of C and header files from the Makefile. This way I index only the files actually used by the project.


You can add directories to your ctags lookup. For example, I have a ctags index built for Qt4, and have this in my .vimrc:

set tags+=/usr/local/share/ctags/qt4