If you write code, you’re probably always adding and deleting comments. It’s one of those things that’s so fundamental you’d think everyone already knows the best way of dealing with them but I often see questions about how best to handle them in Emacs. Mickey has a tweet with some useful tips on wrangling comments in Emacs:
`M-;’ inserts an inline, mode-appropriate comment in #emacs. With an active region it’ll (un)comment as needed.
`C-x C-;’ (un)comments out the line point is on.
`M-x comment-box’ draws a fancy box around a region.
The variable `comment-styles’ controls the formatting.
— Mickey Petersen (@mickeynp) February 11, 2022
Those commands are also useful as building blocks. For example, I like starting functions (especially in C) with a comment box that gives the name of the function and a short description of what it does but I like the boxes to extend to the end of the line. Here’s a simple function that does that:
(defun jcs-comment-box (b e) "Draw a box comment around the region but arrange for the region to extend to at least the fill column. Place the point after the comment box." (interactive "r") (let ((e (copy-marker e t))) (goto-char b) (end-of-line) (insert-char ? (- fill-column (current-column))) (comment-box b e 1) (goto-char e) (set-marker e nil)))
Notice how it leverages comment-box
to do the heavy lifting.