Reputation: 19112
I want to create a map for commenting one or multiple lines of code in Vim, to easily be able to temporarily comment things. For now, I've done the following, which simply inserts //
in front of all of the selected lines:
" place // at the start of current line
nmap #> ^i//<Esc>
nmap ## ^i//<Esc>
" unindent current line
nmap #< ^xx
" change indentation of multiple lines
vmap #> ^<C-v>I//<Esc>
vmap #< ^<C-v><Right>d<Esc>
This already has fairly nice functonality, but it's a bit limited to just languages with //
comments. I'd like to be able to automatically detect what the single-line comment character(s) are for the language I'm using, based on syntax highlighting rules, and use that character to (un)comment lines. I'd be okay with writing a short list of definitions, such as //
for languages in *.{c,cpp,cc,js}
, #
for *.py
, and %
for *.tex
etc.
Also, I'd like to be able to detect whether the start of a line is a comment, in the same way that the key-combination <<
only unindents code when it starts with whitespace. I'm thinking this probably needs to be done using regex, but that also depends on whether it is possible to detect if something is a comment.
I hope there are possibilities to do this.
Upvotes: 0
Views: 308
Reputation: 172638
Yes, there are many possibilities; indeed, several authors have built fully-fledged robust and configurable plugins for commenting out lines:
So, unless this is for learning purposes, or if you absolutely cannot install plugins (but if you can configure Vim there would be ways to download and install a plugin on each run), I'd highly consider using a plugin for this.
Vim already provides the 'comments'
and 'commentstring'
options for the filetype-specific comment characters. Plugins use these (at least as a fallback; some also have their own built-in list).
Upvotes: 2