2011-07-08

Bash/Emacs Rename Refactoring

In my last post I was talking about using Emacs as an IDE for Scala. I imagine you might have a range of objections to such a thing. For instance, what about renaming a class? Between bash and Emacs, it's easy enough. Suppose I want to rename a class from BeezleBopple to BoppleBeezle. Assuming I am confident that there are no occurrences of the text "BeezleBopple" in my code that is not a reference to this class, (this is never really a problem for me, as I tend to name my classes things like CurrentBatchSelectionChangedEvent), I can perform the following steps.
First, in bash:
find */src -name *.scala -exec sed -i 's/BeezleBopple/BoppleBeezle/g' {} \;
This should replace all occurrences in my source files. A couple warnings before you do this. This has the potential to do a lot of damage if something goes wrong. So commit to your version control system first. That way, if anything goes wrong, you can just revert to the latest checked in version. Secondly, this is going to cause you problems if you have any unsaved changes in any of your Emacs buffers. So issue a M-x s to Emacs first to save any outstanding changes.

One really nice thing about Scala is that everything still works if my class BoppleBeezle is defined in a file named BeezleBopple.scala. So at this point, I can switch over to the window where I am running continuous compilation via sbt, and I should be able to see things compiling (and maybe tesing) successfully. Now I can rename the source file, something like this for me:
svn mv path/to/BeezleBopple.scala path/to/BoppleBeezle.scala
Again, I switch over to my sbt window and see that everything still compiles.

One last problem. I potentially have a whole slew of Emacs buffers open that are now out of date. I want to tell Emacs to reload them all. There are various discussions of different ways to do this, including this Stack Overflow post. I ended up using the global-auto-revert-mode suggestion, which is explained in detail in the Emacs manual. I don't want this setting on all the time, so I run M-x global-auto-revert-mode once to update all my buffers, and run the same command again to turn it off.

Easy! Okay, it's slightly more work than the same thing in Eclipse, but my hands never left the keyboard for the mouse.

No comments:

Post a Comment