Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preserve indent after pressing Esc in Vim

Tags:

vim

I have set autoindent
I go to a line, press A and <CR> which gets me to the next line and inserts an indent. However if I press Esc the cursor jumps to the beginning of the line and the indent is gone.
I have to go about and press tabs to get to the right place again.

I know the help says:

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

Is there a way to disable this, or at least a workaround?

like image 906
mihai Avatar asked Apr 28 '12 13:04

mihai


People also ask

How do I indent code in Vim?

To indent the current line, or a visual block: ctrl-t, ctrl-d - indent current line forward, backwards (insert mode) visual > or < - indent block by sw (repeat with . ) then try hitting the F5 key while in insert mode (or just :set paste ).

How do I fix tabs in Vim?

Fix indentation in the whole fileStart in the top of a file (to get there, press gg anywhere in the file.). Then press =G , and Vim will fix the indentation in the whole file. If you don't start in the beginning of the file, it will fix indentation from current line to the bottom of file.

What is smart indent in Vim?

autoindent essentially tells vim to apply the indentation of the current line to the next (created by pressing enter in insert mode or with O or o in normal mode. smartindent reacts to the syntax/style of the code you are editing (especially for C). When having it on you also should have autoindent on.


1 Answers

I had this exact problem until two days ago.

There is no way to disable this, but luckily, you don't need to, because instead:

Enter insert mode with S or cc. Entering insert mode again with S will enter insert mode with the proper level of indentation, making the fact that Vim deleted the indents unimportant.

Note: I found that this trick worked for me most places. But for some reason, it did not work with Python files. I'm guessing it's something to do with the Python filetype messing with its own indentation functions, or something along those lines.

Edit:

Another trick, you can define cpoptions in a way that, if you're on a line with an indent and move the cursor, it will preserve the indent. This won't solve your problem of hitting Esc right away, but it's a related issue that might also be bothering you.

like image 174
Edan Maor Avatar answered Oct 29 '22 23:10

Edan Maor