Reputation: 1994
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?
Upvotes: 7
Views: 2715
Reputation: 30708
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 inisearch+.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 usingM-= C-SPC
during Isearch.You can customize this variable.
Upvotes: 1
Reputation: 3816
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
Upvotes: 5
Reputation: 6926
I'm not sure if there is such a function already, but what you can do it with a keyboard macro:
C-x (
search-forward-regexp
search
or backward-word
etc.C-spc
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
Upvotes: 2