I created two functions in my ~ / .vimrc
The first is to execute commands without changing the position of the
cursor and search records, because when we locate consecutive blank lines in order to erase them, this record is stored, ie the Preserve function can be used in other situations.
The second is the function that will actually delete the blank lines.
if !exists('*Preserve')
function! Preserve(command)
" Preparation: save last search, and cursor position.
let save_cursor = getpos(".")
let old_query = getreg('/')
execute a:command
" Clean up: restore previous search history, and cursor position
call setpos('.', save_cursor)
call setreg('/', old_query)
endfunction
endif
" remove consecutive blank lines
" see Preserve function definition
fun! DelBlankLines()
keepjumps call Preserve("g/^\n\{2,}/d")
endfun
command! -nargs=0 DelBlank :call DelBlankLines()
You can even map to <leader>d
as follows:
:nnoremap <leader>d :call DelBlankLines()
NOTE: <leader>
is by default backslash, but on many systems it is set to "Comma" ,
.