10

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?

4
  • Duplicate of: stackoverflow.com/questions/30883563/vim-keeps-unindenting
    – lcd047
    Jun 17, 2015 at 7:14
  • 1
    Stack Exchange discourages posting the same question on multiple sites. If you decide to post on a different site later, you're expected to delete the original question.
    – muru
    Jun 17, 2015 at 8:57
  • Are you sure you want to keep trailing spaces?
    – romainl
    Jun 17, 2015 at 10:30
  • Maybe you want to look into using set virtualedit=all? It doesn't do what you're asking for, but it is roughly similar (see the help page). Jun 17, 2015 at 11:00

2 Answers 2

4

What you're seeing is the normal behavior of 'autoindent' which the Python indent plugin uses. See :help 'ai'. You can watch what happens to the indent as you type by executing

:set list

There is no way that I know of to make Vim automatically preserve your indent in the case you describe. Setting the I flag of 'cpoptions' doesn't help.

You can work around this problem by using the following mapping.

:inoremap <cr> <space><bs><cr>

That will cause Vim to leave an indentation of spaces when you type Enter on an empty line. I don't recommend doing that as it will leave your file cluttered with unnecessary spaces until you remove them with something like

:%s/\s\+$//

before saving the file, but you may find that less annoying than the normal indent behavior.

3

To keep the indent ... write something on that line, before moving to other lines! Otherwise, since you are a good Vim user and stay mostly in normal mode (right?), when you have to write something on that line, just go there and press S - you'll find yourself at the correct indent level and ready to type. Vim does this to avoid useless ('trailing') tabs/spaces on empty lines.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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