开发者

Emacs copy with regex

开发者 https://www.devze.com 2022-12-19 10:07 出处:网络
I have a text file.Can Emacs select text based on regex and put it in kill-ring, so I ca开发者_如何学Gon copy it somewhere else?Something like regex-kill-ring-save?inspired by the already given commen

I have a text file. Can Emacs select text based on regex and put it in kill-ring, so I ca开发者_如何学Gon 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:

  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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消