Can I keep the same item for yanks in Emacs? - 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.

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?

How to force Emacs to save even if it thinks (no changes need to be saved)

This happens to me all the time:
I have a file open in emacs,
I save it ('save-buffer),
the file changes on disk (or get's deleted, moved, etc.)
but I want it back, so I try to save again in emacs ('save-buffer) and instead of saving it says "(no changes need to be saved)" and does nothing.
Is there a different function, or a setting, that I can use to force emacs to save?
Wrap a function around save-buffer that marks the buffer modified first:
(defun save-buffer-always ()
"Save the buffer even if it is not modified."
(interactive)
(set-buffer-modified-p t)
(save-buffer))
You can save as, with C-x C-w. That should save unconditionally. You can also just type a space then backspace over it. Emacs is smart enough to realize that if you undo everything you've done so far the buffer has no changes, but if you make changes and then manually reverse them it will consider the buffer to have been changed.
You can mark the current buffer as modified using the Emacs-Lisp function not-modified with a prefix arg, bound to:
C-u M-~
The answer above won't work if you don't call the new function directly.
If you want to seamlessly change emacs saving behavior. The best solution is to create an advice:
(defadvice save-buffer (before save-buffer-always activate)
"always save buffer"
(set-buffer-modified-p t))
As a slight alternative to scottfrazer's answer:
(defun my-save-buffer-always-sometimes (prefix)
"Save the buffer even if it is not modified."
(interactive "P")
(when prefix
(set-buffer-modified-p t))
(save-buffer))
This was you can force it when you want to with a prefix (C-u C-x C-s) but not unnecessarily change a file otherwise. The last modified timestamp is very useful (e.g. source code control) that it seems a shame to change it arbitrarily. YMMV, of course.
A similar problem brought me online to look for a solution. Then it hits me that all I have to do is type a space (or any character) and delete it, which marks the buffer as changed. Then I can type C-x C-s as normal. Maybe not sophisticated or advanced, but it works.
Like Tagore Smith said, you can force Emacs to save the buffer with C-x C-w.
If you're using Evil mode, you can also achieve this behavior by typing :w! in normal state. Unlike C-x C-w, :w! will not prompt you for the filename to save to.

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

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.

Emacs copy with regex

I have a text file. Can Emacs select text based on regex and put it in kill-ring, so I can copy it somewhere else? Something like regex-kill-ring-save?
inspired by the already given comments (the Charles answer doesn't work as I would want it), I added a new function to the isearch/isearch-regexp mode map which puts only the matching string into the kill ring (whereas Charles proposal kills from current point to end of matching string):
(defun hack-isearch-kill ()
"Push current matching string into kill ring."
(interactive)
(kill-new (buffer-substring (point) isearch-other-end))
(isearch-done))
(define-key isearch-mode-map (kbd "M-w") 'hack-isearch-kill)
The nice thing about the isearch/isearch-regexp approach (which you can enable with C-s and C-M-s respectively) is that you can see your search string growing and you can copy it with M-w as soon as you are satisfied (and go back to where you have been before with C-u C-Space).
This works for me with Emacs 23.1. Don't know if it will work in all situations. Anyway I hope you find it useful :)
UPDATE: going through the emacswiki I stumbled over KillISearchMatch which suggests more or less the same (plus some more tips ...).
Cheers,
Daniel
I'm not sure if there is such a function already, but what you can do it with a keyboard macro:
Start recording a kbd macro: C-x (
Search for your regexp with search-forward-regexp
Move to the beginning of your match (the text you want to kill) with the various emacs navigation commands, e.g. search or backward-word etc.
Mark: C-spc
Move to the end of your match
Kill the text: C-w
You can then name the keyboard macro with M-x name-last-kbd-macro so that you can execute the macro with a name rather than with C-x e.
If you want to save the macro for future sessions, you can open your .emacs and insert the macro into the buffer with M-x insert-kbd-macro. After than you can bind a key to the macro just like you bind keys to normal emacs functions, e.g. (global-set-key "\C-c m" 'funky-macro-macro).
More about emacs keyboard macros
Isearch+ does this already. It optionally sets the region around the search target. You can use C-SPC C-SPC or M-= C-SPC at any time during Isearch to toggle this.
isearchp-deactivate-region-flag is a variable defined in isearch+.el.
Its value is t
Documentation:
Non-nil means isearching deactivates the region.
See also option isearchp-restrict-to-region-flag.
You can toggle this option using M-= C-SPC during Isearch.
You can customize this variable.

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.