Thomas Möbius Thomas Möbius - 8 months ago 33
Python Question

Format comments in vim starting with #' (hash-dash)

Using vim, I am using gw or gwap to automatically format long comments in python or R, and vim inserts #-signs automatically at the beginning of the line where needed. Both in python and R, comments for automatic documentation generation start with #' instead of #, and vim has no idea on how to handle those.

How to teach vim that lines with #' are comments, too, and when formatting the line into a block to add #'-signs to the beginning of each line?

Minimal example:

#' Some random text. Please
#' format me
#' nicely by
#' typing gwap anywhere in this paragraph.

Should become something like:

#' Some random text. Please format me
#' nicely by typing gwap anywhere in
#' this paragraph.


You need to expand the comments option:

'comments' 'com'        string  (default
                        local to buffer
                        {not in Vi}
                        {not available when compiled without the |+comments|
        A comma separated list of strings that can start a comment line.  See
        |format-comments|.  See |option-backslash| about using backslashes to
        insert a space.

Formatting uses this option to recognise comment leaders. Each comma-separated entry is of the form {flags}:{string}, where flags control what type of comment formatting is used.

Add b:#' to that list to have text formatting insert matching comment leaders, b stands for blank required, so only #' followed by some whitespace, then text, is seen as a comment leader:

:set comments+=b:#'

See :help format-comments for more information.


comment formatting with additional <code>comments</code> setting

Take into account that a filetype plugin can override the comments option again; you can add the same setting as an override (with a :setlocal command) in the respective ~/.vim/ftplugin/<type>.vim file (create it if it doesn't exist yet).

So for a Python buffer, if there is a ~/.vim/ftplugin/python.vim file it'll be run after the general $VIMRUNTIME/ftplugin/python.vim file has been executed letting you set additional configuration for this filetype, including the extra comment configuration.