Warp Refactoring With Emacs

Ashton Wiersdorf has a very interesting post on refactoring in Emacs. His problem is a simple one: we wants to replace all occurrences of set_XXX_config! (where XXX varies) to config_XXX! for all files in a directory. He uses several packages to support this but the only one really necessary is wgrep, which make a search results buffer writable and saves the changes to it back to the original files.

His strategy is to

  1. grep for the appropriate regex,
  2. put the search results in a separate buffer
  3. make the buffer writable with wgrep
  4. use something like replace-regexp to change the identifiers
  5. save the results back to the original files

If you’ve been around Irreal for a while, this probably seems familiar. In abo-abo’s original post, he used rgrep so he didn’t need to worry about getting the results into another buffer but my process uses counsel-rg so I need a Ctrl+c Ctrl+o to move the results from the minibuffer to a separate buffer. After that, things are mostly the same. The nice thing is that Ivy handles all this for me and I don’t need any other packages besides wgrep.

This is a great way to refactor. The process, Wiersdorf says, is better than trying to do it from within an IDE using some sort of language server because it finds and changes all occurrences of the target identifiers including those in, say, documentation files that a language server is not going to find. It’s my favorite way of solving this problem. After you try it, it will probably become yours too.

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