Vim Tip: Comment out multiple lines

Commenting out a bunch of lines without a vim plugin:

Select your lines with VISUAL BLOCK (CTRL-V), then press I to insert before all highlighted lines. Next type your comment character, # (for python, shell, etc). Last press ESC.

I forget not frequently used, but helpful VIM commands from time to time. Why not blog it?

You can alternatively select your lines with VISUAL LINE (SHIFT-V), then type : s/^/#
This tells the selected lines that you wish to substitute the start of the line with the # char.

Advertisements

55 responses to “Vim Tip: Comment out multiple lines

  1. Nice tip.
    How do you uncomment them?

  2. Same thing…but use:
    :s/#/
    Will substitute all lines beginning with the comment ‘#’ to nothing. This has the same effect and is clearer:
    :s/^#/
    The ‘^’ denotes ‘the beginning of the line’ . In the first example it is inferred. Meaning it will not remove extra #’s if they exist elsewhere in the line.
    Thanks for stopping by! 🙂

  3. Thanks, that was helpful!

  4. how do you get your font size to normal

  5. Priscilla — I use the console based VIM. But I was able to find this: http://www.vim.org/tips/tip.php?tip_id=632

  6. I googled your tip. CTRL-V and I is great. Thanks.
    You can use CTRL-V and d to uncommet, too.

  7. Using vim mappings can make this process easier, provided your comment characters is always the same (for example, I primarily script in shell, perl and ruby, so my comment character is almost always ‘#’):

    :map <F4> I#<Esc><Esc>

    (You have to type ‘> E s c >’ as 5 characters, but you should press the F4 key to get the <F4>)

    Then, after you select your visual block to comment out, just press F4. Of course, you can substitute any key or key sequence (like Control+G) you like.

    I’m using Control+G to comment a selected block and Control+T to uncomment it:

    :map ^G I#<Esc><Esc>
    :map ^T x<Esc><Esc>

    (As above, the ^G and ^T is generated by holding down Control and typing G and T, respectively)

  8. Oh yeah, and if you want to put the mappings for ^G and ^T in your .vimrc file, you can use the special <C-G> and <C-T> key representations.

    Happy hacking!

  9. Excellent tip…exactly what I was googling for.

  10. Comment and uncomment with a single shortcut:

    map :s/^/\/\/:s/^\/\/\/\//

    (first we set // to the beginning of the line, and if it’s now 4 slashes there – remove them all)

    Anybody knows how to suppress error message?

  11. anonymous: you can use a different character in your :s, like a # or ? so you dont have to escape those ‘\’.
    James Hunt, avoid mapping ctrl-T, because thats the key for tags.

  12. Ok, here’s a new one).

    map :s@^@//@:s@^////@@e
    vmap :s@^@//@:’s@^////@@e

    Now it comments/uncomments single and multiple lines in normal and visual block selected modes. And it shows no errors.

  13. It’s been reformatted.

    map :s@^@//@:s@^////@@e
    vmap :s@^@//@:’s@^////@@e

  14. Ok, here’s a new one).

    http://pastebin.com/m3805915

    Now it comments/uncomments single and multiple lines in normal and visual block selected modes. And it shows no errors.

    PS Don’t know how to post here correctly. How to make it keep all the symbols? Please delete two previous posts.

  15. Just use the ToggleComment plugin for vim. Get it here: http://www.vim.org/scripts/script.php?script_id=955

    Put ToggleComment.vim in the $HOME/.vim/plugin/ directory.

    Put this in your .vimrc (just one example for Ruby commenting, lots of others are available in the README):
    map ,# :call CommentLineToEnd(‘# ‘)+

    That lets you use ,# (that’s a comma followed by a hash symbol) to toggle comments on one or many lines – just use visual mode for multi-line (shift-v, then arrow keys).

  16. Thanks a lot! That’s exactly what I was searching but could not find.

  17. I wanted to indent a lot of lines in an XML file. I did it by creating a macro and then running it multiple times based on your ^V I tip.

    Here is the commands I used (I prefixed the lines with line numbers so I can explain the steps afterwards):
    1) qa
    2) /^^I^I^I$
    3) mb
    4) /^^I^I^I$
    5) ^V
    6) `b
    7) I^I
    8) q
    9) 100@a

    Here is the explanation of each of the above lines:
    1) Start recording and store in register ‘a’.
    2) Search for the first line (using ^ and $ to ensure pre-indent match).
    3) Set mark ‘b’ (to be able to return here).
    4) Search for the last line.
    5) Enter visual block mode.
    6) Return to mark ‘b’ (backtick to move to column 0).
    7) Add a tab at the beginning of the line.
    8) Stop recording.
    9) Replay the recording stored in register ‘a’ 100 times (repeat as needed).

  18. Oops,

    lines 2 and 4 had the XML tags removed after posting.

    2) /^^I^I^I<xsd:complexType>$
    4) /^^I^I^I<\/xsd:complexType>$

  19. Pingback: Tips GVim | La plaga Tux

  20. Pingback: [Quick Hint] Comentar varias líneas en Vim « racv

  21. I tried both methods

    CTRL+V, I method

    mapping of CTRL+G and CTRL+T

    I get a # only before the first line of the block, not the entire block. What am I doing wrong?

  22. Shameless plug: This works great for a lot of cases, but I wanted something more flexible (something more like Emacs M-; . I wrote a little plugin that’s very much in the spirit of vim (gco: open new comment line, gcA: append trailing comment, gcc[text object]: comment text object). I can’t live without it anymore! Here’s the link: http://www.vim.org/scripts/script.php?script_id=2264

  23. I had the same problem Steve, but I was using Shift+V and not Ctrl+V. This site has screen shots to show it: http://www.vim-fu.com/commenting-out-multiple-lines-in-vim/

  24. Pressing capital I did not work for me. I’m running stable version of Debian. This is what worked: Comment out and uncomment multiple lines in VIM.

  25. Pingback: Where’d I leave that note? » Blog Archive » Comment out multiple lines with vim

  26. I recently found this website that I want to share with everyopne as they were a remarkable help when I was
    working on a recent project. I needed to know how to do some stuff in PHP and they were able to provide
    a tutorial sepcifically tailored to my needs. It was fantastic.

    TeamTutorials

    I recommend you hit them up and check them out if you need assistance.

  27. @Steve: Press Esc twice.

  28. An easy way to uncomment using the ctrl-v method would be to use ctrl-v to select all of the comment characters that were inserted at the beginning of the line and then to press ‘x’ to simply delete ’em.

  29. Very nice idea, thanks! If you want to use your favorite hot key instead of typing the command, you might find useful to put a following mapping to your .vimrc :

    vmap ^R :s/^/\/\//^M

    After selecting several lines in a visual mode, press Ctrl+R to comment out.

    note 1: for case you have already forgotten: use Ctrl + V, Ctrl + R to insert “^R” sequence, similarly Ctrl + V, Enter to insert “^M”

    note 2: feel free to replace Ctrl + R with your combo (this one is from Matlab) … unfortunately I was unable to make my favorite Ctrl-slash from Eclipse / Netbeans working.

    Implementation of reverse operation is of course straightforward 🙂

  30. Can’t believe I never knew this. (Perform actions across multiple lines in Vim.)

  31. cant get you guys words,but i find what i need–alt 3 and alt 4(python)

  32. I wrote a couple of small functions which could be useful to others as well. Saved the following into a file and called it vcomments.vim

    :function! Comment()
    : let ext = split(expand(‘%:t’), ‘\.’)
    : let l_ext = tolower(ext[1])
    : if l_ext == ‘php’ || l_ext == ‘rb’ || l_ext == ‘sh’ || l_ext == ‘py’
    : :silent s/^/\#/
    : elseif l_ext == ‘js’
    : :silent s:^:\/\/:g
    : elseif l_ext == ‘vim’
    : :silent s:^:\”:g
    : endif
    :endfunction

    :function! Uncomment()
    : let ext = split(expand(‘%:t’), ‘\.’)
    : let l_ext = tolower(ext[1])
    : if l_ext == ‘php’ || l_ext == ‘rb’ || l_ext == ‘sh’ || l_ext == ‘py’
    : :silent s/^\#//
    : elseif l_ext == ‘js’
    : :silent s:^\/\/::g
    : elseif l_ext == ‘vim’
    : :silent s:^\”::g
    : endif
    :endfunction

    Once this is done, open your ~/.vimrc file if it exists, or create a new one. There, put the following code.

    :source ~/vcomments.vim
    :map :call Comment()
    :map :call Uncomment()

    Where you can replace a and b of and by whatever is convenient to you. This just calls the functions when the Ctrl + combination is hit.

    To use it, just select the lines to comment by using Shift + v and moving cursor up or down to select lines. Then, hit the Ctrl + combination to comment. Similarly, you can uncomment them

  33. A lot of thanks for each of your efforts on this web page. My daughter really loves managing internet research and it’s simple to grasp why. A number of us learn all concerning the dynamic tactic you present helpful strategies on the web site and in addition recommend contribution from website visitors on that situation so our favorite girl has been being taught a lot of things. Take pleasure in the rest of the year. You’re the one carrying out a stunning job.

  34. It’s difficult to find well-informed people about this subject, however, you sound like you know what you’re talking about! Thanks
    BR Removal Services
    27a Jade Close Unit 2
    London
    E16 3TY
    United Kingdom
    0800 001 6111

  35. Literally, not a single one of these methods worked for me. Are we sure we’re all talking about vim, as in linux vim?

    • guy – I haven’t checked all the comments, but the original post still works. Be sure to use : (colon) to at the start of the command. It is easy to miss that as the command line wraps in the text.

    • Double-check which visual mode you are in – visual, visual line, and visual block all need different commands (from what I can see)/

  36. Greatly appreciated.

    For my experience, I here are the steps with more detail:
    1) Initiate Visual Block
    2) Select the region
    3) Shift + “i”
    4) Then I used pound “#”
    5) Last, Esc (escape) to apply the comment

  37. This page is great! Thanks, everyone!

    I’m still a beginner at Vim, but I’ve modified Mark’s reply to produce the following, which places the commenting character (# for Python) *after any whitespace/indentation* and *does nothing to blank lines.* This was important to me since some code-folding routines for Python can get confused if your comments place # before indentation.

    I’ve maped \c to comment and \u to uncomment.

    ” For commenting and uncommenting
    vmap \c :s/^\(\s*\)\(\S\+\)/\1#\2
    vmap \u :s/#/

    nmap \c :s/^\(\s*\)\(\S\+\)/\1#\2
    nmap \u :s/#/

    If any more experienced Vim users see any improvements (ie could this be done in just two lines?), I’d be glad to hear it.

  38. Hello, i read
    your blog from time to time and
    i own a similar one and i was
    just wondering if you get a lot of s
    pam feedback? If so how do you stop it,
    any plugin or anything you can recommend?
    I get so much lately it’s driving
    me crazy so any assistance is very much appreciated.
    My blog

  39. This is ridiculous doesn’t work for me at all!

  40. Hurrah! At last I got a weblog from where I know how
    to really obtain valuable data concerning my study and knowledge.

  41. I keep listening to the news speak about getting boundless online grant applications so I have been looking around for the finest site to get one. Could you tell me please, where could i get some?

  42. 2) Identify your regular finances, preferred deposit (if any), and preferred term. Look for a personal loan calculator and plug in quantities right until you recognize match your finances. If you happen to know likely in that a total finance amount of money of $15,000 with zero down will likely be $311 per thirty day period for 60 months at 8.9%, you will manage to find the car that matches your finances.
    hermes birkin outlet http://www.diamondstyling.co.uk/skins/php/hermes-bags-03.html

  43. True, there are comedians that cuss a lot, but you
    got to earn that right before you do that. Unfortunately Nora Ephron recently passed away, but she left us with some
    of our most endearing romantic comedies of all time — from “When Harry Met Sally” to “Sleepless in Seattle” and
    “You’ve got Mail. After you do all this, you are ready to start performing in front of people for money.

  44. Make it clear as to when all bids can be presented. You could also advertise in local newspapers, classifieds, local radio station etc.
    Keep them closed for that nice look BUT pull them up a foot
    so people will be within the house.

  45. I love to share understanding that will I’ve accrued with
    the year to assist improve team functionality.

  46. Pingback: Kalpa Pharmaceuticals Injectable Steroids

  47. Great website, thank You !!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s