Org Mode PostScript Source Blocks

org ps

Table of Contents

Hacky org-babel execute function for generating images from PostScript source blocks in Org Mode .

(defun org-babel-execute:ps (body params)
  "Execute a block of PostScript code with org-babel.
This function is called by `org-babel-execute-src-block'."
  (let* ((session (cdr (assq :session params)))
         (size (cdr (assq :size params)))
         (parent-dir (file-name-directory (buffer-file-name)))
         (outfile (or (cdr (assq :outfile params)) "out.pdf"))
         (flags (list (or (cdr (assq :flags params)) "")))
         (outfile-abs (concat parent-dir outfile))
         (result-type (cdr (assq :result-type params)))
         (full-body (org-babel-expand-body:generic
                     ;; TODO: Handle variables
                     body params nil)))
    (pp full-body)
    (if (string= (file-name-extension outfile) "png")
        (push "-sDEVICE=png16m" flags)
      (push "-sDEVICE=pdfwrite" flags))
    (if size (push (format "-g%s" size) flags))

    (let ((script-file (org-babel-temp-file "ghostscript-")))
      (with-temp-file script-file
        (insert full-body)
        (unless (string-suffix-p "showpage" (string-trim-right full-body))
          (insert "\nshowpage")))
      (org-babel-eval
       (format
        "gs %s -o %s %s"
        (mapconcat #'identity flags " ")
        outfile-abs
        (org-babel-process-file-name script-file))
       ""))
    (org-babel-result-cond (cdr (assq :result-params params)) outfile outfile)))

The PNG output device expects a showpage at the end of the code. This will be inserted automatically.

Usage

#+begin_src ps :results file :size 1000x1000 :outfile images/ps/lines.png :exports both
   % PostScript code
#+end_src

If you have an idea how this page could be improved or a comment send me a mail.