Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How Vim handles comments

📅 2015-Apr-28 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ comments, commentstring, vim ⬩ 📚 Archive

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