Search code examples
vimctags

Ctags - only show relevant or contextual tags


I have a working Ctags setup with Vim.
My current settings are as follows:

set tags=./tags;/
set tags+=~/.ctags/*/tags

which basically looks up for a tags file in the current directory and up until /, and also looks up for tags inside ~/.ctags directory, where I have tags sorted for different projects in different directories.

Now, everything is working fine except when: - I have two tag files defined as: ~/.ctags/ruby/tags and ~/.ctags/php/tags - and I am working in a PHP project and CTRL+] takes me to a tag for a Ruby project (due to the second rule defined above) - when I expected it to search for a relevant tag inside ~/.ctags/php/tags - it instead found a match inside ~/.ctags/ruby/tags - and hence, the behaviour.

So, can I ask Vim to only look up inside ~/.ctags/php/tags when I am working in PHP, only look up ~/.ctags/ruby/tags when I am working in ruby, and lets say ~/.ctags/xxxx/tags when I am working in xxxx

Regards


Solution

  • The way I have done it in my .vimrc file is by setting a local tags variable:

    augroup TagFileType
        autocmd!
        autocmd FileType * setl tags<
        autocmd FileType * exe 'setl tags+=~/.ctags/' . &filetype . '/tags'
    augroup END
    

    What this does: whenever you open a file it copies the current contents of the global tags variable to the local tags variable, and adds ~/.ctags/[filetype]/tags to it. This means that in a php buffer only ~/.ctags/php/tags would be searched, and in a ruby buffer ~/.ctags/ruby/tags. If you have any tags you want to be searched in all buffers you can set the global tags variable to point to those, and they will be loaded in all buffers.