0

I'm using vim to code and I set autoindent in my ~/.vimrc.

Now, if I code as below:

if (a == 1)
{|     // the cursor is here and I type ENTER
}

After typing the ENTER, the code becomes as below:

if (a == 1)
{
    |     // Now the cursor is here, it indented automatically
}

It works as expected.

However, if I code like this:

if (a == 1)
{
|}   // the corsor is here and I type ENTER

It will become:

if (a == 1)
{

|}   // the corsor is here

Then I type k to move the cursor up and it will become:

    if (a == 1)
    {
|       // the corsor is here now, this is NOT what I expected
    }

What I expect:

if (a == 1)
{
    |       // after typing `k`, the cursor will indent automatically
}

Well, this might not be a big issue but I still want to make it.

Is it possible to do so?

  • 1
    I use UltiSnips for this. The workflow is if<tab> --> change condition-->jump forward. Done. – dedowsdi Apr 21 at 13:01
  • <c-f> always resets the indentation and the cursor position on the current line. – Luc Hermitte Apr 21 at 15:42
0

Well, I found another way to avoid this issue:

inoremap <C-v><Enter> <CR><C-o>O

So, if I code like this:

if (a == 1)
{|}    // the cursor is here with INSERT mode

Now I can type <C-v><C-Enter> to get what I expected.

If you have a better way, please feel free to pose your answer and I'll accept it.

| improve this answer | |
0

The simpler solution is to create a small function and to map <CR> to this function:

function! Enter()

    " When the cursor is between 2 curvy braces
    if search('{\%#}', 'n')

        " new line and insert line above
        return "\<CR>\<C-o>O"
    endif

    " Otherwise, simple newline
    return "\<CR>"
endfunction

inoremap <CR> <C-r>=Enter()<CR>

This is actually what some auto tag closing plugins do. (like autopairs for example)

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.