Tags for PHP in Vim

on March 09, 2016. in Software, Programming, Development. A 2 minute read.

One thing I was missing for a long time in Vim is to be able to “jump to definition” in an easy and painless way.

The other thing I wanted to improve is to be able to tell easily where am I actually in the code base; to see the current class and method name of wherever the cursor was.

With a bit of googling and poking around, I finally came up with a perfect combo of 5 plugins (yep, five!) that enables me to do both, and a little bit of extra.

Tags made easy

Gutentags  is a brilliant Vim plugin that makes it so easy to have tags. Just install the plugin and boom! Tags! It will figure out things on it’s own and just generate the tags in the background. I use it daily for a fairly large code base and I never had any problems with the tags, or with Vim being unresponsive while the tags are being generated.

The only two settings I have set for it is what to exclude and where to store the tag files to not pollute the current project with them.

let g:gutentags_exclude = ['*.css', '*.html', '*.js']
let g:gutentags_cache_dir = '~/.vim/gutentags'

That’s it.

Jump to definition

Pair gutentags with CtrlP and it’s CtrlPTag method and we get jump to definition.

map <silent> <leader>jd :CtrlPTag<cr><c-\>w

Move to the method name we’re interested in, hit <leader>jd and it will jump to it’s definition. Tip: <C->w means “insert word under cursor”.

Where the hell am I?

My second requirement for displaying the current class and method name was a bit more difficult to fulfill. It takes the tagbar, tagbar-phpctags and lightline plugins as well as the phpctags tag generator to accomplish that.

Let the tagbar plugin know where the phpctags bin is:

let g:tagbar_phpctags_bin='~/.vim/phpctags'

This will make the tagbar plugin use phpctags to generate tags for the current file. To finally display the current tag in lightline, I wrote a simple tagbar component for it:

'tagbar': '%{tagbar#currenttag("[%s]", "", "f")}'

My complete lightline settings at the time of writing this can be found here.