Jun 2

Crazy Cool Vim Mapping for Ruby

by Peter Jones / June 2, 2006

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.


3 Comments:


Rick MacConnell said on Feb 09, 2007: Reply

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.


P Joshi said on May 27, 2007: Reply

This is amazing! Thanks a lot, Peter, for sharing this code! It worked like a charm. And you are more than justified in saying that it is natural to use carriage return. I prefer that to Shift-Return!


saLOUt said on Tue, Aug 26: Reply

Cool script! The original seems to be not available any longer.


Post a comment.