If you are a Linux developer, there is no alternative to the deadly combination of ctags and cscope when it comes to source code browsing and editing. I remember years back, out of mere curiosity I started learning them one evening and ended up in practicing throughout the night to get accustomed. I am a fan of ctags and cscope since then. They are much much lighter and faster than any other IDE I have laid my hands on.
ctags and cscope are the solutions to all your code browsing needs
Installation
To install on Ubuntu:
$ sudo apt-get install exuberant-ctags cscope
Usage
I added the following in my .bashrc to generate the tags and cscope file data:
function ta () { #clean older info rm -rf tags rm -rf cscope.files rm -rf cscope.out # generate new info find $PWD | egrep -i "\.(c|h|cpp)$" > cscope.files ctags -R . *.c *.h *.cpp --tag-relative=yes ./ }
To generate tags and cscope file information, navigate to the root directory of your project and run
$ ta
Troubleshooting on SuSE
I got the following error repeatedly on SuSE while trying to open tag search results (though it worked well on Ubuntu):
E429: File "/path/to/file.c" does not exist
Here are the steps I followed to fix it:
- Generate cscope.files with absolute path
$ find /path/to/project/files | egrep -i "\.(c|h|cpp)$" > cscope.files
- Generate the tags file
$ ctags -R . *.c *.h *.cpp --tag-relative=yes ./
A list of excellent tutorials, tips etc. to learn ctags & cscope:
- Browsing programs with tags
- The Vim/Cscope tutorial
- Jumping to the declaration of a local/global variable
- Vi and Vim Editor: 12 Powerful Find and Replace Examples
- ctags and cscope
- Ctags and Taglist
- Jumping to previously visited locations
The only plug-ins I use:
- MiniBufExplorer
NOTE: Add ‘set hidden
‘ in your ~/.vimrc not to lose syntax highlighting when you close a buffer. This hides the buffer instead of closing them. vim has a bug which causes loss of syntax highlighting on a buffer quit. - Taglist
- CScope maps
- a.vim
Some pointers:
- search word under cursor:
<Shift-#>
- find file with pattern in cscope:
cs f fe file
//check cscope_maps.vim for other switches - to list all possibilities: type
:ts IPPR
and then press<Ctrl-d>
<Ctrl-]>
jumps to definition while<Ctrl-o>
returns to previous location (double<'>
does the same too).<Ctrl-i>
jumps forward.
Some handy .vimrc entries to enjoy your mug of vi:
set ai //leads to scattered code when pasting in remote terminal (like PuTTY) on Windows, //run set noai first to avoid. set cindent //c like indentation set ic //ignore case while searching set incsearch //incremental search during typing set hlsearch //highlight search matches set ts=4 //tab length set sw=4 //shift width, amount on shift you want in new lines set nu //show line numbers
Happy coding! 🙂