vim-localorie

vim-localorie is a Vim plugin which makes it easier to work with Rails' i18n locale files.

It provides two features:

It has saved me a lot of time I used to waste wandering around my large locale files looking for the right translations.

Implementation

There are two hurdles to jump in order to look up translations for the key under the cursor.

  1. Load the translations into Vim while preserving the line number of each key.
  2. Identify the key under the cursor.

Loading translations into Vim

The constraint here is the need to preserve the line number of each key so we can load the correct location into the quickfix or location list.

It wasn’t obvious to me how to parse YAML in Vimscript, let alone how to preserve the line numbers while doing so. Fortunately I found some Ruby code which does it so I used that. Normally I prefer pure-Vimscript, zero-dependency plugins; however this is for Rails projects so everyone will have Ruby already.

These days Vim supports JSON natively so I used JSON to pass the data from Ruby to Vim.

Identifying the key under the cursor

There could be several keys on the same line so you need to pull out the right one. Vim doesn’t provide a direct way to test whether a pattern matches at the cursor position. Instead you have to walk along the line looking at each matchstrpos() and test whether the match spans the cursor position (implementation).

And now that Vim has lambdas you can pass in what you want to do with the match without having to create an explicit function for each outcome. It makes the code much neater.

Andrew Stewart • 20 October 2016 • vimRails
You can reach me by email or on Twitter.