vimtricks.wiki Concise Vim tricks, one at a time.

How do I define the comment format Vim uses for auto-commenting and plugins like vim-commentary?

Answer

:set commentstring=//\ %s

Explanation

The commentstring option controls the template Vim uses to represent commented-out lines. It is a string containing %s as a placeholder for the actual code. This setting affects how Vim inserts comment leaders when formatoptions includes the r or o flags (auto-insert on Enter/o), and it is the primary interface used by plugins like vim-commentary to determine which characters wrap a comment.

How it works

  • commentstring must contain %s as a placeholder for the commented text
  • Single-line comment style: //\ %s → produces // code
  • Block comment style: /*\ %s\ */ → produces /* code */
  • Hash-style: #\ %s → produces # code
  • Vim's built-in ftplugins set this automatically for known filetypes, but custom or unusual filetypes may need it set manually

Example

For a custom filetype or to override the default:

" In your vimrc or an ftplugin file:
autocmd FileType lua setlocal commentstring=--\ %s
autocmd FileType toml setlocal commentstring=#\ %s

Then when vim-commentary's gc command runs, it knows to use -- for Lua or # for TOML:

Before: name = "vim"
After:  -- name = "vim"

Tips

  • Use :setlocal commentstring (not :set) so the option applies only to the current buffer
  • Check the current value with :set commentstring?
  • The %s placeholder is required — omitting it will cause plugin errors
  • For block comments, both sides of %s must be included: /*\ %s\ */
  • Combined with formatoptions+=cro, Vim auto-inserts comment leaders on new lines inside comments

Next

How do I open a file in a read-only split window in Vim?