6

Emacs has a Vim emulator mode called Evil. This mode has a search-replace function that does basically the same thing as highlighting a region and running sed on it. The brilliant thing about this function is that it shows a preview of the changes you're making in real time, before you execute the command, which is great for constructing search-replace commands that use regular expressions.

I am weak and do not want to retrain my muscle memory to use Vim keys. Is there a way of getting this sed-like search and replace function with preview in normal Emacs?

3 Answers 3

1

Emacs has replace-regexp which lets you do search and replace with regular expressions. I'm not aware of any tool that interactively previews replacements but there are several tools that allow you to interactively build the regular expressions used to do search and replace:

Emacs comes with re-builder. M-x re-builder will open a small buffer where can construct your regexp. It will highlight all matches in your current buffer with each group uniquely colored. Here is a nice summary about it.

Then there is re-builder+ which allows you to call the replace command with the regexp you build. But replacing is not interactive.

The last tool I know of is regex-tool which gives you a three buffer view with your text, your regex and the matched groups.

Those tools don't provide everything that Evil does by your description but they cover what I think the hardest part of searching and replacing with regular expression.

If you want to run it only on a region of the buffer you can use C-x n n to narrow to the selected region (between mark and point) or C-x n p to narrow to the current page. And then afterwards C-x n w to widen again to the whole buffer.

1

Take a look at Anzu, which came out a few months after this question was asked. It can perform interactive highlighting and replacement of text in both query-replace and query-replace-regexp forms.

In my .emacs, I override the default replace functions with their anzu equivalents as a former evil-user:

(global-set-key (kbd "M-%") 'anzu-query-replace)
(global-set-key (kbd "C-M-%") 'anzu-query-replace-regexp)
1
  • This is the correct answer to OP's question Dec 9, 2016 at 14:13
0

It's not exactly like sed, but C-M-% for query-replace-regexp lets you enter a regexp to search for and a replacement text. The interface is the same as for the more known M-% or query-replace, which searches for a plain text string.

You don't get to limit the search-and-replace to lines matching a certain pattern, but you can work around that. For example, the sed expression /foo/s/bar/baz/ could be emulated by searching for \(foo.*\)bar and replacing with \1baz (assuming that bar would always occur after foo on any of the interesting lines).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .