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")))
        "gs %s -o %s %s"
        (mapconcat #'identity flags " ")
        (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.


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

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