Miskatonic University Press

Prettifying R in Emacs

r emacs

Emacs 24.4 has a new feature: prettify-symbols-mode. Bozhidar Batsov wrote about it and I’ve seen other mentions of it in discussions of what’s coming when this new version is released. It’s not out yet, but I decided to stop waiting and compile from source so I can run the latest development version because there was something I wanted to do.

I use R a lot, and I use Emacs to edit it with ESS mode. In R I’m a great user of Hadley Wickham’s dplyr package (the vignette has examples that show its power), and so I spend a lot of time writing %>% (“x %>% f(y) turns into f(x, y)” says the docs).

As great as dplyr is, I thought its %>% wasn’t very eyepleasing, so I made Emacs show me the pipe symbol when actually the R operator is there. On top of that, the built-in prettifying already takes care of turning <- into (Unicode LEFTWARDS ARROW).

So when I write this:

usage <- read.csv("refworks-usage.csv")
usage <- tbl_df(usage)

## Which accounts have logged in the most?
usage %>% select(user_id, name, number_of_logins) %>% arrange(desc(number_of_logins))

What I see is:

usage  read.csv("refworks-usage.csv")
usage  tbl_df(usage)

## Which accounts have logged in the most?
usage | select(user_id, name, number_of_logins) | arrange(desc(number_of_logins))

I think that’s much nicer. It shows a lot better in a screenshot:

Screenshot of Emacs prettifying R

Beautiful!

It also works in the interactive mode, at an R session with a REPL, and does the prettifying on the fly there. Copying and pasting from one to the other works perfectly because what’s copied and executed is different from what I see.

How I got it working

As I said, this requires Emacs 24.4, which will be released soon, so you can wait for that or compile from source. Xah Lee’s How to build Emacs from git Repository and How to build Emacs on Linux are helpful; all I had to do to prepare to get it to compile was add a few missing packages with sudo install libgtk-3-dev libxpm-dev libgif-dev.

With that done, I was now running 25.0.50.1 (they’re moving from 24.4 to 25), and I added this to ~/.emacs.d/init.el in my Emacs config:

(when (boundp 'global-prettify-symbols-mode)
  (add-hook 'ess-mode-hook
            (lambda ()
              (push '("%>%" . ?|) prettify-symbols-alist)
	      ))
  (add-hook 'inferior-ess-mode-hook
            (lambda ()
              (push '("%>%" . ?|) prettify-symbols-alist)
	      ))
  (global-prettify-symbols-mode +1))

Except it doesn’t actually look like that, it looks like this, with lambda (an anonymous function) replaced by λ:

(when (boundp 'global-prettify-symbols-mode)
  (add-hook 'ess-mode-hook
            (λ ()
              (push '("%>%" . ?|) prettify-symbols-alist)
	      ))
  (add-hook 'inferior-ess-mode-hook
            (λ ()
              (push '("%>%" . ?|) prettify-symbols-alist)
	      ))
  (global-prettify-symbols-mode +1))