General solution
I would make use of :help function-search-undo
and extract the commands into a :function
. This won't clobber the current search pattern, and therefore also doesn't affect search highlighting. To be fully neutral, you just have to remove the used substitution pattern from the search history (via histdel()
):
function! MakeHeading()
normal! Vyp
s/./=/g
call histdel('search', -1)
endfunction
nnoremap <leader>= :call MakeHeading()<CR>
Note that I've also simplified the visual selection handling: As V
always selects the entire line, you don't need to go to the first column (^
), neither is the reselection necessary; we can just let :substitute
work on the current (pasted) line.
Alternative implementation
That reminds me that the canonical implementation of this functionality uses the :help v_r
command, and this indeed requires a re-selection:
nnoremap <leader>= Vyp0v$r=
As there's no pattern involved here, search highlighting is totally unaffected by it :-)