Weekly Emacs tip #13: Commenting lines and regions in your code
After a week-long holiday, it’s time for an Emacs tip again. Programming means writing comments. Or at least it should. Good source code is well-documented with comments explaining what the non-trivial parts of the code (are supposed to) do.
Of course, Emacs has functions to help you managing the comments in your code. The first one, comment-line
(bound to C-x C-;
) does what is says: it comments the current line, or if it is already commented, it uncomments it. If a region is active (i.e. if several lines are selected), this function comments or uncomments those lines.
The second function, however, is the one I mostly use, mainly because its keyboard shortcut is shorter 😇. It is comment-dwim
, bound to M-;
. Here, “dwim” stands for “do what I mean”, a term that shows up in other places in Emacs as well.
The idea is that the command will do different things in different situations, trying to do the most logical thing. When a region is selected, it will comment it, or uncomment it, depending on whether it currently is a comment or not. When no region is selected and the line is empty, a new comment is started. If the line already contains code/text, it will start a comment after the existing text. The point (cursor) will be moved there to so you can immediately start typing your comment.
For most use cases I have seen, Emacs knows what symbol(s) to use in order to start a comment, e.g. a #
in Bash or R, ;
for Emacs Lisp code and a <!--
-->
pair for HTML. And if it doesn’t know, it will ask you to enter the symbol in the minibuffer.
And while we’re on the subject of comments: using M-j
generally insert a newline and indents (it runs the default-indent-new-line
command). When run on a commented line it will also insert the comment character(s) on that new line. A nice thing when writing larger comment blocks.
For reference, this is a link to the corresponding page in the Emacs manual.
No Comments