May 4, 2012

Rectangle replace in Emacs

Man, Emacs rocks! I love how it gives you a fighting chance to at figure out how to do almost anything.

Case in point: I was working on a project managed in subversion the other day. When I ran svn stat, I saw this:

$ svn stat
!       commons-logging.LICENSE
!       wsdl4j.LICENSE
!       jakarta-oro-2.0.7.LICENSE
!       servlet.jar
!       log4j-1.2.8.LICENSE
!       commons-fileupload.jar
!       commons-digester.jar
!       commons-discovery.LICENSE

Well, that's no good. All those things are dependencies and shouldn't be part of the codebase.

It doesn't look like a big deal, but I'm pretty lazy and would rather not have to repeatedly type svn rm ... 8 times.

Well, wouldn't you know?!, emacs has awesome ability to edit vertical (a.k.a block and/or rectangle) blocks of text.

Some of the relevant commands are:

  • kill-rectangle will delete a rectangular region of text
  • string-rectangle will prompt you for a string to use to replace a rectangular region of text.

Here are the emacs keystrokes I used:

  • put cursor before the line ! commons-logging.LICENSE
  • Then move cursor to the first c on commons-discovery.LICENSE.
  • Then do C-x r t to run the string-rectangle command
  • Then enter svn rm and then hit RET and you get this: svn rm commons-logging.LICENSE svn rm wsdl4j.LICENSE svn rm jakarta-oro-2.0.7.LICENSE svn rm servlet.jar svn rm log4j-1.2.8.LICENSE svn rm commons-fileupload.jar svn rm commons-digester.jar svn rm commons-discovery.LICENSE

Then simply cut and past this into a shell. Or, highlight and run `M-x shell-command-on-region` and voila!

Here's a live shot:

Example Rectangle Edit

Tags: emacs tech