8

I am trying to implement the following: duplicate the currently selected region or a line (if there is no selection) and comment out the original region with the help of comment-or-uncomment-region-or-line.

I figured I could use kill-region followed by yank but then my original selection is lost, so I can't comment. If on the other hand I comment first I will get both copies of my region commented out.

The other idea I have (which I think is better because I use evil-mode) is to use evil-yank and then evil-visual-restore to restore the selection so that I can comment it out. But I can't figure what arguments to pass to evil-yank to specify the selected region.

What am I missing here?

egdmitry
  • 2,071
  • 15
  • 18

1 Answers1

7

The main thing you are missing is function copy-region-as-kill.

(defun copy-and-comment-region (beg end &optional arg)
  "Duplicate the region and comment-out the copied text.
See `comment-region' for behavior of a prefix arg."
  (interactive "r\nP")
  (copy-region-as-kill beg end)
  (goto-char end)
  (yank)
  (comment-region beg end arg))
Drew
  • 29,895
  • 7
  • 74
  • 104
  • Thanks! How can I move one line down after this? I tried (next-line 1), but it doesn't seem to work for some reason. – egdmitry May 11 '14 at 05:27
  • See function `forward-line`. – Drew May 11 '14 at 05:30
  • It doesn't work as well. I suspect it's related to evil mode, if I select the region with `V`, `forward-line` doesn't work. – egdmitry May 11 '14 at 05:46
  • Maybe post another question that is specific to whatever problem you have now. It might be more Evil-specific, as you suspect. (I assume you tried it without Evil mode, at least, for comparison.) – Drew May 11 '14 at 14:08
  • almost correct! – CD86 Feb 08 '22 at 12:13