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 ()
  "Like `comment-dwim', but toggle comment if cursor is not at end of line.

URL `http://xahlee.info/emacs/emacs/emacs_toggle_comment_by_line.html'
Version 2016-10-25"
  (if (region-active-p)
      (comment-dwim nil)
    (let (($lbp (line-beginning-position))
          ($lep (line-end-position)))
      (if (eq $lbp $lep)
            (comment-dwim nil))
        (if (eq (point) $lep)
              (comment-dwim nil))
            (comment-or-uncomment-region $lbp $lep)
            (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, Prefix Lines, Rectangle Edit

Xah Emacs Commands