How to remove multiple blank lines in sequence with vim?

0

I have the following problem, I have a file with all messy code, many blank lines. I've tried removing the blank lines according to the post post on line deletion , but it removed all blank lines. I wanted to leave at least one blank line between each line of the code.

    
asked by anonymous 14.06.2017 / 16:41

2 answers

3

Sorry for my poor Portuguese. I used the google translator. Edit any bad grammar you see:)

You can use the following command:

:%s/^$\n^$

This tells vim to remove any occurrence of two empty rows close to each other. Usually, you'd like to use

:%s/^$\n^$//g

To end the command, but we do not need the /g option because there can only be one match per line, and we do not need diagonal bars, since vim does not require this.

    
14.06.2017 / 17:56
0

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" , .

    
30.08.2017 / 15:50