After writing functions in C/C++, I like to format my block comments that explain a function's purpose, parameters, use, and so on.

(See example below) Desired Emacs Comment Style

However, to indent my comments in emacs, I need to do C-q TAB, which is a bit of an awkward set of keystrokes (not to mention having to press three keys as opposed to one).

My question is: what would the Elisp code be for:

  1. See whether or not what I'm typing is in a comment block (I'm thinking it has to do with font-lock-comment-face but I'm not sure
  2. If the text is inside a block comment, have TAB perform the same functionality as the aforementioned C-q TAB

For more information, some of the shortcuts given in the Emacs guide, such as M-j are helpful, but I still need to C-q TAB to initially indent a region within the comment.

1 Answer 1


The usual way to check if you are in a comment is to use syntax-ppss.

A simple way to do what you want would be something like:

(defun my/c-indent-or-tab-in-comment ()
  (if (nth 4 (syntax-ppss))
      (insert "\t")
    (call-interactively 'indent-for-tab-command)))

(define-key c-mode-map (kbd "TAB") #'my/c-indent-or-tab-in-comment)

Some other possible approaches: modify the indent-line-function variable to point to a function that does what you want, or define advice on indent-for-tab-command.

  • Thank you very much! This helped immensely. For future reference, I used the (kbd "<tab>") command on my terminal. I am relatively new to elisp and all the crazy customizations it provides, so I was wondering what prefixing the argument and padding it to indent-for-tab-command would be used for. Again, many thanks! Commented Oct 15, 2017 at 17:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.