Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Yet another comment-do-what-I-want function
(defun ap/comment-dwiw (prefix)
"Add/remove comments from code.
With prefix, uncomment region or remove commented lines.
More specifically:
With active region:
* With prefix: Uncomment region.
* Without prefix: Comment/uncomment region.
Without active region:
* With prefix: comment-kill.
* Without prefix:
** Point at beginning of line/comment:
Comment/uncomment current line.
** Point elsewhere on line:
Add/remove comment at end of line."
(interactive "p")
(if (use-region-p)
(if (>= prefix 4)
(uncomment-region (region-beginning) (region-end))
(comment-or-uncomment-region (region-beginning) (region-end)))
;; No region
(if (>= prefix 4)
(comment-kill nil)
(delete-indentation)) ; Remove blank line
;; No prefix
(if (looking-back (rx bol (optional (1+ (or whitespace (syntax comment-start)))))
;; Point at beginning-of-line/end-of-whitespace
(let ((line-end (line-end-position)))
(if (string-blank-p (buffer-substring-no-properties (line-beginning-position) (line-end-position)))
;; Line is blank; insert comment
;; Line not blank; act on line
(comment-or-uncomment-region (line-beginning-position) (line-end-position)))
(when (> (line-end-position) line-end)
;; Comment added; insert space after comment delimiter
(search-forward-regexp "\\s<+" (line-end-position))
(insert-char ? )))
;; Point elsewhere on line
(comment-dwim nil)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment