2

I have some visual-mode commenting macros that should place a comment character g:CommentChar before the first non-whitespace character of each line in the selection. However, it places it right of the 0 position instead. How can I remedy this/what could be the reason for this? I'm guessing in Visual Mode ^ signifies the first highlighted character in the line?

I'd like to place comment characters before non-whitespace instead of at the beginning of line so I can preserve indent-based folding.


Here are the macros (g:CommentChar is defined in ftplugin files).

vnoremap <expr> <Leader>c ':s/^/'.g:CommentChar.'/<CR>:noh<CR>'
vnoremap <expr> <Leader>C ':s/'.g:CommentChar.'//<CR>:noh<CR>'
2

^ in s/^/.../ is a regexp, not a visual mode command. I suggest the following mappings:

vnoremap <expr> <Leader>c ':s/^\s*\zs/'.escape(g:CommentChar, '/\').'/<CR>:noh<CR>'
vnoremap <expr> <Leader>C ':s/^\s*\zs\V'.escape(g:CommentChar, '/\').'//<CR>:noh<CR>'

Better yet, you should consider using one of the commenter plugins instead of writing your own macros. They can deal with corner situations you aren't even aware of at this time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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