A Diff Preview Of A Regex Replace

When it rains, it pours. Sometimes I find it hard to find an interesting topic to write about. Other times, like today, four or five topics pop up. The problem is that today is Sunday and tomorrow Sacha will be publishing her weekly Emacs News. I generally try not to write about things that she’s already covered but I may have to break that rule for some of these interesting topics.

For me, the most exciting thing I’ve found today is Bozhidar Batsov’s post on Preview Regex Replacements as Diffs. It addresses a problem we’ve all had. You want to do a query-replace-regexp on a large file—or even multiple files—but you’re a bit nervous that maybe your regex isn’t quite right and the command might make a change you don’t want. So you step through each change, which is time consuming and a pain.

As Batsov explains, that got a lot easier in Emacs 30. There’s a new command, replace-regexp-as-diff that runs the regexp replace process but instead of actually making the changes, it produces a diff file in a separate buffer. That way you can see all the changes that would be made. If you’re happy with them, you can simply apply the diff buffer as a patch with diff-ediff-patch to apply them. If you’re not happy, you can simply delete the diff buffer.

There are two related commands: multi-file-replace-regexp-as-diff and dired-do-replace-regexp-as-diff for handling multiple files. The Dired variety is probably the easiest to use because you can simply mark the files you want to change in a Dired buffer and call dired-do-replace-regexp-as-diff to generate a diff for them all.

Batsov speculates that in the age of AI, people won’t be as interested in this type of command. I disagree strongly. It’s useful not only for coding but for writing pose or any other text-based file that you might want to edit.

If you’re an Emacs user, I urge you to take a look at Batsov’s post. It’s about a really useful new(ish) feature of Emacs that you can probably make good use of.

This entry was posted in General and tagged . Bookmark the permalink.