Problem with smartindent in Vim

In vim with smartindent on:

  • Press Enter , say if-statement
  • Enter {
  • Press Enter twice
  • Enter }
  • If you press ↑ and go to the previous line, the indent is removed from the empty line.

Even the vim documentation says that:

If you do not enter anything on a new line except <BS> or CTRL-D , and then enter <Esc> , CTRL-O or <CR> , the indent will be deleted again.

Is there a way to keep this indent and not delete it?

+6
vim auto-indent
source share
4 answers

Use Shift + S to start editing on an empty line (from the command line, obviously). This will launch your cursor with the expected level of indentation.


The other does not answer: "the answer to the question-how-to-ask-but-better-better":

When you enter an opening curly bracket in insert mode, this inserts the corresponding set of curly braces and leave the cursor on a new line in the middle.

 :imap { {<CR>}<Esc>O 

Similarly, it automatically inserts the corresponding parsers and square brackets.

 :imap ( ()<Left> :imap [ []<Left> 

(Reset the lead : when added to vimrc .)

As I commented on Victor’s answer, changing the Vim indentation behavior will leave β€œempty” lines containing extraneous spaces in your files. IMO, this is completely unbearable.

+7
source share

When this happens to me, I sometimes use ddko (or ddO ) to delete a line without enough spaces and open a new line with the right indentation. Or I just press A and then Tab enough time to get the right indent.

+2
source share

the article here says that you have the very same problem, and that you insert vimrc to fix it.

 inoremap <CR> <CR><Space><BS> nnoremap o o<Space><BS> nnoremap O O<Space><BS> 

I definitely have not tested this.

also the same articles cite a shorter alternative solution .

+1
source share

My preferred method is {<CR>}<esc>shift+o , as it surpasses {<CR><CR>}<esc>k shift+s few strokes. However, I got into a rut with him, and in the end I just used o or O to grab new, correctly indented lines from empty when I should use S.

That is, configure your binding structure and open the line above:

 if (true) { }//cursor here, press shift-o 

And you get the indentation that you expect.

An open-tag trick is no less keypresses than <up><end><cr> , but when reinstalling and shifting a transition, you can quickly drop it.

In addition, do not forget to specify your manual indentation reset and block the movement. If you are inside a distorted curly brace, just use ={ (or =i{ if you are on top of one of the curly braces). I use this when I have a good idea that should see the text as soon as possible, and I don't worry about any frippery formatting until I have a break.

+1
source share

All Articles