The below code works fine from my brief testing in a c-mode
buffer:
- After typing
/*
, hit M-j
, the default binding for indent-new-comment-line
(and the default binding for c-indent-new-comment-line
in c-mode
). If it is the first comment line the closing closing characters */
will be auto-inserted.
- Hitting
M-j
more times with insert more comment lines with the *
prefix. This is the in-built behavior of c-indent-new-comment-line
/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
(save-excursion
(re-search-backward "/\\*")
(1+ (current-column))))))
(apply orig-fun args)
(when first-comment-line
(save-excursion
(newline)
(dotimes (cnt star-col-num)
(insert " "))
(move-to-column 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: /*
M-j
First comment line
M-j
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: /*
M-j
Test offset comment
gives the below. The ▮ indicates the cursor location at the end of typing.
#include<stdio.h>
main() {
printf("Hello World"); /*
* Test offset comment▮
*/
}