The below code works fine from my brief testing in a
- After typing
M-j, the default binding for
indent-new-comment-line (and the default binding for
c-mode). If it is the first comment line the closing closing characters
*/ will be auto-inserted.
M-j more times with insert more comment lines with the
* prefix. This is the in-built behavior of
indent-new-comment-line functions. Check out the Multiple lines of comments documentation.
- An extra nugget in the below code ensures that there is at least one space between the
* on each comment line and the comment.
(defun my-prettify-c-block-comment (orig-fun &rest args)
(let* ((first-comment-line (looking-back "/\\*\\s-*.*"))
(star-col-num (when first-comment-line
(apply orig-fun args)
(dotimes (cnt star-col-num)
(insert " "))
(move-to-column star-col-num) ; comment this line if using bsd style
(insert "*") ; comment this line if using bsd style
;; Ensure one space between the asterisk and the comment
(when (not (looking-back " "))
(insert " ")))
(advice-add 'c-indent-new-comment-line :around #'my-prettify-c-block-comment)
;; (advice-remove 'c-indent-new-comment-line #'my-prettify-c-block-comment)
For instance, after evaluating the above code, I get the below on typing:
First comment line
Second comment line. The ▮ indicates the cursor location at the end of typing.
* First comment line
* Second comment line▮
Testing offset comment block ..
With cursor after the semicolon, typing:
Test offset comment gives the below. The ▮ indicates the cursor location at the end of typing.
printf("Hello World"); /*
* Test offset comment▮