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!
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
.
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>
/
). I have also learned something :-)
Commented
Feb 14, 2023 at 17:57