tags:

views:

105

answers:

2

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?

+1  A: 

I'm not sure if there is such a function already, but what you can do it with a keyboard macro:

  1. Start recording a kbd macro: C-x (
  2. Search for your regexp with search-forward-regexp
  3. 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.
  4. Mark: C-spc
  5. Move to the end of your match
  6. 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

liwp
+3  A: 

Hi,

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

danielpoe
Thanks, it's just what I wanted, but couldn't make since I suck at LISP.
Nikola Kotur