Thursday, December 9, 2010

perl, tags, and vim : effective code browsing.

Adding a tags file to vim makes for an effective code browser for perl.

I've just started a new job, so I have a large new repository of perl code and modules to familiarize myself with. I've taken this as an opportunity to refresh my tag-fu in vim. After creating a tag file with ctags [exhuberant ctags], I can now jump around my whole perl repo from within my vim session.

The -t command-line flag to vim opens files by tag (module) name, e.g. vim -t My::Module::Name. Within a vim session, I jump to the definition of a function by hitting ctrl-] with the cursor over a usage of the function, even if that definition is another file! Ctrl-t and I'm back where I started.

Today I found the -q flag to ctags, which adds the fully qualified tag for package methods, e.g. My::Package::method_1, which aids with long package names and the ctrl-] key. FTW!
I have this set of ctag flags aliased as "ctagit":


ctags -f tags --recurse --totals \
--exclude=blib --exclude=.svn \
--exclude=.git --exclude='*~' \
--extra=q \
--languages=Perl \
--langmap=Perl:+.t

In my .vimrc file, I defined the tags search path as ./tags, tags,~/code/tags ;, this will look for a tags file in the directory of a loaded file, then the current directory, and then a hardcoded path in my code area.

" [ .vimrc file ] " set tag search path: directory of current file, current working directory, hard-path set tags=./tags,tags,~/code/tags

More info on using tags in vim is available in :help tags. I've found the following commands useful.

ctrl-]jump to tag from under cursor
visual ctrl-] jump to tag from visual mode
:tag tagname jump to tag tagname
:stag tagname split screen and open tagname
:tags show the tag stack, '>' labels the current tag
:ctrl-t jump to [count] older entry in the tag stack
:[count]pop jump to [count] older entry in tag stack
:[count]tag jump to [count] newer entry in tag stack

Update:
To configure vim to treat ':' (colon) as part of the keyword to match Long::Module::Sub::Module package names, add it to the iskeyword setting. I have multiple perl filetype hooks stored in files in .vim/ftplugin/perl/. These filetype hooks are enabled with the filetype plugin on directive in my main .vimrc file.

" [ .vimrc file]
"enable loading the ftplugin directories
filetype plugin on
" [ .vim/ftplugin/perl/keyword_for_perl file]
" Append : to the list of keyword chars to allow completion on Module::Names
set iskeyword+=:

The same effect could be conjured directly in the .vimrc file via autocmd:

" append colon(:) to the iskeyword list for perl files, to enable Module::Name completion.
autocmd FileType perl set iskeyword+=:

My Configuration files are available in the spazm/config git repository on github.

2 comments:

Unknown said...

Thanks for this post! Really helped me to improve my work!

Unknown said...

Thanks for the post too.
Hello Eduardo, good to see you here.