When I am refactoring code, I often need to make the same change in my files. My current workflow is often something like this:

  • M-x grep for foo.bar.baz
  • Go to first hit
  • M-x replace-string RET foo.bar RET foo
  • Go to next hit
  • Repeat previous two lines until no more hits

Keyboard macros and M-p can help with this, but I tried to write a function to do all the replacements in a simple command: M-x my-replace-grep-hits RET foo.bar RET foo.

I am having trouble figuring out how to actually get to the file with the error. It seems that

      (compilation-next-file 1)

should do what I want, but I get an error that the buffer is read-only, so clearly compile-goto-error is not changing the buffer when I call it programatically.

What do I need to do?

  • Check out wgrep when combined with the power of multiple-cursors. Once you do, you will probably never look back. When it is active, after doing a regular grep or recursive grep, I just hit: C-c C-p (which is wgrep-change-to-wgrep-mode), and then I activate multiple-cursors by Magnar Sveen and make my edits all in one fell swoop, and then I exit that multiple-cursor mode and type C-x C-s (which is wgrep-finish-edit). – lawlist Oct 4 '19 at 2:40
  • Pro tip when working with wgrep / multiple-cursors: When dealing with an enormous amount of changes; e.g., 500 or more, multiple-cursors can get bogged down and become slow ... In such a case, replace-string when wgrep is active works well to change all occurrences. – lawlist Oct 4 '19 at 3:22
  • What about using function next-error? – Marco Wahl Oct 5 '19 at 8:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.