Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emacs copy region/line and comment at the same time

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?

like image 431
egdmitry Avatar asked May 11 '14 03:05

egdmitry


People also ask

How do I copy and paste lines in Emacs?

Once you have a region selected, the most basic commands are: To cut the text, press C-w . To copy the text, press M-w . To paste the text, press C-y .

How do I comment multiple lines in Emacs?

Emacs also allows you to pass the number of lines you need to comment or uncomment. To do this: Start by pressing the CTRL + U key, followed by the number of lines to comment out. As you can see from the screenshot above, Emacs comments out 10 lines from the current cursor position.

What is the command to paste an entire line in Emacs?

Kill (Cut), Copy, and Yank (Paste) Commands in Emacs To cut, or kill, the text, you can use the keys Ctrl + k to kill a particular line, or the Ctrl + w command to kill the entire selected region. To paste, or yank, the text, press the keys Ctrl + y.

How do I select a line in Emacs?

With Emacs 25, simply press Ctrl + Space and then move your cursor wherever you want to highlight/select the region of text which interests you. After that, you may need these commands: Ctrl + W for cutting.


1 Answers

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))
like image 178
Drew Avatar answered Oct 12 '22 21:10

Drew