I spend way too much time fumbling around because Vim doesn\'t handle closing braces like most IDEs do. Here\'s what I want to happen:
Type this:
Here is what I have in my vimrc:
let s:pairs={
\'<': '>',
\'{': '}',
\'[': ']',
\'(': ')',
\'«': '»',
\'„': '“',
\'“': '”',
\'‘': '’',
\}
call map(copy(s:pairs), 'extend(s:pairs, {v:val : v:key}, "keep")')
function! InsertPair(left, ...)
let rlist=reverse(map(split(a:left, '\zs'), 'get(s:pairs, v:val, v:val)'))
let opts=get(a:000, 0, {})
let start = get(opts, 'start', '')
let lmiddle = get(opts, 'lmiddle', '')
let rmiddle = get(opts, 'rmiddle', '')
let end = get(opts, 'end', '')
let prefix = get(opts, 'prefix', '')
let start.=prefix
let rmiddle.=prefix
let left=start.a:left.lmiddle
let right=rmiddle.join(rlist, '').end
let moves=repeat("\<Left>", len(split(right, '\zs')))
return left.right.moves
endfunction
noremap! <expr> ,f InsertPair('{')
noremap! <expr> ,h InsertPair('[')
noremap! <expr> ,s InsertPair('(')
noremap! <expr> ,u InsertPair('<')
And, for some filetypes:
inoremap {<CR> {<C-o>o}<C-o>O
// I know that InsertPair function is trivial, but it saves time because with it I can define both command and normal mode mappings with one command without having to write lots of <Left>
s.
Vim patch 7.4.849 added a binding to allow for cursor movements without restarting the undo sequence. Once updated to >= 7.4.849 then something like this works great.
inoremap ( ()<C-G>U<Left>
Note that I grabbed that straight from the documentation included in the patch. Best simple solution for this feature yet.
inoremap ( ()<ESC>i
inoremap " ""<ESC>i
inoremap ' ''<ESC>i
inoremap { {<Cr>}<Esc>O
Install and use Vim script AutoClose as recommended in the article titled Automatically append closing characters.
Just a note to @Bob.
Karl Guertin's AutoClose has a function named ``double brace'', that is, you can type curly brace twice, as below.
int func_name(void) {{ ==> Type `{' twice here.
would result in:
int func_name(void) {
| ==> Cursor here.
}
Then, you can type a single Tab, to get indented according to your `shiftwidth' setting, then type.
If you type {}
and hit alti you will be in between the braces in INSERT
mode (at least in a terminal). Then you can hit ENTER followed by altshifto to insert the line break. You could also just do {<CR>}
and altshifto.
This may not be fully automatic, but I consider it semi-auto. It removes the need for more plugins, and is useful info to know for other use cases. For example, I use altshifto all the time to insert blank lines without having to explicitly leave INSERT
mode, and alti for getting inside ()
etc.