How do I make vim's autoindent not drop trailing spaces?

In some text editors (e.g. Kate, gedit), when auto indent is enabled, pressing return twice will leave a trailing whitespace (which I want):

if (code) {
....
....|
}

While others cater to the coding standard where trailing spaces (even in blank lines) aren't allowed:

if (code) {

....|
}

What annoys me about this is that if I arrow up after auto-indenting, the auto-indent is lost:

if (code) {
|
....
}

If I run vim and :set autoindent , I get the latter behavior.

My question is, how do I set vim to keep the trailing spaces rather than automatically removing them if they go unused?


See this hint on the vim wiki for how to have correct indention even for empty lines. If you just want to keep the previous indent (ignoring what vim calculated as the correct indent) use let ind = indent(prevnonblank(v:lnum - 1)) like explained in a comment under the same wiki entry.


I found this solution to work for me:

:inoremap <Return> <Space><BS><Return>