Reputation: 34489
I'm a C# developer and I'm new to using Vim. I'm curious, what would you put in your .vimrc
file so that when you type a curly brace and hit Enter, like this:
public void Foo() {<Enter>
that brace gets put on a new line, and the caret moves to the innards of the braces, like this:
public void Foo()
{
|
}
Any help would be appreciated, thanks!
Upvotes: 5
Views: 4099
Reputation: 32926
Your question is very close to auto-close plugin issuse with curly brackets where
inoremap <expr> <cr> getline(".")[col(".")-2:col(".")-1]=="{}" ? "<cr><esc>O" : "<cr>"
answers the question -- this is somewhat what I use in lh-brackets.
Here, it seems you aren't using any bracketing plugin. The text to search becomes '\S\s*{$'
, and you can insert instead: <BS><cr>{<cr>}<esc>O
, or just {<cr>}<esc>O
if there is only {
on the line. If the cursor is within {}
, you should also integrate the previous test.
This becomes:
inoremap <expr> <cr>
\ getline(".") =~ '\S\s*{$' ? "<bs><cr>{<cr>}<esc>O"
\ : getline('.') =~ '^\s*{$' ? "<cr>}<esc>O"
\ : getline(".")[col(".")-2:col(".")-1]=="{}" ? "<cr><esc>O"
\ : "<cr>"
Upvotes: 6
Reputation: 10064
There are a lot of ways to program this. Just as an example I might do this:
inoremap {<Cr> <Esc>:call AutoBracketDrop()<Cr>a
function! AutoBracketDrop()
if col('.') == col('$') - 1
substitute /\s*$//
exec "normal! A\<Cr>{\<Cr>X\<Cr>}\<Esc>k$x"
else
exec "normal! a{\<Cr>\<Esc>"
endif
endfunction
First I add a insert map that will break out of insert and call the AutoBracketDrop
function and when finished enter back into insert mode.
The function simply checks to see if the cursor column matches the last column of the line. If so we remove the trailing whitespace and append the test:
cursor is here>
{
X
}
Because the use of <Cr>
it should keep the indentation as if you typed them. We have to have a marker X
otherwise Vim will remove whitespace from the empty line and continuing with an append (a
) will loose the indentation. This way the text ends up as:
cursor was here>
{
X
}
Then we move the cursor up a line, delete the X
and exit the function.
In the case of it being in the middle of the line we just simple recreate the characters typed that were used to trigger the mapping.
Upvotes: 1