Navigating your bundled gems in Vim
Do you sometimes find yourself wanting to read the code of a method in one of the gems that your project is using? Wouldn't it be good if you could put your cursor on the method or class in question, and press a key to jump straight to the definition within the gem's source code? With the
ctags program you can, and with Ivan Tkalin's
guard-ctags-bundler gem your tag files will be automatically updated when you add new gems to your bundle.
You'll want a recent version of ctags for use with Ruby. Check for a recent version with:
$ ctags --version
ctags isn't found (or you get an error message because the
--version switch isn't supported) you'll need to install Exuberant ctags.
On Debian or Ubuntu, try this:
$ sudo apt-get install exuberant-ctags
On the Mac I'd recommend installing it with Homebrew:
$ brew install ctags
Test it by typing
ctags -R inside your project's directory. It should create a
tags file that Vim can read to navigate around the classes and methods defined in your own project.
To add support for navigating around your bundled gems, we need to setup
Add these two gems to the development group in your
group :development do gem 'guard-ctags-bundler' gem 'rb-readline' end
You don't strictly need
rb-readline, but Guard's prompt improves dramatically when readline support is enabled.
bundle, and then create your
$ bundle install $ guard init ctags-bundler
You can edit the paths in your
Guardfile if you like, but the default should work well with most Rails projects and gems. Run
guard, and then edit your
Gemfile and run
bundle install in another terminal. Guard should report that it has re-generated a
If you leave
guard running while you're working it'll keep the tags files up to date for you.
Vim will automatically read the
tags file, but we'll have to tell it to read the
gems.tags file too. Add this to your
Don't store tags files in version control
Your tags files are continually updated as you edit your project, and because they're automatically generated it doesn't make any sense to check them in. If you're using
git you can tell it to ignore the tags files in all your projects like this:
$ cat <<EOF >> ~/.gitignore tags gems.tags EOF
Using ctags in Vim
Find a method in your project that you know is defined in one of the Gems in your bundle. Position the cursor on the method call, and press
Ctrl-]. You should find yourself looking at the code in the gem where the method is defined. To jump back to where you came from press
Ctrl-T (these keybindings are the same ones used for following hyperlinks in Vim's help system).
ctags support can do a lot more than that (such as opening the code in a split), and Vim's help on using ctags is excellent. Read it by typing
:help 29.1 within Vim.
- The guard-ctags-bundler GitHub page.
- Section 29 of the Vim manual.
I love feedback and questions — please feel free to get in touch on Mastodon or Twitter, or leave a comment.