[ESS] ESS/R transcript with embedded graphics

Short, Tom TShort at epri.com
Wed Aug 5 04:43:10 CEST 2009

This email describes two things I've cobbled together:

  + HTML export of an R session with syntax highlighting and inline
    graphics (prettyR is a different way to get this). See enclosed
    for a pdf of a part of a transcript of the graphics demo printed 
    to pdf.
  + Transcript of an R session with inline graphics in Emacs

It's a way to document work during the "exploratory stage".

Both are independent of each other. Both require you to use the
function "showplot" to create a copy of the graphic and indicate where
to put it. So you need to do:

> plot(sin)
> showplot() # the image is shown after this
> plot(cos)
> showplot("cos.png") # give it a local name

First, here's showplot:

showplot <- function(file = paste(tempfile(), ".png", sep = ""), ...) {
    file <- gsub("\\\\", "/", file)    # Needed on windows as iimage.el
doesn't like back slashes
    din <- dev.size("in")
    dev2bitmap(file, width = din[1], height = din[2], taa = 4, gaa = 2,
    cat("{{", file, "}}\n", sep = "")

This copies the current graph to a PNG file (a temporary file by
default). It outputs the name of the buffer between a set of curly
brackets. These curly brackets are used to insert the graphic into the
emacs buffer and for exporting to HTML.

HTML export
This relies on htmlize by Hrvoje Niksic.


Run the following emacs lisp function to htmlize and launch your
browser. In the process, it substitutes the {{whatever}} with
appropriate html links.

(defun htmlize-buffer-with-images ()
  "Convert buffer to html, including embedded images.
Creates a file called emacs-html-export.html in the current directory"
  (require 'htmlize)
    (switch-to-buffer (htmlize-buffer (current-buffer)))
    (goto-char (point-min))
    ; replace the {{file.png}} with <img src='file.png'/>
    (while (re-search-forward "{{\\([-+./_0-9a-zA-Z:\\\\].*\\)}}" nil t)
      (replace-match (concat "<img src='\\1'/>")))
    ;; cludge for Firefox/windows absolute paths: add // in front of c:
    (goto-char (point-min))
    (while (re-search-forward "<img src='\\(.:\\)" nil t)
      (replace-match (concat "<img src='//\\1")))
    (write-file "emacs-html-export.html")

Inline images in your emacs buffer
This uses iimage, a minor mode by KOSEKI Yoshinori. It's included with
GNU Emacs 23 and is also here:


You need the following for your regex for image replacement, then just
run "iimage-mode".

(setq iimage-mode-image-regex-alist
  `((,(concat "\\({{\\)"
          "\\(}}\\)") . 2)))

With iimage, it doesn't automatically show graphics. Maybe a
hook could be added.

Note that most of this is only useful with ess-eval-visibly-p set 
to t. Finally, this has only been tested on GNU Emacs 22 under
Windows XP with R 2.9.0.

- Tom 

Tom Short
Electric Power Research Institute (EPRI)

More information about the ESS-help mailing list