This base action can be a single command like '<,'>s/^\s*\zs\(\S\)/#\1
. Or, in a function:
" Insert Python comment char # before first non-whitespace char
" for all Visually selected lines
func! PyComment()
'<,'>s/^\s*\zs\(\S\)/#\1
endfunc
I can see how you might run into a few gotchas, though, getting this to run by way of a mapping.
Tricky part #1: Which mapping command? So you want this to be available when lines are visually selected. That means :vmap
. Or more accurately it means :vnoremap
. Always use the "noremap" variants until you know enough about mappings to recognize a reason to do otherwise. (There are very few circumstances where it comes into play.)
Tricky part #2: What are those weird characters on the command line? When you enter the command line to, say, call a function while you're in Visual mode, vim will prepopulate it with '<,'>
. That is the range of lines covered by the Visual selection. This will also happen behind the scenes when we do the same thing as part of a mapping. Well we don't want that, we're handling the range in our function, so the first thing to do is hit Ctrl-U
(delete from cursor to beginning of line) or, in mapping speak, add <C-U>
.
Tricky part #3: How do I call a function? Well, this isn't really "tricky" but not everyone knows that user functions must be called with :call
.
Tricky part #4: It doesn't do anything? As DBK suggested in his comment it's common for people to forget that the mapping must include the carriage return that submits everything for execution. So make the last thing you add to the mapping <CR>
.
That gives us
vnoremap X :<C-U>call PyComment()<CR>
(Where X
is whatever key(s) you want to use for the mapping.)
<CR>
at the end of your mapping, but can you clarify why any of the many other QAs we have on comments dont solve your problem? Which part of:help map
is unclear? What isn’t working for you? I think I can answer but it would be helpful to know what direction to go, and I’d be thoroughly surprised if this wasn’t a dupe.