Often when you enter a blank line by pressing <CR> twice in insert mode, Vim removes the indent from the blank line and your cursor moves back to column 1. Likewise, if you position the cursor on a blank line and press letter o to open a new line below it, Vim does not open that line with any indent. Often, though, you want to use the same indent as the preceding non-blank line.
There are two ways to achieve this. If you can bear or want to have lines
in your files that have whitespace in them but nothing else, you can simply
put this in your vimrc:
- inoremap <CR> x<BS><CR>
Vim doesn't delete the indent if you type something, even if you delete
that something, and this mapping simulates your typing something even if
you didn't, and deletes it before proceeding to the next line! This
approach is not recommended, though, as it is generally considered poor
practice to have lines that contain only whitespace.
Another approach is to save the following in a .vim file in your ~/.vim/plugin (or $HOME/vimfiles/plugin on Windows) directory, or add it to your vimrc:
function! IndentIgnoringBlanks(child)
while v:lnum > 1 && getline(v:lnum-1) == ""
normal k
let v:lnum = v:lnum - 1
endwhile
if a:child == ""
if v:lnum <= 1 || ! &autoindent
return 0
elseif &cindent
return cindent(v:lnum)
else
return indent(v:lnum-1)
endif
else
exec "let indent=".a:child
return indent==-1?indent(v:lnum-1):indent
endif
endfunction
augroup IndentIgnoringBlanks
au!
au FileType * if match(&indentexpr,'IndentIgnoringBlanks') == -1 |
\ let &indentexpr = "IndentIgnoringBlanks('".
\ substitute(&indentexpr,"'","","g")."')" |
\ endif
augroup END
You can change the * in the au command at the bottom to make it apply to only the filetypes you want, or put the part after the * in after scripts instead of with the above (see :help after-directory).
It works by 'wrapping' your indentexpr in another. The script sets the indentexpr to its own function, which adjusts the cursor position and variables as if your were inserting directly after the last non-blank line, not after the blank line, and then evaluates the original indentexpr.
Ben.