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?

  • Duplicate of: stackoverflow.com/questions/30883563/vim-keeps-unindenting
    – lcd047
    Commented 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
    Commented Jun 17, 2015 at 8:57
  • Are you sure you want to keep trailing spaces?
    – romainl
    Commented 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). Commented Jun 17, 2015 at 11:00

2 Answers 2


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


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


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 you have read our privacy policy.

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