Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I preview a regular expression in search/replace?

Is there a package (or free-floating elisp) around that dynamically previews both the matches and the effect of a regular expression search/replace in Emacs? I believe a few specialized modes offer something like this, but I haven't been able to find a universal solution.

I should note that I'm familiar with regexp-builder, but it only previews matches and requires me to copy strings between buffers---not a perfect solution.

like image 464
Karl Avatar asked Dec 27 '22 14:12

Karl


2 Answers

One way to 'preview the matches' is by entering the regexp via isearch-forward-regexp (C-M-s) which interactively highlights matches as you write the regexp, and then calling isearch-query-replace-regexp with C-M-% (i.e. the normal query-replace-regexp binding).

To see the matches throughout the buffer (as opposed to just the visible portion), you can type M-so while entering the isearch regexp to run isearch-occur. The minibuffer remains selected, so you can continue editing the regexp.

I'm not sure about 'previewing' the replacements. I suspect most people simply do the replacement, and undo it again if it was a mistake? (and I'm not sure there's a big different between that and a preview feature).

Edit: I guess the occur buffer does facilitate a 'replacement preview' option of sorts. It's restricted to the occur buffer, but maybe that's good enough.

Emacs 24 has a rather useful occur-edit-mode: Type e in the occur buffer and you can edit the matches as text (so you can perform a search & replace in that buffer). After editing the occur buffer, you type C-cC-c to write the changes back to the original buffer(s); but until you do that, the changes only exist in the occur buffer itself, as a preview of what will happen if you confirm them.

As-is, that doesn't combine as smoothly as you might want with the original part of this answer, but it certainly seemed worth mentioning.

Edit 2: Ooh, okay, my previous edit was a lie. Or at least not remotely consistent enough for what I'd written. I thought that occur edit mode didn't make the changes to the original buffers immediately, and sometimes that's true, but most of the time it updates the original buffer at the same time as the occur buffer. I'm not sure why it's not consistent, but obviously you can't treat it as a preview, as I had suggested.

like image 45
phils Avatar answered Jan 05 '23 08:01

phils


visual-regexp allows previewing replacements inline:

enter image description here

like image 117
Vladimir Panteleev Avatar answered Jan 05 '23 08:01

Vladimir Panteleev