Commenting code


If you’re working with code in Vim, you may have the occasion to comment and uncomment multiple lines at a time. There are many ways to do this, including with blockwise selection. My preferred way is with a plugin which I’ll cover later. But first, here’s a simple way to comment and uncomment blocks of code in Vim without a plugin:

First, visually make a visual selection of the lines you wish to comment using V and j or k to move down and up. Then, use the norm command to run a normal mode command across all lines in the visual selection. The command will be i to insert at the beginning of the line followed by # or whatever your language’s comment character is:

:norm i#

If you want a whitespace separator after your comment character, add an extra space after the # so :norm i# .

Now, how do we remove those comments? Similarly, visually select the lines with V and then run a normal mode command across all lines, x which will delete one character:

:norm x

If you inserted that extra space, use :norm xx or just :norm 2x.

What if the lines are indented before the comment character? Try the following, which anchors the deletion to the first non-whitespace character:

:norm ^x

All of this can be made easier with Tim Pope’s Commentary plugin. With the plugin installed, just press gc after visually selecting multiple lines. The plugin will add the comment after any indents and add a whitespace character, too. If it’s already commented, gc will remove the comment character and any whitespace padding, meaning you have just one command to remember that toggles comments on and off.

The beauty of Commentary is that it understands many popular languages and can be extended to support any language at all. So if you shift between various languages, you can save yourself the mental overhead of switching comment characters by using commentary.vim.

Here’s a demo of both the non-plugin and plugin method of commenting code in action:

How useful was this tip?

Average rating 4.8 / 5. Vote count: 76

No votes so far! Be the first to rate this tip.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Written by

Colin Bartlett

105 Posts

Vim enthusiast and software developer for more than 20 years.
View all posts