I'm trying to create a mapping on Vim, that behaves like the following:
First of all I select a block of code or text using on Visual mode. The I use this mapping to substitute the first column on each line for '#' effectively commenting each line.
Up until now I have the following:
vnoremap <Leader>c :normal! :s/^/#/<cr>
But for some reason it is not working. Nothing happens when I hit <Leader>c
on a block of text. On the other hand, if I have:
vnoremap <Leader>c :normal! s/^/#/<cr>
it will for example subsitute:
The grey fox.
For
/^/#/he grey fox.
Any idea on how can I solve this issue?
:normal
is an Ex command that allows to execute normal mode commands (from a custom command or function, or command-line mode in general). Your keys start off with :
, so immediately switch from normal (or here: visual) mode to command-line mode. That doesn't make sense. Just define the mapping like this:
vnoremap <Leader>c :s/^/#/<cr>
The :
will automatically insert '<,'>
for you, and that's what you want here (to operate on all selected lines). You can also define a related normal-mode mapping that works on the current (or [count]
) lines:
nnoremap <Leader>c :s/^/#/<cr>
If the highlighting disturbs you, append the :nohlsearch
command:
nnoremap <Leader>c :s/^/#/<bar>nohlsearch<cr>