Mapping over table rows in org-mode

9 Mar 19

dev

I’m an Emacs guy, and so if I’ve got some simple tabular data I’d much rather keep it in an org-mode table than have to fire up Excel.

Here’s an example:

#+NAME: pap-table
| first name  | last name | yearly-income |
|-------------|-----------|---------------|
| Mr          | Bennett   |          2000 |
| Fitzwilliam | Darcy     |         10000 |
| Charles     | Bingley   |          5000 |

If the prospect of having to keep all those | characters manually aligned is freaking you out, don’t worry—orgtbl-mode does it all for you automatically.

Now, I often want to get my functional programming on and apply a function to all the rows of the table. Org-mode does have some special syntax with bunch of cool features for doing arithmetic on the cells (just like Excel formulas) but I’m usually happier just writing regular elisp to get the job done.

The nicest1 way I’ve found to do this is to give the table a name (in the example above the table name is pap-table—can you guess why?). Then, you can tell an elisp code block about the data in that table like so (note the :var table=pap-table at the start):

#+BEGIN_SRC emacs-lisp :var table=pap-table
  (-map
   (lambda (row)
     (cl-destructuring-bind (first last income) row
       (list
        (format "Mr. %s is a man of %s fortune; %s a year."
                last
                (if (< income 2500) "small" "large")
                income))))
   table)
#+END_SRC

Then, when you evaluate the code block with C-c C-c (or just , , in Spacemacs) it’ll return the “result”:

#+RESULTS:
| Mr. Bennett is a man of small fortune; 2000 a year. |
| Mr. Darcy is a man of large fortune; 10000 a year.  |
| Mr. Bingley is a man of large fortune; 5000 a year. |

This is really handy, as you can imagine. I use it for all sorts of things, including sending “mail merge” emails with template values (since I also use Emacs as my mail client—sending an email is just an elisp function call away).

Caveats

There are a few “tricks” in the above process which took me a while to figure out, so hopefully by listing them here I can save others a bunch of time & hassle.

Footnotes

  1. if there’s a nicer way, please let me know!

Cite this post
@online{swift2019mappingOverTableRowsInOrgMode,
  author = {Ben Swift},
  title = {Mapping over table rows in org-mode},
  url = {https://benswift.me/blog/2019/03/09/mapping-over-table-rows-in-org-mode/},
  year = {2019},
  month = {03},
  note = {AT-URI: at://did:plc:tevykrhi4kibtsipzci76d76/site.standard.document/2019-03-09-mapping-over-table-rows-in-org-mode},
}