I am using following mapping. The command works fine but when I open a new file, all the empty lines are highlighted. Could you please check my mapping?

vnoremap <leader>n :g/^$/d<CR><Esc>

Thank you!

2 Answers 2


If you don't want your substitution to impact hlsearch, you can execute it within a function, which effectively creates a kind of bubble (a closure) around the commands in its body:

function! Trim() range
    execute a:firstline .. ',' .. a:lastline .. 'g/^$/d'
xnoremap <leader>n :call Trim()<CR>

Note that, while this solution is slightly more involved than the other one, it has the advantage of leaving the search register completely untouched: you don't get the unwanted ^$ but you don't get random garbage either, which is a lot cleaner and makes the search register actually reusable.

See :help function-range.

  • this works quite well, thank you very much Feb 14 at 17:55

Your command is good but it set the search register / to ^$ that highlight the empty lines if hlsearch is set.

To avoid that you could do:

vnoremap <leader>n :g/^$/d<CR>:let @/='h6d4o9kz'<CR><Esc>
  • 1
    "search register".
    – romainl
    Feb 13 at 6:22
  • @romainl Thanks :-) Feb 13 at 6:34
  • 1
    Thank you @VivianDeSmedt, used romainl solution given it seems more robust. Feb 14 at 17:55
  • Indeed I like the fact that it doesn't affect the search register (/). I have also learned something :-) Feb 14 at 17:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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