Vim keeps unindenting

670 views Asked by At

Vim keeps unindenting the lines I want to keep indented if I don't write anything on them... I'll give an example, where the | is the caret.

  1. Caret is indented and I press enter

    if expression:
        print("hello world")
        |
    
  2. Caret is indented on the next line, and now I press the up arrow

    if expression:
        print("hello world")
    
        |
    
  3. Now the caret isn't indented anymore, what happened?

    if expression:
        print("hello world")
    |
    

So how do I keep the indent?

3

There are 3 answers

0
Ben On BEST ANSWER

As others have pointed out, Vim intentionally removes indent of empty lines if the indent was added automatically. But, this does not happen if you have inserted any text on the line, even if you delete it. So on a case-by-case basis, just insert some text and delete it with backspace if you want to keep the indent of an empty line. A mapping also works, if you always want to keep it:

inoremap <CR> <CR>x<BS>
1
nirajkumar On

this is the expected behavior of vim . Since you have skipped the next line it assume you do not want to write in that particular block of code

0
Xavier T. On

On my installation, it keeps the indentation (for C file at least).

You should try to insert a new line using o in normal mode.

Then according the the documentation (see :help o):

When 'autoindent' is on, the indent for a new line is obtained from the previous line. When 'smartindent' or 'cindent' is on, the indent for a line is automatically adjusted for C programs.

You are probably using only the 'autoindent' option.

See :help indenting for more information.

For non C-like language, you might need to rely on the $VIMRUNTIME/indent files.

You can enable it by adding :set filetype indent on assuming your language is supported. Otherwise, you will have to write your own indent file.