Skip to content

Instantly share code, notes, and snippets.

@alphapapa
Last active April 2, 2016 22:05
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save alphapapa/97642ff798f773f48af4dd5c20f4854f to your computer and use it in GitHub Desktop.
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)
(progn
(comment-kill nil)
(delete-indentation)) ; Remove blank line
;; No prefix
(if (looking-back (rx bol (optional (1+ (or whitespace (syntax comment-start)))))
(line-beginning-position))
;; 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
(comment-indent)
;; 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