Skip to content

Instantly share code, notes, and snippets.

@prakashk
Created April 5, 2013 14:40
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save prakashk/5319782 to your computer and use it in GitHub Desktop.
Save prakashk/5319782 to your computer and use it in GitHub Desktop.
(defun copy-comment-paste ()
"copy active region/current line, comment, and then paste"
(interactive)
(unless (use-region-p)
(progn
(beginning-of-line 2)
(push-mark (line-beginning-position 0))))
(kill-ring-save (region-beginning) (region-end))
(comment-region (region-beginning) (region-end))
(yank)
(exchange-point-and-mark)
(indent-according-to-mode))
@noahfriedman
Copy link

I do this all the time, and never automated it! Your version inspired me
to write this alternative with a couple of useful features:

  1. the kill ring and mark are not altered. This is significant if yank-pop-change-selection is enabled.
  2. Behavior is more consistent with region-using commands when transient-mark-mode is disabled.
  3. Point is preserved if you are in the middle of a line when you invoke the command.

Thanks for the inspiration!

(defun copy-and-comment-region (beg end)
  "Insert a copy of the lines in region and comment them.
When transient-mark-mode is enabled, if no region is active then only the
current line is acted upon.

If the region begins or ends in the middle of a line, that entire line is
copied, even if the region is narrowed to the middle of a line.
The copied lines are commented according to mode.

Current position is preserved."
  (interactive "r")
  (let ((orig-pos (point-marker)))
  (save-restriction
    (widen)
    (when (and transient-mark-mode (not (use-region-p)))
      (setq beg (line-beginning-position)
            end (line-beginning-position 2)))

    (goto-char beg)
    (setq beg (line-beginning-position))
    (goto-char end)
    (unless (= (point) (line-beginning-position))
      (setq end (line-beginning-position 2)))

    (goto-char beg)
    (insert-before-markers (buffer-substring-no-properties beg end))
    (comment-region beg end)
    (goto-char orig-pos))))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment