Add closing brace automatically on code blocks
From Vim Tips Wiki
[edit] Duplicate tip
This tip is very similar to the following:
These tips need to be merged – see the merge guidelines.
Tip 1162 Previous Next Created: March 5, 2006 Complexity: basic Author: Anthony Van Ham Version: 6.0
When I type an opening brace '{' I want the closing brace '}' to be inserted automatically. The following abbreviation does that as long as you code in the following style:
class blah
{
}
Just define the following abbreviation and then whenever you hit the '{' you get the rest for free, and the cursor is placed between the two braces.
iab { {<CR>}<UP>
[edit] Comments
Inserting TWO <CR> would be even better.
There are bracketing macros elsewhere on this site (in scripts) that will do these things for you, as well as place a special marker at the end of the block -- right after the } -- to which a hotkey can be used to jump when you're done editing the block.
I have an imap for 'if' in Java code that does this:
if ( <put cursor here> )
{
<put marker here>
}
<put marker here>
I then type my boolean expression and hit the hotkey to jump to the marker inside the if block, type the if code, and then hit the hotkey again to come out of the if block. Obviously, I have similar ones for else, try, catch etc.
If you use a mapping instead:
:inoremap { {<CR>}<Esc>O
You will be able to have your curly braces at the end of the control structure:
if(expression) {
}
Using the above reply I have created a binding for brackets as well
inoremap ( ()<LEFT>
I map the combination {} to do this so I still have the option of inserting just one { when I want to.
imap {} {<CR>}<Esc>O
