Emacs: Toggle Comment Current Line 🚀

By Xah Lee. Date: . Last updated: .

Here's a command to toggle comment of current line.

put this in your Emacs Init File:

(defun xah-comment-dwim ()
  "Toggle comment in programing language code.

Like `comment-dwim', but toggle comment if cursor is not at end of line.
If cursor is at end of line, either add comment at the line end or move cursor to start of line end comment. call again to comment out whole line.

URL `http://xahlee.info/emacs/emacs/emacs_toggle_comment_by_line.html'
Created: 2016-10-25
Version: 2023-07-10"
  (interactive)
  (if (region-active-p)
      (comment-dwim nil)
    (let ((xbegin (line-beginning-position))
          (xend (line-end-position)))
      (if (eq xbegin xend)
          (progn
            (comment-dwim nil))
        (if (eq (point) xend)
            (progn
              (comment-dwim nil))
          (progn
            (comment-or-uncomment-region xbegin xend)
            (forward-line )))))))

Put it in your emacs init.

Also, you can give it the comment-dwim key, like this:

(global-set-key (kbd "M-;") 'xah-comment-dwim)

Emacs, Comment, Uncomment, Rectangle Edit