Fernando Fernando - 1 month ago 9
Linux Question

Vim - automatic open close braces and move cursor

I'm new to Vim and right now i just need a very simple thing:

(1)public class Foo <open brace><hit ENTER>
or
(2)public class Foo <hit ENTER><open brace><hit ENTER>


To get this

(1)public class Foo{
|cursor here
}


or

(2)public class Foo
{
|cursor here
}


My .vimrc is:

set smartindent
set shiftwidth=4
set number
inoremap { {<CR>}<Left>


Appreciate any help, thanks!

Answer

There are many ways to do what you want: "smart" plugins like AutoClose or DelimitMate or simpler custom mappings. Here is one way to do #1 but one could find many alternatives (I've had a few in ~/.vimrc):

inoremap {<CR> {<CR>}<C-o>==<C-o>O

And here is a variation for #2:

inoremap {{ <CR>{<CR>}<C-o>==<C-o>O

But I'd suggest, if you didn't do it already, to try SnipMate or UltiSnips. Both allow you to expand snippets and are very useful when writing lots of boilerplate. For example,

cla<Tab>

could become:

public class Foo
{
    |
}

Think about all the keypresses you'd save!