Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emacs copy with regex

Tags:

emacs

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?

like image 647
Nikola Kotur Avatar asked Feb 02 '10 11:02

Nikola Kotur


1 Answers

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

like image 107
danielpoe Avatar answered Sep 18 '22 07:09

danielpoe