Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autoindent in vim always empty the line if there are only whitespace in it, can I change that?

Tags:

vim

For example I usually type paired braces first then move the cursor inside the block, what I expect should be like this:

....{
....█
....}

But vim automatically empty the second line since there are only whitespace characters in it, so the result coming out is like this:

....{
█
....}

How do I fix this?

(The dots are for space characters, and █ shows the location of my cursor.)

like image 876
xzhu Avatar asked May 14 '11 09:05

xzhu


2 Answers

Don't worry about the fact that Vim strips spaces from an otherwise empty line when you leave insert mode. As others here have commented, this is a good thing. Instead, look for a way to automatically restore the indentation level when you invoke insert mode on that line.

The i, I, a and A commands all preserve the cursor position when putting you into insert mode. But check the documentation for :help cc:

["x]cc    Delete [count] lines [into register x] and start
          insert linewise. If 'autoindent' is on, preserve
          the indent of the first line.

If the autoindent option is on, then running cc on the blank line will switch to insert mode and restore the appropriate level of indentation, setting you up just as you want:

....{
    |
....}

Note that the S key is a synonym for cc (:help S).

like image 107
nelstrom Avatar answered Oct 21 '22 06:10

nelstrom


If you really want that (though I agree with @ThiefMaster), it's just a matter of changing the way you type it.

Here are 2 solutions:

Solution 1: If you like the arrow keys

Step 1 Cursor is "|". Type the {

{|

Step 2 Type Return

{
    |

Step 3 Type }

{
}|

Step 4 Press the up arrow

{|
}

Step 5 Type Return

{
    |
}

Solution 2

Step 1 Type the {

{|

Step 2 Type Return

{
    |

Step 3 Type }

{
}|

Step 4 Escape from insert mode

{
}█

Step 5 Type O

{
    |
}
like image 43
sidyll Avatar answered Oct 21 '22 06:10

sidyll