How Vim handles comments

You might have noticed that Vim is aware of comments in a source file. For example, it can fold a block of comments. When you continue typing a comment into a new line it inserts the appropriate comment string. You might have used plugins which can toggle comments on a block of code.

All of this relies on the comments and commentstring options in Vim. These options are set for each filetype that Vim can detect. You can see what they are set to for a particular language by looking for the respective Vim file in /usr/share/vim/vim74/ftplugin.

For example, for Java open the file /usr/share/vim/vim74/ftplugin/java.vim and you can see that it sets these options as:

setlocal comments& comments^=sO:* -,mO:*  ,exO:*/
setlocal commentstring=//%s

The comments option is typically used for C-style comments which have a different beginning and ending components. The commentstring option is used for C++-style comments which are set for the entire rest of the line.

To enable correct commenting behavior in Vim for your own filetypes, set these options by yourself in your Vimrc. For example, see How to set commentstring in Vim.

For more info, see :help comments and :help commentstring

Tried with: Vim 7.4 and Ubuntu 14.04

One thought on “How Vim handles comments

Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.