Skip to content

Instantly share code, notes, and snippets.

@jamis
Created Oct 29, 2009
Embed
What would you like to do?
Quickly look up Rails translation strings
" Lets you quickly find translation strings. Position your cursor over a translation
" key, type '<leader>rt' (whatever your leader character is configured to be, usually
" backslash, but I have mine set to comma) and the screen will split to show the
" corresponding translation string in config/locales/en.yml.
"
" Right now, this only supports en.yml, and does not search any other locations.
" Also, error handling is abysmal. :) But it does what I need. If you hack it up
" and make it better, let me know!
" MatchPatternAtCursor lifted (and renamed) from rails.vim, thanks tpope! :)
function! MatchPatternAtCursor(pat)
let line = getline(".")
let lastend = 0
while lastend >= 0
let beg = match(line,'\C'.a:pat,lastend)
let end = matchend(line,'\C'.a:pat,lastend)
if beg < col(".") && end >= col(".")
return matchstr(line,'\C'.a:pat,lastend)
endif
let lastend = end
endwhile
return ""
endfunction
function! RailsFindTranslationAtCursor()
let key = MatchPatternAtCursor('\w*\(\.\w\+\)\+')
call RailsFindTranslation(key)
endfunction
function! RailsFindTranslation(key)
let key = a:key
if key[0] == "."
let view = split(expand("%:h"), '/')[-1]
let file = substitute(expand('%:t'), '^_\?\(.\{-1,\}\)\..*', '\1', '')
let key = view . "." . file . key
endif
let key = "en." . key
let parts = split(key, '\.')
let pattern = ""
let index = 0
for part in parts
if len(pattern) > 0
let pattern = pattern . '\n\_.\{-\}'
endif
let pattern = pattern . '\_^' . repeat(' ', index*2)
let index = index + 1
if index == len(parts)
let pattern = pattern . '\zs'
endif
let pattern = pattern . part . ":"
endfor
let current = bufname('%')
let window = bufwinnr('config/locales/en.yml')
if window < 0
execute "10split +/" . escape(pattern, ' \') . " config/locales/en.yml"
else
execute window . "wincmd w"
execute "/" . pattern
normal zz
end
let window = bufwinnr(current)
execute window . "wincmd w"
endfunction
command! -n=1 Rtrans :call RailsFindTranslation('<args>')
map <leader>rt :silent call RailsFindTranslationAtCursor()<CR>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment