Search code examples
emacselisp

Wrong indentation of comments in Emacs


In many languages, the line comment starts with a single symbol, for example # in Python and R.

I find that in Emacs, when writing such line comments, I have to repeat the comment symbol twice to make the correct indentation.

See the following example:

(setq x-select-enable-clipboard t)
                                        ;using a single comment symbol indents wrongly
;; repeating the comment symbol indents fine
(setq-default c-basic-offset 4)

With a single ; at the beginning of the line cannot get the correct indentation. How to get the correct setting? Thanks!

EDIT:

I found the solution myself. In ESS's document:

Comments are also handled specially by ESS, using an idea borrowed from the Emacs-Lisp indentation style. By default, comments beginning with ‘###’ are aligned to the beginning of the line. Comments beginning with ‘##’ are aligned to the current level of indentation for the block containing the comment. Finally, comments beginning with ‘#’ are aligned to a column on the right (the 40th column by default, but this value is controlled by the variable comment-column,) or just after the expression on the line containing the comment if it extends beyond the indentation column. You turn off the default behavior by adding the line (setq ess-fancy-comments nil) to your .emacs file.

So I put this in my .emacs:

(setq ess-fancy-comments nil) ; this is for ESS

I think for Python mode, it has a similar variable.


Solution

  • The major mode should take care of this properly. If not, consider filing an enhancement request or bug report to the maintainers. Of course, "properly" might be in the eye of the beholder. You can try to make your preferences known, however. And check whether the major-mode code might already have user options for this.

    Beyond that, the function that is the value of variable comment-indent-function governs this. Normally, this is set by the major mode. You can set it to any function you want (e.g. on the mode hook, so that your definition overrides the one provided by the major-mode code).

    It accepts no arguments, and it returns the column you want the comment to be indented to.

    Here is code that indents a comment to column 0, for example:

    (defun foo () (setq comment-indent-function (lambda () 0)))
    (add-hook 'SOME-MODE-HOOK 'foo 'APPEND)
    

    For Emacs-Lisp mode, for example, you would use (add-hook 'emacs-lisp-mode-hook 'foo 'APPEND).