Align and Columnize Key/Value Data in Emacs

Posted on August 13, 2012

I finally got around to writing some shortcuts to aligning key/value data in Emacs for the languages I use the most:

Commas

(defun align-commas (beg end)
  (interactive "r")
  (align-regexp beg end ",\\(\\s-*\\)" 1 1 t))
this, is, a list
and another, one, at that
oh, goodie, gumdrops

... becomes ...

this,        is,     a list
and another, one,    at that
oh,          goodie, gumdrops

JSON Colons

(defun align-colons (beg end)
  (interactive "r")
  (align-regexp beg end ":\\(\\s-*\\)" 1 1 t))
{
  key: "value",
  like_a_boss: "hired",
  zip: zap
}

... becomes ...

{
  key:         "value",
  like_a_boss: "hired",
  zip:         zap
}

Ruby Hashes

(defun align-hash (beg end)
  (interactive "r")
  (align-regexp beg end "\\(\\s-*\\)\=\>\\(\\s-*\\)" 1 1 t))
{
  :crazy_hash => "value",
  :another_one => "foobar",
  :zip => "zap"
}

... becomes ...

{
  :crazy_hash  => "value",
  :another_one => "foobar",
  :zip         => "zap"
}

C-style Single-line Comments

(defun align-c-comment (beg end)
  (interactive "r")
  (align-regexp beg end "\\(-*\\)//" 1 0 t))
some sort of statement // this is a comment
another one // another
good gracious! does this work? // yes it does

... becomes ...

some sort of statement         // this is a comment
another one                    // another
good gracious! does this work? // yes it does

yay!!

comments powered by Disqus