Jun 2
Crazy Cool Vim Mapping for Ruby
Want Vim to automatically insert a end for you when you type do ? I
do, and I tried out PitCapitain's EndToken function, but the mapping
for shift-newline doesn't work for me.
So, I hacked his function so that it works with a normal newline, which is also a bit more natural.
There are two functions at work here, the first does the real magic:
function RubyEndToken ()
let current_line = getline( '.' )
let braces_at_end = '{\s*\(|\(,\|\s\|\w\)*|\s*\)\?$'
let stuff_without_do = '^\s*\(class\|if\|unless\|begin\|case\|for\|module\|while\|until\|def\)'
let with_do = 'do\s*\(|\(,\|\s\|\w\)*|\s*\)\?$'
if match(current_line, braces_at_end) >= 0
return "\<CR>}\<C-O>O"
elseif match(current_line, stuff_without_do) >= 0
return "\<CR>end\<C-O>O"
elseif match(current_line, with_do) >= 0
return "\<CR>end\<C-O>O"
else
return "\<CR>"
endif
endfunction
And the next, which is my function that gets called when I edit a ruby file:
function UseRubyIndent ()
setlocal tabstop=8
setlocal softtabstop=2
setlocal shiftwidth=2
setlocal expandtab
imap <buffer> <CR> <C-R>=RubyEndToken()<CR>
endfunction
And here is how I get UseRubyIndent called:
autocmd FileType ruby,eruby call UseRubyIndent()
After putting this in your vimrc, you'll have new magic when editing a ruby file. Give it a try, type "class Foo" and then press Return!
Update: May 27, 2007, I've made several improvements to this code, and extracted it into a plugin for vim.
This is an awesome script if you're using Vim to edit Ruby code. I also tried the PitCaptain function and had trouble getting it to work. Thanks for putting this together.