vim-localorie is a Vim plugin which makes it easier to work with Rails' i18n locale files.
It provides two features:
With your cursor on an i18n key, e.g. in a view or a controller, calling
localorie#translate()will load all the translations for that key into the quickfix list (or location list if you prefer). This makes it trivial to see what the translations are, and to jump to any of them.
In a YAML locale file, calling
localorie#expand_key()will echo the fully qualified key for the line you’re on. In a lengthy file this can save pages of upward scrolling whenever you want to verify you’re looking at the right key.
It has saved me a lot of time I used to waste wandering around my large locale files looking for the right translations.
There are two hurdles to jump in order to look up translations for the key under the cursor.
- Load the translations into Vim while preserving the line number of each key.
- 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.