Emacs: Toggle Comment Current Line

By Xah Lee. Date: .

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

(defun xah-comment-dwim ()
  "Like `comment-dwim', but toggle comment if cursor is not at end of line.

URL `http://ergoemacs.org/emacs/emacs_toggle_comment_by_line.html'
Version 2016-10-25"
  (interactive)
  (if (region-active-p)
      (comment-dwim nil)
    (let ((-lbp (line-beginning-position))
          (-lep (line-end-position)))
      (if (eq -lbp -lep)
          (progn
            (comment-dwim nil))
        (if (eq (point) -lep)
            (progn
              (comment-dwim nil))
          (progn
            (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)

Enhanced Editing Commands Topic

  1. Emacs: Select Line, between Quotes, Extend Selection
  2. Emacs: Copy/Cut Current Line If No Selection
  3. Emacs: Copy/Cut All or Selection
  4. Emacs: Paste or Paste Previous
  5. Emacs: Delete Whitespace around Cursor
  6. Emacs: Move Cursor to Beginning of Line/Paragraph
  7. Emacs: Move Cursor by Text Block
  8. Emacs: Delete Paragraph, Text Block
  9. Emacs: Toggle Comment Current Line
  10. Emacs: Insert Date Time
Like it? Buy Xah Emacs Tutorial. Thanks.

or, buy something from Best Keyboard for Emacs