Ctags for PHP 5
In an earlier post I wrote about how to use Ctags with Vim. Unfortunately ctags doesn’t support PHP 5 yet. The creators of ctags anticipated a scenario of unknown languages, so they made it easy to customize the parsing behaviour. A blog post about a similar solution can be found at the Phly, boy, phly blog.
The main feature available to make this possible is the --regex-<LANG>=/regex/replacement/flag option. The LANG is replaced with the language name of your choice, regex is a standard regex for finding the function or class name, replacement is the name we will associate with the tag (usually the name captured in the regex part). The last flag part is used to give meta information about the search – in this case either c for class or f for function.
Instead of going around and remember the usage of that option, as well as the other ones needed, I created little script, ctags_php, to do it all for me. The code for the script is given below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #!/bin/bash pushd . if [ $# -lt 2 ] then echo "usage: $0 <path to project base dir> <ctags file name>" exit 0 fi cd $1 ctags-exuberant -f ~/.vim/tags/$2 \ -h ".php" -R \ --exclude="\.svn" \ --totals=yes \ --tag-relative=yes \ --PHP-kinds=+cf \ --regex-PHP='/abstract class ([^ ]*)/\1/c/' \ --regex-PHP='/interface ([^ ]*)/\1/c/' \ --regex-PHP='/(public |static |abstract |protected |private )+function ([^ (]*)/\2/f/' 2> /dev/null echo "Ctags-file for $1 saved to $2" popd |
Usage of the script is very simple. If the base path of my project files are at /home/michael/project/world_domination I would use the follow to index all of the files:
ctags_php /home/michael/project/world_domination world_domination
First argument is the path to the project, and the second part is the name given to the ctags file which is later stored in ~/.vim/tags. It is important that the ~/.vim/tags/ directory is created before running the script, otherwise it won’t work. To load those tags into Vim I would then use :set tags=~/.vim/tags/world_domination.
You might also noticed that I’m piping the error output from the ctags-exuberant command to /dev/null. This is because it has a tendency to create some annoying errors about invalid references that I’ve been unable to remove. Luckily they can safely be ignored. If the script doesn’t give the proper tags, you might want to remove the 2> /dev/null parts so you can read through the error messages to discern the reason.
Amr Mostafa Said,
May 18, 2009 @ 11:29
How about you give credit for the original script? http://weierophinney.net/matthew/archives/134-exuberant-ctags-with-PHP-in-Vim.html
Michael Plikk Said,
May 18, 2009 @ 11:55
The script is not from his page, but I can see that the similarities are striking so it might be easy to draw the wrong conclusions. I’ve added a link to his page at the start of the post now, just to make sure that everyone gets credit where it is due.