0

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

3

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'
endfunction
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.

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

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>
4
  • 1
    "search register".
    – romainl
    Commented Feb 13, 2023 at 6:22
  • @romainl Thanks :-) Commented Feb 13, 2023 at 6:34
  • 1
    Thank you @VivianDeSmedt, used romainl solution given it seems more robust. Commented Feb 14, 2023 at 17:55
  • Indeed I like the fact that it doesn't affect the search register (/). I have also learned something :-) Commented Feb 14, 2023 at 17:57

Your Answer

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

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