9

After copying a "rectangle" using C-x r M-w, doing C-x r y yanks or pastes the rectangle. But that inserts the copied rectangle.

How can I paste the copied rectangle so that it overwrites the text?

Example:

 a b c d e f g
 h i j k▮l m n
 o p q r s t u▮

I copied the rectangle enclosed between the cursor positions shown above using M-x copy-rectangle-as-kill or C-x r M-w.

Now when I paste it in front of the character h using M-x yank-rectangle or C-x r y, I want the result to look like

 a b c d e f g
▮l m n k l m n
 s t u r s t u

instead of

 a b c d e f g
▮l m n h i j k l m n
 s t u o p q r s t u

How can I make the yank-rectangle overwrite?

Kaushal Modi
  • 25,203
  • 3
  • 74
  • 179
  • Works for me. Try running Emacs with the -Q flag in order to use the default configuration. If that works then its going to be something in your configuration. – Colin Bell Sep 24 '14 at 00:18
  • Ah! I mistakenly asked the reverse question. I mean to find a way for `C-x r y` to overwrite. I am editing my question now. – Kaushal Modi Sep 24 '14 at 01:12

2 Answers2

8

Use M-x picture-mode. C-c C-y, bound to command picture-yank-rectangle, does what you want. (You can use C-_ to undo.)

These related keys are also available in picture-mode:

  • C-c C-k - Clear a rectangle and save it (picture-clear-rectangle)
  • C-c C-w - Clear a rectangle and save it in a register (picture-clear-rectangle-to-register)
  • C-c C-x - Like C-c C-y, but uses the rectangle in a register (picture-yank-rectangle-from-register)
  • C-x r r - Copy a rectangle to a register (copy-rectangle-to-register)

Use C-c C-c to exit picture mode.

You can also use the picture-mode commands without turning on picture-mode, but in that case their keys are not bound. You will anyway need to load library picture.

So you can, for example, do this:

  1. Use C-x r r to copy a rectangle to a register.
  2. Put the cursor where you want to yank that rectangle, replacing existing text.
  3. M-x picture-yank-rectangle-from-register (which you can also bind to a key).
Drew
  • 75,699
  • 9
  • 109
  • 225
  • 1
    Thanks! The `M-x picture-yank-rectangle-from-register` solution works great for me; I simply need to put `(require 'picture)` in my `init.el`. – Kaushal Modi Sep 24 '14 at 13:18
1

Another approach is to use delete-selection-mode and do this in your init file:

 (put 'yank-rectangle 'delete-selection 'yank)

But that makes yank-rectangle always replace the text at point, which might not be what you want.

Drew
  • 75,699
  • 9
  • 109
  • 225