How to replace a region in emacs with yank buffer contents? - emacs

When I use VIM or most modeless editors (Eclipse, NetBeans etc.) I frequently do the following. If I have similar text blocks and I need to change them all, I will change one, copy it (or use non-deleting yank), select next block I need and paste the changed version over it. If I do the same thing in emacs (select region and paste with C-y), it doesn't replace the region, it just pastes at the cursor position. What is the way to do this in emacs?

Add this to your .emacs:
(delete-selection-mode 1)
Anything that writes to the buffer while the region is active will overwrite it, including paste, but also simply typing something or hitting backspace

Setting delete-selection-mode, as Michael suggested, seems the most natural way to do it.
However, that's not what I do :) Instead, I put the good stuff into a "register" -- for example, register "a" -- with C-x r x a. Then I kill the other copy, and copy the register into the same spot with C-x r g a.
This is convenient because killing doesn't affect the registers, so C-x r g a always inserts the good stuff.

The default way to do something like this is the not-entirely-elegant following:
Get your desired replacement text into the kill ring somehow (e.g., M-w).
Highlight the region to be replaced.
Delete it (C-w).
Replace it with the prior-copied region (C-y, M-y). This replaces the freshly deleted contents with the exact same text that you just deleted (C-y), and then re-replaces it with the next most-recently saved buffer in the buffer ring (M-y).
This would get to be a real pain if you wanted to do this 10 times with the same text, as the desired replacement would get pushed farther back in the kill ring each time you deleted a region, so you'd have to call M-w an increasing number of times each time you wanted to yank it.
I've also just discovered M-x delete-region, thanks to Emacs: how to delete text without kill ring?. As the question implies, this deletes the offending text without putting it into the kill ring, avoiding the problem of pushing your replacement text further down on the stack. And, as the relevant response mentions, you can bind this to a shortcut key of your choosing.

The way I do this is:
go to where you want the new stuff
paste the good stuff
your cursor is now between the new stuff and the stuff you want to get rid of
select forward until everything you want to get rid of is selected
delete it
It's a slightly different way of thinking about it. Paste what you want, then get rid of what you don't want, rather than replace what you don't want with what you do.

If you enable CUA-mode, this paste over selected region becomes the normal behaviour.

Use delete-selection-mode, so that pasted text replaces the active region.
Use the secondary selection, to paste the same text over and over, even if you alternately select a new region to replace.
See http://www.emacswiki.org/emacs/SecondarySelection.

For anyone landing on this who doesn't want to change the global setting like me, I use this function and key binding:
(defun replace-yank(beg end)
(interactive "r")
(kill-region beg end)
(yank 3))
(global-set-key (kbd "C-S-y") 'replace-yank)
I intentionally add the selected text to the kill ring incase I want it later, and yank what was previously first in the ring.

If you don't care to preserve the highlighted text in the kill ring you could use something similar to the answer above by ekneiling
(defun replace-yank(beg end)
(interactive "r")
(delete-region beg end)
(yank 1))
(global-set-key (kbd "C-S-y") 'replace-yank)
One advantage is the above can be done repeatedly.

Related

Help with deleting in Emacs

I want to delete everything up to the cursor or after the cursor or everything but selected text.
What you want sounds a pretty infrequent thing to be done, but here are a few ways to do it:
First, put cursor on start of text you want to keep. Press C-space to set mark. Then, use M-< (beginning-of-buffer) and afterwards C-w (kill-region-x). Now, everything before text is deleted.
Next, go to end of text and set mark once again with C-space. Now, go to end of buffer with M-> and once again delete everything with C-w.
This is one way to do it.
Other way is to simply copy selected text and put it into new buffer. I'll leave it to you as an exercise.
To keep only the selected text:
C-w C-x h C-w C-y M-y
In other words, kill the selection, select what remains, kill that, then yank the previous selection.
Everything after "the cursor" (aka "point") is deleted using C-k (kill-line). To kill the line up to point, give a 0 argument like this: C-u 0 C-k.
I don't know if there's a way to kill only things that aren't selected. Maybe some kind of "invert-region" before hand?

Can I keep the same item for yanks in Emacs?

Something I do often in Emacs is to cut a bit of text, and then replace another bit with the cut text. So, say I've got the text I want to yank as the last item in my kill-ring. I yank it into the new place, then kill the text that was already there. But now the killed text is the latest item in the kill-ring. So next time I want to yank the first item, I have to do C-y M-y. Then the next time there are two more recent items in the kill-ring, so I have to do C-y M-y M-y, and so on.
I'm guessing there's a better way to do this. Can someone enlighten me please?
Several alternatives:
Turn on delete-selection-mode, and use C-d or delete to delete region without touching the kill-ring.
Use C-x r s i to save text to register i, and later, C-x r i i to insert the saved text.
If the pattern of texts to be replaced can be captured in a regular expression, use query-replace-regexp (C-M-%).
You should use delete-region instead of kill-region.
delete-region deletes the region without putting it in the kill ring. It is bind to <menu-bar> <edit> <clear> by default.
If you only want to use default bindings without using the menu, you could use delete-rectangle with C-x r d but it works on rectangle. It could be fine to use it on a single line like delete-region.
One of the oldest and best kept secrets in Emacs -- dunno why: Emacs has a secondary selection.
And this is exactly what it is good for. It saves another selection of text for you to use, over and over.
Select some text, then yank the secondary in to replace it. Repeat elsewhere. Often this is more convenient, flexible, and precise than something like query-replace.
Please take a look, for your own good -- maybe it will stop being such a little-known feature...
http://www.emacswiki.org/emacs/SecondarySelection
I wrote this function to pop the newest item off the kill-ring:
(defun my-kill-ring-pop ()
"Pop the last kill off the ring."
(interactive)
(when kill-ring
(setq kill-ring (cdr kill-ring)))
(when kill-ring-yank-pointer
(setq kill-ring-yank-pointer kill-ring))
(message "Last kill popped off kill-ring."))
So after I kill something I don't want to keep, I hit a key that calls this.
Related to this is M-x browse-kill-ring. If you use M-x anything, you can also use M-x anything-show-kill-ring.

Simple Emacs keybindings

I have two operations that I do all the time in Emacs:
Create a new buffer and paste the clipboard. C-S-n
Close the current buffer. C-S-w
Switch to the last viewed buffer. C-TAB
I feel like a keyboard acrobat when doing the first two operations. I think it would be worth trying some custom key bindings and macros.
A few questions about this customization:
How would I make a macro for #1?
Are these good key bindings? (I know this is a bit subjective, but they might be used by something popular that I don't use.)
Has anyone found a C-TAB macro that will act like Alt+Tab in Linux/Windows? Specifically, I want to have a stack of buffers according to the last viewed timestamp (most recent on top). I want to continue cycling through the stack until I let go of the Ctrl key. When the Ctrl key is released, I want the current buffer to get an updated position on the stack.
Have you tried using vertically or horizontally split windows for this (via C-x 3 or C-x 2)? It seems like it would give you fewer steps - even if you implement something like you're talking about.
I find split windows really speed up copy and pasting operations. I use the arrow keys on my num pad to switch among windows (windmove-left/-right/-up/-down), so it's only one key to press and you go to the window you want.
I guess this is a little different from what you're asking for, but it sounds like it might help speed things along a bit.
C-x left and C-x right cycle through buffers, but you have to hit it multiple times, you can't just keep the key pressed down.
For creating a macro for #1, you just start a macro, hit the keys you usually do to create a new buffer, and stop the macro.
So it would be something like:
C-x ( C-x b NEW RET C-x )
You can then save NEW to a file once you're done pasting, so you can use the macro again to create a new buffer. C-x e to try out the macro. If it works you can save it into your init.el file. This is done with:
M-x name-last-kbd-macro
Then you'll get a prompt to enter the name of your choice. This is only good for the current session. Then you save the named macro to your initialization file. First you open your .emacs or init.el file. Then you place point where you want the macro definition to go, then you type:
M-x insert-kbd-macro
Now you can run your macro using its name via M-x <macroname> . You can bind your macro to keys too (in your .emacs or init.el file):
(global-set-key (kbd "C-c a") '<macroname>)
For example this is how your init.el would look after creating a macro that opens a new buffer called NEW that is not associated with a file and binding this macro to C-c n:
;; Creates a new unassociated buffer called NEW
(fset 'new-buffer "\C-xbNEW\C-m");
;; Shortcut for new-buffer
(global-set-key (kbd "C-c n") 'new-buffer)
You can also throw in the paste, buffer close, and buffer switching operations. I guess you'd have to save the buffer to a file manually.
Some resources
Information about macros on EmacsWiki
Possibly useful: Swap text between buffers
start by invoking start-kbd-macro, finish by with end-kbd-macro. Afterwards you may immediately test the new macro with call-last-kbd-macro. If you're happy with the result you might want to save the macro.
Emacs generally doesn't use C-S keybindings and they are easy to use, so I'd call them good. They might cause problems if you're using the terminal version of Emacs, but I assume that's not the case with you.
I use this simple snippet:
(global-set-key (kbd "<C-tab>") 'bury-buffer)
bury-buffer basically makes the current buffer the last in the buffer-list so you'll be able to cycle buffers in a predictable order.
I wouldn't make a macro for that but write a function like someone else posted on this page. Instead of (cua-paste nil) you could also use (yank). I'm not sure which one's better and why.
I don't like them that much. For things that I use often I'd like to do as little finger acrobatics as possible, so that would mean modifier+key instead of modifier1+modifier2+key.. or use a function key if you don't feel tied to the homerow.
no comment

Emacs: copying text (without killing it)

In Emacs, how do I copy a region of text (to paste it in another buffer) without killing it (for example: the file I want to copy from is opened in read-only mode, so killing it isn't an option).
Just mark it (C-space at one end of the range, and move to the other end) and use M-w (kill-ring-save):
(kill-ring-save BEG END)
Save the region as if killed, but don't kill it.
Two additional ways:
You can also select it with the mouse (mouse-button-1), which will copy the region to the kill ring.
When the buffer is read-only, you can use the kill-* routines (C-w and C-k) to copy the region/line to the kill ring. Emacs will beep at you, but it's a documented feature:
If the buffer is read-only, Emacs will
beep and refrain from deleting the
text, but put the text in the kill
ring anyway. This means that you can
use the killing commands to copy text
from a read-only buffer.
I use the command
M-x append-to-file
the problem with this is that if the file you want to copy it to is open, you will need to refresh the screen somehow so that the new stuff appears there. Also, the stuff you copied will go to the end of the file you choose as the target.
You might also find the commands
M-x write-region
and
C-x i (insert-file)
useful.

How to preserve clipboard content in Emacs on Windows?

This is scenario that I ran into a few times:
I copy some text from other program. Go to Emacs and did some editing before I paste/yank the text in. C-y to yank and voila ... not the text I intended to paste in. Then I realize that while I am moving things around, I used commands like kill-line and backward-kill-word, and those killed lines and words now occupied the kill-ring. But typing M-y does not bring the original copied text back, so I need to go back to my original program to copy the text again. And even worst if the original program is closed, then I lost the copied text completely.
Kill-line, etc. are such basic commands (like hitting the delete key, almost), and while I don't mind that the kill-ring gets a bit cluttered by using those command, I expect that my original text stays somewhere in the kill-ring so that I can eventually find it by typing M-y a few times. How can I make Emacs to automatically preserve the current clipboard content into the kill-ring before overriding the clipboard content?
This code should automatically put the selection (from outside Emacs) onto the kill-ring any time you do a kill in Emacs. It's been tested on Linux, but shouldn't be restricted to Linux.
(defadvice kill-new (before kill-new-push-xselection-on-kill-ring activate)
"Before putting new kill onto the kill-ring, add the clipboard/external selection to the kill ring"
(let ((have-paste (and interprogram-paste-function
(funcall interprogram-paste-function))))
(when have-paste (push have-paste kill-ring))))
If you find yourself doing this a lot, it may be useful to take a look at the package browse-kill-ring, which gives you a nice view of the kill ring (as opposed to repeatedly typing M-y).
Note that latest Emacs CVS version have the variable save-interprogram-paste-before-kill which does exactly this cf: from the etc/NEWS file :
** When save-interprogram-paste-before-kill'
is non-nil, emacs will not clobber the
the interprogram paste when something
is killed in it by saving the former
in thekill-ring' before the latter.
I think the problem is that when you yank from the clipboard outside emacs, you're not saving to the kill ring.
What you'd need is to use the function clipboard-yank to insert the region, then somehow select it and save it to the kill ring, like the function kill-ring-save does.
Or even better write a function clipboard-save-to-kill-ring-and-yank which saves the clipboad to the kill ring and then yanks it.
edit: Tracking through the code a bit, this does what you want; you could hook it up to a key. It saves the windows clipboard contents to the kill ring.
(defun clipboard-to-kill-ring()
"save the external clipboard contents to the kill ring"
(interactive)
(let ((clip (funcall interprogram-paste-function)))
(when clip
(kill-new clip)))
(defadvice yank (before maybe-copy-windows-clipboard (arg))
(clipboard-to-kill-ring))
(ad-activate 'yank)
I'd guess you could hack the various kill commands to not put text into the clipboard, and then have clipboard-yank bound to a different key, dunno if that would work.
I sort of work around this by just yanking the text then re-killing it, when I pop into emacs after having done a copy or cut in another windows app.
A better approach would be to hack emacs so that when you kill something, it compares the existing clipboard to the topmost entry in the kill ring, and if different, it pushes the clipboard contents to the kill ring, before doing the kill you explicitly requested.