Query Replace with Occur

Over at (with-Emacs, Clemens Radermacher has posted a short tutorial on using occur and query-replace across several files. It’s sort of a riff on abo-abo’s post on refactoring multiple files. To a first order approximation, the idea is to use occur to locate the term of interest, put the occur buffer in edit mode, and then use query-replace or your favorite replacement tool to make the actual substitutions.

This works fine if you’re interested in a single buffer but if the text of interest is spread across several buffers, you need to use multi-occur. I can’t ever remember doing this because multi-occur is hard to use. You have to specify each buffer you’re interested in and while you can make this a little easier with multi-occur-in-matching-buffers, it isn’t ideal either.

For me, the most interesting thing about Radermacher’s post is his recommendation to use Nicolas Petton’s noccur. It’s just like occur—actually, it’s a front end to the multi-occur command—but you can ask it to operate on all files in a project or all the files marked in a dired buffer. Noccur will load the requested files into buffers and call multi-occur.

There are plenty of other ways of doing this but Radermacher’s solution works in a seamless way for project files and dired-marked files. It’s definitely worth knowing the technique. Radermacher offers some code snippets to provide a bit of context for your replacement decisions and to solve a couple of other problems. It’s a good post and definitely worth taking the time to read.

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