[vim] What's a quick way to comment/uncomment lines in Vim?

I have a Ruby code file open in vi, there are lines commented out with #:

class Search < ActiveRecord::Migration
  def self.up
    # create_table :searches do |t|
    #   t.integer :user_id
    #   t.string :name
    #   t.string :all_of
    #   t.string :any_of
    #   t.string :none_of
    #   t.string :exact_phrase
    # 
    #   t.timestamps
    # end
  end

  def self.down
    # drop_table :searches
  end
end

Say I want to uncomment all the lines in the first def ... end section. What's an efficient way to do that in Vim?

In general, I'm looking for an easy and fluid way to comment and uncomment lines. Here I'm dealing with Ruby code, but it could be JavaScript (//) or Haml (-#).

This question is related to vim comments

The answer is


There are several vim plugins like Tcomment and nerdcommenter available.

I use tcomment for commenting purposes.

gcc: It will will toggle comment on the current line. v{motion}gc: It will toggle commenting a range of lines visually selected

Example: v3jgc will toggle region of 3 lines.

These commands can work for working with comments in any language.


Even though this question already has a ton of answers I still thought I would give a shoutout to a small plugin I wrote: commentify.

Commentify uses the commentstring setting to decide how to comment out a block of code, so you don't have to keep a mapping of different comment types in your configuration, and supports both line based comments (eg, //) and block comments (eg, /* */).

It also maps the same shortcut (defaults to ctrl+c) for both commenting and uncommenting the block, so you don't have to remember two mappings or a complex set of commands.


This solution maps / to commenting and ? to uncommenting (comment toggling using the single mapping is too complex to implement properly). It takes comment strings from VIM's builtin commentstring option which is populated from files like /usr/share/vim/vim*/ftplugin/*.vim if filetype plugin on is declared.

filetype plugin on
autocmd FileType * let b:comment = split(&commentstring, '%s', 1)
autocmd FileType * execute "map <silent> <Leader>/ :normal 0i" . b:comment[0] . "<C-O>$" . b:comment[1] . "<C-O>0<CR>"
autocmd FileType * execute "map <silent> <Leader>? :normal $" . repeat('x', strlen(b:comment[1])) . "0" . strlen(b:comment[0]) . "x<CR>"

Yes, there are 33 (mostly repetitive) answers already to this question.

Here is another approach to how to comment lines out in Vim: motions. The basic idea is to comment or uncomment lines out using the same method as yanking a paragraph by typing yip or deleting 2 lines by typing dj.

This approach will let you do things like:

  • ccj to comment the next 2 lines out, and cuk to uncomment them;

  • cci{ to comment a block out, and cui{ to uncomment it;

  • ccip to comment a whole paragraph out, and cuip to uncomment it.

  • ccG to comment everything out down to the last line, and cugg to uncomment everything up to the first line.

All you need are 2 functions that operate over motions, and 2 mappings for each function. First, the mappings:

nnoremap <silent> cc  :set opfunc=CommentOut<cr>g@
vnoremap <silent> cc  :<c-u>call  CommentOut(visualmode(), 1)<cr>
nnoremap <silent> cu  :set opfunc=Uncomment<cr>g@
vnoremap <silent> cu  :<c-u>call  Uncomment(visualmode(), 1)<cr>

(See the manual about the g@ operator and the operatorfunc variable.)

And now the functions:

function! CommentOut(type, ...)
  if a:0
    silent exe "normal!  :'<,'>s/^/#/\<cr>`<"
  else
    silent exe "normal!  :'[,']s/^/#/\<cr>'["
  endif
endfunction

function! Uncomment(type, ...)
  if a:0
    silent exe "normal!  :'<,'>s/^\\(\\s*\\)#/\\1/\<cr>`<"
  else
    silent exe "normal!  :'[,']s/^\\(\\s*\\)#/\\1/\<cr>`["
  endif
endfunction

Modify the regular expressions above to suit your taste as to where the # should be:


Starting with the ideas in answers here, I started my own comment function. It toggles comments on and off. It can handle things like //print('blue'); //this thing is blue and just toggles the first comment. Furthermore it adds comments and a single space just where the first non whitespace is and not at the very start of the line. Aditionally it doesn't unnecessarily copy the whitespaces, but uses zooms (:h \zs for help) to avoid this extra work, when commenting and indented line. Hope it helps some minimalists out there. Suggestions are welcome.

" these lines are needed for ToggleComment()
autocmd FileType c,cpp,java      let b:comment_leader = '//'
autocmd FileType arduino         let b:comment_leader = '//'
autocmd FileType sh,ruby,python  let b:comment_leader = '#'
autocmd FileType zsh             let b:comment_leader = '#'
autocmd FileType conf,fstab      let b:comment_leader = '#'
autocmd FileType matlab,tex      let b:comment_leader = '%'
autocmd FileType vim             let b:comment_leader = '"'

" l:pos   --> cursor position
" l:space --> how many spaces we will use b:comment_leader + ' '

function! ToggleComment()
    if exists('b:comment_leader')
        let l:pos = col('.')
        let l:space = ( &ft =~ '\v(c|cpp|java|arduino)' ? '3' : '2' )
        if getline('.') =~ '\v(\s*|\t*)' .b:comment_leader
            let l:space -= ( getline('.') =~ '\v.*\zs' . b:comment_leader . '(\s+|\t+)@!' ?  1 : 0 )
            execute 'silent s,\v^(\s*|\t*)\zs' .b:comment_leader.'[ ]?,,g'
            let l:pos -= l:space
        else
            exec 'normal! 0i' .b:comment_leader .' '
            let l:pos += l:space
        endif
        call cursor(line("."), l:pos)
    else
        echo 'no comment leader found for filetype'
    end
endfunction

nnoremap <Leader>t :call ToggleComment()<CR>
inoremap <Leader>t <C-o>:call ToggleComment()<CR>
xnoremap <Leader>t :'<,'>call ToggleComment()<CR>

This simple snippet is from my .vimrc:

function! CommentToggle()
    execute ':silent! s/\([^ ]\)/\/\/ \1/'
    execute ':silent! s/^\( *\)\/\/ \/\/ /\1/'
endfunction

map <F7> :call CommentToggle()<CR>

It's for //-Comments, but you can adapt it easily for other characters. You could use autocmd to set a leader as jqno suggested.

This is a very simple and efficient way working with ranges and visual mode naturally.


I personally don't like a comment "toggle" function, as it will destroy comments wich are already included in the code. Also, I want to have the comment char appear on the far left, always, so I can easily see comment blocks. Also I want this to work nested (if I first comment out a block and later an enclosing block). Therefore, I slightly changed one of the solutions. I use F5 to comment and Shift-F5 to uncomment. Also, I added a /g at the end of the s/ command:

autocmd FileType c,cpp,java,scala let b:comment_leader = '//'
autocmd FileType sh,ruby,python   let b:comment_leader = '#'
autocmd FileType conf,fstab       let b:comment_leader = '#'
autocmd FileType tex              let b:comment_leader = '%'
autocmd FileType mail             let b:comment_leader = '>'
autocmd FileType vim              let b:comment_leader = '"'
autocmd FileType nasm             let b:comment_leader = ';'

function! CommentLine()
    execute ':silent! s/^\(.*\)/' . b:comment_leader . ' \1/g'
endfunction

function! UncommentLine()
    execute ':silent! s/^' . b:comment_leader . ' //g'
endfunction

map <F5> :call CommentLine()<CR>
map <S-F5> :call UncommentLine()<CR>

In VIM:

1- Enter visual mode by presssing v.

2- Use arrows to select the block you want to comment.

3- Press :

4- Type 's/^/#'

To remove comments just replace step 4 with:

4- Type 's/^#//'


If you already know the line numbers, then n,ms/# // would work.


I combined Phil and jqno's answer and made untoggle comments with spaces:

autocmd FileType c,cpp,java,scala let b:comment_leader = '//'
autocmd FileType sh,ruby,python   let b:comment_leader = '#'
autocmd FileType conf,fstab       let b:comment_leader = '#'
autocmd FileType tex              let b:comment_leader = '%'
autocmd FileType mail             let b:comment_leader = '>'
autocmd FileType vim              let b:comment_leader = '"'
function! CommentToggle()
    execute ':silent! s/\([^ ]\)/' . escape(b:comment_leader,'\/') . ' \1/'
    execute ':silent! s/^\( *\)' . escape(b:comment_leader,'\/') . ' \?' . escape(b:comment_leader,'\/') . ' \?/\1/'
endfunction
map <F7> :call CommentToggle()<CR>

how it works:

Lets assume we work with #-comments.

The first command s/\([^ ]\)/# \1/ searches for the first non-space character [^ ] and replaces that with # +itself. The itself-replacement is done by the \(..\) in the search-pattern and \1 in the replacement-pattern.

The second command s/^\( *\)# \?# \?/\1/ searches for lines starting with a double comment ^\( *\)# \?# \? (accepting 0 or 1 spaces in between comments) and replaces those simply with the non-comment part \( *\) (meaning the same number of preceeding spaces).

For more details about vim patterns check this out.


There is this life changing plugin by tpope called vim-commentary

https://github.com/tpope/vim-commentary

This plugin provides:

  • Sanity
  • Properly indented comments
  • Does not comment out empty/unnecessary lines

Usage:

  • Install via Vundle (or Pathogen I guess).
  • Highlight your text and press : which will show as :<,'>
  • Type Commentary here :<,'>Commentary and press Enter.
  • Boom. Your done bud.

I like /* ... */ (C ansi comments), so here it is my trick for you. You can adapt it to use in different cases, of course.


Comment with /* ... */

Select the text (go to the begin, start visual block, jump with }):

<c-V>}

Type the command to be applied in the selection

:norm i/* <c-v><esc>$a */

Command will look like: :'<,'>norm i /* ^[$a */

See (i*) for details.


Uncomment the /* ... */

Select the text (as before, or other way you like):

<c-V>}

Type the command to be applied in the selection

:norm :s-\s*/\*\s*-<c-v><enter>$bbld$

Command will look like: :'<,'>norm :s-\s*/\*\s*-^M$bbld$

See (ii*) for details.


Result

Effect is comments line by line:

Comment block
Comment block
Comment block

Becomes (and vice-versa):

/* Comment block */
/* Comment block */
/* Comment block */

Its better to save it as some map or @reg in your .vimrc, because it's a lot to type. If you prefer a single /* and */ to the whole block, use:

Comment with a single /* */ the whole block

Save it in a register by recording with, say, qc, then, at the beginning of a paragraph to comment:

v}di/*  */<esc>hhhp

and don't forget q again, to finish the record.

See (iii*) for details.


Uncomment a single /* */ from a block

Save it in register, say, @u. Put your cursor anywhere inside the block, and:

?/\*<enter>xx/\*/<enter>xx

Save the register by finishing q command.

See (iv*) for details.


Result

Effect is a single comment for multiple lines:

Comment block
Comment block
Comment block

Becomes (and vice-versa):

/* Comment block
Comment block
Comment block */

Explanations

(i*) It works by using norm which applies the same command repeatedly in every selected line. The command simply insert a /*, finds the end of that line and finishes by inserting a */

:norm i/* <c-v><esc>$a */

(ii*) It also uses norm to repeat the search/replace on every line. Search for spaces /* spaces and replace by nothing. After that, finds the end of the line, back two words, right a letter, delete to the end.

:norm :s-\s*/\*\s*-<c-v><enter>$bbld$

(iii*) Selects the paragraph by v}, delete it, insert a comment open and close, move to its middle and paste the deleted block.

v}di/*  */<esc>hhhp

(iv*) Anywhere in the middle, finds backwards a /*, deletes it; finds forward a */, deletes it.

?/\*<enter>xx/\*/<enter>xx

I like to use the tcomment plugin: http://www.vim.org/scripts/script.php?script_id=1173

I have mapped gc and gcc to comment a line or a highlighted block of code. It detects the file type and works really well.


: %s/^/ \ / \ / /g

remove the sapces between the characters and Use this command to comment .C or CPP files


How to uncomment the following three lines in vi:

#code code
#code
#code code code

Place the cursor over the upper left # symbol and press CtrlV. This puts you in visual block mode. Press the down arrow or J three times to select all three lines. Then press D. All the comments disappear. To undo, press U.

How to comment the following three lines in vi:

code code
code
code code code

Place the cursor over the upper left character, press CtrlV. This puts you in visual block mode. Press ? or J three times to select all three lines. Then press:

I//Esc

That's a capital I, //, and Escape.

When you press ESC, all the selected lines will get the comment symbol you specified.


I mark the first and last lines (ma and mb), and then do :'a,'bs/^# //


A few regular Vim commands do not work with my setup on Windows. Ctrl + v and Ctrl + q are some of them. I later discovered the following methods worked to uncomment lines.

Given

Some indented comments

   # Practice in Vim
   # Practice in Vim
   # Practice in Vim
   # Practice in Vim
   # Practice in Vim
   # Practice in Vim
   # Practice in Vim

The following approaches remove the # symbol and preserve indents.

Approaches

Move the cursor to the first comment (arrows or h, j, k, l)

Special Visual Mode (faster)

  • Ctrl + Shift + v to enter special visual mode
  • js to choose the vertical lines.
  • l to include horizontal characters (optional)
  • x to delete the block

Search/Replace + Regex

  • Choose text with regular visual mode, i.e. Shift + v
  • Type :. You'll get this prompt '<,'>.
  • Type regex, e.g. s/#// substitutes the hash with nothing.
    (Optional: type s/# // to include the space).
  • Enter

g mode

  • Choose text with regular visual mode, i.e. Shift + v
  • Type :. You'll get this prompt '<,'>.
  • Give a command. Type g/#/norm! ^x.
    (Optional: type g/#/norm! ^xx to include the space).
  • Enter

Results

    Practice in Vim
    Practice in Vim
    Practice in Vim
    Practice in Vim
    Practice in Vim
    Practice in Vim
    Practice in Vim

See Also

  • ThePrimeagen's tutorial on g commands.
  • Post on removing indented comments
  • Post on how to quickly comment w/Vim

I use vim-multiple-cursors for this.

  1. To select the region, go to the first character of the first or last line of the region to be commented out by pressing 0 (it's zero, not letter "o"). Then press V and select the region using J, K or up and down arrow keys.
  2. Then put a virtual cursor on each line of the selection by pressing CtrlN.
  3. Then press I to simultaneously edit each line of the selection.

Press ctrl+v then use ? or ? to select the number of lines to comment. Then press shift+I, press # and then ESC. This will comment out the number of lines you have selected.

The opposite for uncomment lines.


I have the following in my .vimrc:

" Commenting blocks of code.
augroup commenting_blocks_of_code
  autocmd!
  autocmd FileType c,cpp,java,scala let b:comment_leader = '// '
  autocmd FileType sh,ruby,python   let b:comment_leader = '# '
  autocmd FileType conf,fstab       let b:comment_leader = '# '
  autocmd FileType tex              let b:comment_leader = '% '
  autocmd FileType mail             let b:comment_leader = '> '
  autocmd FileType vim              let b:comment_leader = '" '
augroup END
noremap <silent> ,cc :<C-B>silent <C-E>s/^/<C-R>=escape(b:comment_leader,'\/')<CR>/<CR>:nohlsearch<CR>
noremap <silent> ,cu :<C-B>silent <C-E>s/^\V<C-R>=escape(b:comment_leader,'\/')<CR>//e<CR>:nohlsearch<CR>

Now you can type ,cc to comment a line and ,cu to uncomment a line (works both in normal and visual mode).

(I stole it from some website many years ago so I can't completely explain how it works anymore :). There is a comment where it is explained.)


To uncomment the whole file:

  1. Esc exits insert mode
  2. gg goes to first char on first line
  3. ctrl+V or ctrl+shift+v selects current char
  4. G or shift+g goes to last line
  5. x deletes selection

I personally wanted commenting a-la Visual Studio. I've gotten so used to it at work that it has taken over my muscle memory (using vsvim). Use shift+v select lines you want and then press ctrl+k, ctrl+c to comment or Ctrl+k, Ctrl+u to uncomment.

:vnoremap <C-k><C-c> :norm i//<Cr>
:vnoremap <C-k><C-u> :s/\/\///g<Cr>:noh<Cr>

This answer is most useful if you are unable to install plugins but you still want your comment characters to follow existing indentation levels.

This answer is here to 1) show the correct code to paste into a .vimrc to get vim 7.4+ to do block commenting/uncommenting while keeping indentation level with 1 shortcut in visual mode and 2) to explain it. Here is the code:

let b:commentChar='//'
autocmd BufNewFile,BufReadPost *.[ch]    let b:commentChar='//'
autocmd BufNewFile,BufReadPost *.cpp    let b:commentChar='//'
autocmd BufNewFile,BufReadPost *.py    let b:commentChar='#'
autocmd BufNewFile,BufReadPost *.*sh    let b:commentChar='#'
function! Docomment ()
  "make comments on all the lines we've grabbed
  execute '''<,''>s/^\s*/&'.escape(b:commentChar, '\/').' /e'
endfunction
function! Uncomment ()
  "uncomment on all our lines
  execute '''<,''>s/\v(^\s*)'.escape(b:commentChar, '\/').'\v\s*/\1/e'
endfunction
function! Comment ()
  "does the first line begin with a comment?
  let l:line=getpos("'<")[1]
  "if there's a match
  if match(getline(l:line), '^\s*'.b:commentChar)>-1
    call Uncomment()
  else
    call Docomment()
  endif
endfunction
vnoremap <silent> <C-r> :<C-u>call Comment()<cr><cr>

How it works:

  • let b:commentChar='//' : This creates a variable in vim. the b here refers to the scope, which in this case is contained to the buffer, meaning the currently opened file. Your comment characters are strings and need to be wrapped in quotes, the quotes are not part of what will be substituted in when toggling comments.

  • autocmd BufNewFile,BufReadPost *... : Autocommands trigger on different things, in this case, these are triggering when a new file or the read file ends with a certain extension. Once triggered, the execute the following command, which allows us to change the commentChar depending on filetype. There are other ways to do this, but they are more confusing to novices (like me).

  • function! Docomment() : Functions are declared by starting with function and ending with endfunction. Functions must start with a capital. the ! ensures that this function overwrites any previous functions defined as Docomment() with this version of Docomment(). Without the !, I had errors, but that might be because I was defining new functions through the vim command line.

  • execute '''<,''>s/^\s*/&'.escape(b:commentChar, '\/').' /e' : Execute calls a command. In this case, we are executing substitute, which can take a range (by default this is the current line) such as % for the whole buffer or '<,'> for the highlighted section. ^\s* is regex to match the start of a line followed by any amount of whitespace, which is then appended to (due to &). The . here is used for string concatenation, since escape() can't be wrapped in quotes. escape() allows you to escape character in commentChar that matches the arguments (in this case, \ and /) by prepending them with a \. After this, we concatenate again with the end of our substitute string, which has the e flag. This flag lets us fail silently, meaning that if we do not find a match on a given line, we won't yell about it. As a whole, this line lets us put a comment character followed by a space just before the first text, meaning we keep our indentation level.

  • execute '''<,''>s/\v(^\s*)'.escape(b:commentChar, '\/').'\v\s*/\1/e' : This is similar to our last huge long command. Unique to this one, we have \v, which makes sure that we don't have to escape our (), and 1, which refers to the group we made with our (). Basically, we're matching a line that starts with any amount of whitespace and then our comment character followed by any amount of whitespace, and we are only keeping the first set of whitespace. Again, e lets us fail silently if we don't have a comment character on that line.

  • let l:line=getpos("'<")[1] : this sets a variable much like we did with our comment character, but l refers to the local scope (local to this function). getpos() gets the position of, in this case, the start of our highlighting, and the [1] means we only care about the line number, not other things like the column number.

  • if match(getline(l:line), '^\s*'.b:commentChar)>-1 : you know how if works. match() checks if the first thing contains the second thing, so we grab the line that we started our highlighting on, and check if it starts with whitespace followed by our comment character. match() returns the index where this is true, and -1 if no matches were found. Since if evaluates all nonzero numbers to be true, we have to compare our output to see if it's greater than -1. Comparison in vim returns 0 if false and 1 if true, which is what if wants to see to evaluate correctly.

  • vnoremap <silent> <C-r> :<C-u>call Comment()<cr><cr> : vnoremap means map the following command in visual mode, but don't map it recursively (meaning don't change any other commands that might use in other ways). Basically, if you're a vim novice, always use noremap to make sure you don't break things. <silent> means "I don't want your words, just your actions" and tells it not to print anything to the command line. <C-r> is the thing we're mapping, which is ctrl+r in this case (note that you can still use C-r normally for "redo" in normal mode with this mapping). C-u is kinda confusing, but basically it makes sure you don't lose track of your visual highlighting (according to this answer it makes your command start with '<,'> which is what we want). call here just tells vim to execute the function we named, and <cr> refers to hitting the enter button. We have to hit it once to actually call the function (otherwise we've just typed call function() on the command line, and we have to hit it again to get our substitutes to go through all the way (not really sure why, but whatever).

Anyway, hopefully this helps. This will take anything highlighted with v, V, or C-v, check if the first line is commented, if yes, try to uncomment all highlighted lines, and if not, add an extra layer of comment characters to each line. This is my desired behavior; I did not just want it to toggle whether each line in the block was commented or not, so it works perfectly for me after asking multiple questions on the subject.


I use Tim Pope's vim-commentary plugin.


To Comment A Line (For All Languages):

  • noremap <silent> ,// :call CommentLine() <CR>

We can call it with number of lines and in visual mode too, it works. Like : To comment four lines use 4,// and to uncomment use 4,/.

To Uncomment A Line (For All Languages):

  • noremap <silent> ,/ :call UnCommentLine() <CR>

If You want to add new symbol[comment] then add a list and add some lines in function. If you want to add a language that has the comment symbol that already defined in one of the lists just add your language name in the corresponding list (To Get correct name: Open your file in vim and use :set ft to get the correct name for your language).

Definition of CommentLine()

function! CommentLine() let slash_ft_list = ['c' , 'cpp', 'java', 'scala' , 'systemverilog' , 'verilog' , 'verilog_systemverilog'] let hash_ft_list = ['sh' , 'ruby' , 'python' , 'csh' , 'conf' , 'fstab' , 'perl'] let perct_ft_list = ['tex'] let mail_ft_list = ['mail'] let quote_ft_list = ['vim'] if (index(slash_ft_list, &ft) != -1) :norm I// elseif (index(hash_ft_list, &ft) != -1) :norm I# elseif (index(perct_ft_list, &ft) != -1) :norm I% elseif (index(mail_ft_list, &ft) != -1) :norm I> elseif (index(quote_ft_list, &ft) != -1) :norm I" endif endfunction

Definition of UnCommentLine()

function! UnCommentLine() let slash_ft_list = ['c' , 'cpp', 'java', 'scala' , 'systemverilog' , 'verilog' , 'verilog_systemverilog'] let hash_ft_list = ['sh' , 'ruby' , 'python' , 'csh' , 'conf' , 'fstab' , 'perl'] let perct_ft_list = ['tex'] let mail_ft_list = ['mail'] let quote_ft_list = ['vim'] if (index(slash_ft_list, &ft) != -1) :norm ^2x elseif (index(hash_ft_list, &ft) != -1) :norm ^x elseif (index(perct_ft_list, &ft) != -1) :norm ^x elseif (index(mail_ft_list, &ft) != -1) :norm ^x elseif (index(quote_ft_list, &ft) != -1) :norm ^x endif endfunction


"comment (cc) and uncomment (cu) code 
noremap   <silent> cc      :s,^\(\s*\)[^# \t]\@=,\1# ,e<CR>:nohls<CR>zvj
noremap   <silent> cu      :s,^\(\s*\)# \s\@!,\1,e<CR>:nohls<CR>zvj

You can comment/uncomment single or multiple lines with #. To do multiple lines, select the lines then type cc/cu shortcut, or type a number then cc/cu, e.g. 7cc will comment 7 lines from the cursor.

I got the orignal code from the person on What's the most elegant way of commenting / uncommenting blocks of ruby code in Vim? and made some small changes (changed shortcut keys, and added a space after the #).


@CMS's solution is the most "vim native" way to comment in/out lines. In @CMS's second step, after CtrlV, you could also use r# to add comments or x to delete them. Drew Neil's Practical Vim, page 46, explains this technique well.

Another good option is to use an ex mode command. :[range]normali##?. Obviously, to save keystrokes with this one, you'll need to comment out 15+ lines.


mark a text area by mark command say ma and mb type command: :'a,'bg/(.*)/s////\1/

You can see an example of this kind of test manipulation at http://bknpk.ddns.net/my_web/VIM/vim_shell_cmd_on_block.html


:g/.spare[1-9].*/,+2s/^/\/\//

The above code will comment out all the lines that contain "spare" and a number after that plus it will comment two lines more from the line in which that was found. For more such uses visit : http://vim.wikia.com/wiki/Search_and_replace#Details


I use vim 7.4 and this works for me.
Assuming we are commenting/uncommenting 3 lines.

To comment:

if the line has no tab/space at the beginning:
ctrl + V then jjj then shift + I (cappital i) then //then esc esc
if the line has tab/space at the beginning you still can do the above or swap for c:
ctrl + V then jjj then c then //then esc esc

To uncomment:

if the lines have no tab/space at the beginning:
ctrl + V then jjj then ll (lower cap L) then c

if the lines have tab/space at the beginning, then you space one over and esc
ctrl + V then jjj then ll (lower cap L) then c then space then esc


Very good question, but not so many good answers imho. First, I would say, using block insert mode is not an easy solution here, just too many keystrokes, so obviously it must work on selected lines to improve performance of code editing. Another point which nobody mentions : where the comment sign should be put - in the very beginning of the line or before actual text? It is a matter of taste probably, but my opinion, it should be put before the text to keep the code readable: when the comment sign is put in the very line beginning it breaks the visual consistence of indented code, so it looks like a bulleted list. With that in mind, I've ended up with following solution (I make example for # comment). In my vimrc:

vnoremap 1 :s:^\(\s*\)\([^#\t ]\):\1#\2:e<CR>
vnoremap 2 :s:^\(\s*\)#\(\s*\):\1\2:e<CR>

Key 1 inserts # before the text (after white space) in every selected line. It checks if there is already #, not to insert # twice. And also ignores empty lines.
Key 2 deletes one #. It also keeps the comments on the right side of line safe.


Update: here is an example, how to make file type dependent toggle comment command. To learn more about these thing read: http://learnvimscriptthehardway.stevelosh.com/chapters/14.html

Just to make it work, put the following lines in your .vimrc file.

" build the whole regex search/replace command
function! Build()
    let b:Comment_ON='''<,''>s:^\(\s*\)\([^\t ]\):\1' . b:cs . '\2:e'
    let b:Comment_OFF='''<,''>s:^\(\s*\)' . b:cs . '\(\s*\):\1\2:e'
endfunction

" run this group on Filetype event
augroup SetCS
    autocmd!
    "default comment sign
    autocmd FileType * let b:cs='--'
    "detect file type and assign comment sign
    autocmd FileType python,ruby let b:cs='#'
    autocmd FileType c,cpp,java,javascript,php let b:cs = '\/\/'
    autocmd FileType vim let b:cs='"'
    autocmd FileType * call Build()
augroup END

vnoremap 1 :<C-u>execute b:Comment_ON<CR>
vnoremap 2 :<C-u>execute b:Comment_OFF<CR>

For those tasks I use most of the time block selection.

Put your cursor on the first # character, press CtrlV (or CtrlQ for gVim), and go down until the last commented line and press x, that will delete all the # characters vertically.

For commenting a block of text is almost the same:

  1. First, go to the first line you want to comment, press CtrlV. This will put the editor in the VISUAL BLOCK mode.
  2. Then using the arrow key and select until the last line
  3. Now press ShiftI, which will put the editor in INSERT mode and then press #. This will add a hash to the first line.
  4. Then press Esc (give it a second), and it will insert a # character on all other selected lines.

For the stripped-down version of vim shipped with debian/ubuntu by default, type : s/^/# in the third step instead (any remaining highlighting of the first character of each line can be removed with :nohl).

Here are two small screen recordings for visual reference.

Comment: Comment

Uncomment: Uncomment


With 30 answers ahead of me, I'll try to give an even easier solution: Insert a # at the beginning of the line. Then go down a line and press dot (.). To repeat, do j,.,j,., etc...To uncomment, remove a # (you can hit x over the #), and do the reverse using k,.,etc...


Sometimes I'm shelled into a remote box where my plugins and .vimrc cannot help me, or sometimes NerdCommenter gets it wrong (eg JavaScript embedded inside HTML).

In these cases a low-tech alternative is the built-in norm command, which just runs any arbitrary vim commands at each line in your specified range. For example:

Commenting with #:

1. visually select the text rows (using V as usual)
2. :norm i#

This inserts "#" at the start of each line. Note that when you type : the range will be filled in, so it will really look like :'<,'>norm i#

Uncommenting #:

1. visually select the text as before (or type gv to re-select the previous selection)
2. :norm x

This deletes the first character of each line. If I had used a 2-char comment such as // then I'd simply do :norm xx to delete both chars.

If the comments are indented as in the OP's question, then you can anchor your deletion like this:

:norm ^x

which means "go to the first non-space character, then delete one character". Note that unlike block selection, this technique works even if the comments have uneven indentation!

Note: Since norm is literally just executing regular vim commands, you're not limited to comments, you could also do some complex editing to each line. If you need the escape character as part of your command sequence, type ctrl-v then hit the escape key (or even easier, just record a quick macro and then use norm to execute that macro on each line).

Note 2: You could of course also add a mapping if you find yourself using norm a lot. Eg putting the following line in ~/.vimrc lets you type ctrl-n instead of :norm after making your visual selection

vnoremap <C-n> :norm

Note 3: Bare-bones vim sometimes doesn't have the norm command compiled into it, so be sure to use the beefed up version, ie typically /usr/bin/vim, not /bin/vi

(Thanks to @Manbroski and @rakslice for improvements incorporated into this answer)


I've come up with a simple addition to my .vimrc file which works pretty well and can be extended easily. You simply add a new filetype to the comment_map and its comment leader.

I added a mapping to normal and visual modes, but you can remap to anything you like. I prefer only to have a 'toggle' style function. One bears having multiple mappings etc.

let s:comment_map = { 
    \   "c": '\/\/',
    \   "cpp": '\/\/',
    \   "go": '\/\/',
    \   "java": '\/\/',
    \   "javascript": '\/\/',
    \   "lua": '--',
    \   "scala": '\/\/',
    \   "php": '\/\/',
    \   "python": '#',
    \   "ruby": '#',
    \   "rust": '\/\/',
    \   "sh": '#',
    \   "desktop": '#',
    \   "fstab": '#',
    \   "conf": '#',
    \   "profile": '#',
    \   "bashrc": '#',
    \   "bash_profile": '#',
    \   "mail": '>',
    \   "eml": '>',
    \   "bat": 'REM',
    \   "ahk": ';',
    \   "vim": '"',
    \   "tex": '%',
    \ }

function! ToggleComment()
    if has_key(s:comment_map, &filetype)
        let comment_leader = s:comment_map[&filetype]
        if getline('.') =~ "^\\s*" . comment_leader . " " 
            " Uncomment the line
            execute "silent s/^\\(\\s*\\)" . comment_leader . " /\\1/"
        else 
            if getline('.') =~ "^\\s*" . comment_leader
                " Uncomment the line
                execute "silent s/^\\(\\s*\\)" . comment_leader . "/\\1/"
            else
                " Comment the line
                execute "silent s/^\\(\\s*\\)/\\1" . comment_leader . " /"
            end
        end
    else
        echo "No comment leader found for filetype"
    end
endfunction


nnoremap <leader><Space> :call ToggleComment()<cr>
vnoremap <leader><Space> :call ToggleComment()<cr>

Note:

I don't use any callbacks or hooks into the file types/loading, because I find they slow down Vim's startup more than the .vimrc static function/map does but that's just my preference. I've also tried to keep it simple and performant. If you do use autocommands you need to be sure to put them in an autocommand group or else the callbacks get added to the filetype multiple times per-file loaded and cause a lot of performance degradation.


I use comments.vim from Jasmeet Singh Anand (found on vim.org),

It works with C, C++, Java, PHP[2345], proc, CSS, HTML, htm, XML, XHTML, vim, vimrc, SQL, sh, ksh, csh, Perl, tex, fortran, ml, caml, ocaml, vhdl, haskel, and normal files

It comments and un-comments lines in different source files in both normal and visual mode

Usage:

  • CtrlC to comment a single line
  • CtrlX to un-comment a single line
  • ShiftV and select multiple lines, then CtrlC to comment the selected multiple lines
  • ShiftV and select multiple lines, then CtrlX to un-comment the selected multiple lines

Specify which lines to comment in vim:

Reveal the line numbers:

:set number

then

:5,17s/^/#/     this will comment out line 5-17

or this:

:%s/^/#/        will comment out all lines in file

Here is how I do it:

  1. Go to first character on the first line you want to comment out.

  2. Hit Ctrl+q in GVIM or Ctrl+v in VIM, then go down to select first character on the lines to comment out.

  3. Then press c, and add the comment character.

Uncommenting works the same way, just type a space instead of the comment character.


I use EnhancedCommentify. It comments everything I needed (programming languages, scripts, config files). I use it with visual-mode bindings. Simply select text you want to comment and press co/cc/cd.

vmap co :call EnhancedCommentify('','guess')<CR>
vmap cc :call EnhancedCommentify('','comment')<CR>
vmap cd :call EnhancedCommentify('','decomment')<CR> 

The quickest and the most intuitive method of them all is to remap ) for walk-down-commenting of lines, and then ( for walk-up-uncommenting. Try it and you won't go back.

In Ruby or Bash, with 2-space indents:

map ) I# <Esc>j
map ( k^2x

In C/C++ or PHP, with 4-space indents:

map ) I//  <Esc>j
map ( k^4x

Downsides are that you lose ( and ) for sentence-movement (but das can fill in there), and you'll occasionally fall back on select-and-replace or CtrlV for handling long sections. But that's pretty rare.

And for C-style, the long comments are best handled with:

set cindent
set formatoptions=tcqr

... Which combines well with using V[move]gq to redo the word-wrapping.


Toggle comments

If all you need is toggle comments I'd rather go with commentary.vim by tpope.

enter image description here

Installation

Pathogen:

cd ~/.vim/bundle
git clone git://github.com/tpope/vim-commentary.git

vim-plug:

Plug 'tpope/vim-commentary'

Vundle:

Plugin 'tpope/vim-commentary'

Further customization

Add this to your .vimrc file: noremap <leader>/ :Commentary<cr>

You can now toggle comments by pressing Leader+/, just like Sublime and Atom.


Here's a basic one-liner based on the C-v followed by I method outlined above.

This command (:Comment) adds a chosen string to the beginning of any selected lines.

command! -range -nargs=1 Comment :execute "'<,'>normal! <C-v>0I" . <f-args> . "<Esc><Esc>"

Add this line to your .vimrc to create a command that accepts a single argument and places the argument at the beginning of every line in the current selection.

E.g. if the following text is selected:

1
2

and you run this: :Comment //, the result will be:

//1
//2

Here is a section of my .vimrc:

"insert and remove comments in visual and normal mode
vmap ,ic :s/^/#/g<CR>:let @/ = ""<CR>
map  ,ic :s/^/#/g<CR>:let @/ = ""<CR>
vmap ,rc :s/^#//g<CR>:let @/ = ""<CR>
map  ,rc :s/^#//g<CR>:let @/ = ""<CR>

In normal and in visual mode, this lets me press ,ic to insert comments and,rc to remove comments.


Use Control-V to select rectangles of text: go to the first # character, type Ctrl+V, move right once, and then down, up to the end of the comments. Now type x: you're deleting all the # characters followed by one space.


You can use vim-commentary by tpope (https://github.com/tpope/vim-commentary) you can use it as following:

Enter visual mode by pressing

'v'

Then press

'j' repeatedly or e.g 4j to select 4 row

Now all you have to do with the selection is enter keys:

'gc'

This will comment out all the selection, to uncomment repead keys:

'gc'

To comment out blocks in vim:

  • press Esc (to leave editing or other mode)
  • hit ctrl+v (visual block mode)
  • use the ?/? arrow keys to select lines you want (it won't highlight everything - it's OK!)
  • Shift+i (capital I)
  • insert the text you want, e.g. %
  • press EscEsc

To uncomment blocks in vim:

  • press Esc (to leave editing or other mode)
  • hit ctrl+v (visual block mode)
  • use the ?/? arrow keys to select the lines to uncomment.

    If you want to select multiple characters, use one or combine these methods:

    • use the left/right arrow keys to select more text
    • to select chunks of text use shift + ?/? arrow key
    • you can repeatedly push the delete keys below, like a regular delete button

  • press d or x to delete characters, repeatedly if necessary