litorgy.el 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. ;;; litorgy.el --- literate programming in org-mode
  2. ;; Copyright (C) 2009 Eric Schulte, Dan Davison, Austin F. Frank
  3. ;; Author: Eric Schulte, Dan Davison, Austin F. Frank
  4. ;; Keywords: literate programming, reproducible research
  5. ;; Homepage: http://orgmode.org
  6. ;; Version: 0.01
  7. ;;; License:
  8. ;; This program is free software; you can redistribute it and/or modify
  9. ;; it under the terms of the GNU General Public License as published by
  10. ;; the Free Software Foundation; either version 3, or (at your option)
  11. ;; any later version.
  12. ;;
  13. ;; This program is distributed in the hope that it will be useful,
  14. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. ;; GNU General Public License for more details.
  17. ;;
  18. ;; You should have received a copy of the GNU General Public License
  19. ;; along with GNU Emacs; see the file COPYING. If not, write to the
  20. ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  21. ;; Boston, MA 02110-1301, USA.
  22. ;;; Commentary:
  23. ;; See rorg.org in the parent directory for more information
  24. ;;; Code:
  25. (require 'org)
  26. (defun litorgy-execute-src-block-maybe ()
  27. "Detect if this is context for a litorgical src-block and if so
  28. then run `litorgy-execute-src-block'."
  29. (interactive)
  30. (let ((info (litorgy-get-src-block-info)))
  31. (if info (progn (litorgy-execute-src-block current-prefix-arg info) t) nil)))
  32. (add-hook 'org-ctrl-c-ctrl-c-hook 'litorgy-execute-src-block-maybe)
  33. (defvar litorgy-default-header-args '()
  34. "Default arguments to use when evaluating a source block.")
  35. (defvar litorgy-default-inline-header-args '((:results . "silent") (:exports . "results"))
  36. "Default arguments to use when evaluating an inline source block.")
  37. (defvar litorgy-src-block-regexp nil
  38. "Regexp used to test when inside of a litorgical src-block")
  39. (defvar litorgy-inline-src-block-regexp nil
  40. "Regexp used to test when on an inline litorgical src-block")
  41. (defun litorgy-set-interpreters (var value)
  42. (set-default var value)
  43. (setq litorgy-src-block-regexp
  44. (concat "#\\+begin_src \\("
  45. (mapconcat 'regexp-quote value "\\|")
  46. "\\)[ \t]*"
  47. "\\([ \t]+\\([^\n]+\\)\\)?\n" ;; match header arguments
  48. "\\([^\000]+?\\)#\\+end_src"))
  49. (setq litorgy-inline-src-block-regexp
  50. (concat "src_\\("
  51. (mapconcat 'regexp-quote value "\\|")
  52. "\\)"
  53. "\\(\\|\\[\\(.*\\)\\]\\)"
  54. "{\\([^\n]+\\)}")))
  55. (defun litorgy-add-interpreter (interpreter)
  56. "Add INTERPRETER to `litorgy-interpreters' and update
  57. `litorgy-src-block-regexp' appropriately."
  58. (unless (member interpreter litorgy-interpreters)
  59. (setq litorgy-interpreters (cons interpreter litorgy-interpreters))
  60. (litorgy-set-interpreters 'litorgy-interpreters litorgy-interpreters)))
  61. (defcustom litorgy-interpreters '()
  62. "Interpreters allows for evaluation tags.
  63. This is a list of program names (as strings) that can evaluate code and
  64. insert the output into an Org-mode buffer. Valid choices are
  65. R Evaluate R code
  66. emacs-lisp Evaluate Emacs Lisp code and display the result
  67. sh Pass command to the shell and display the result
  68. perl The perl interpreter
  69. python The python interpreter
  70. ruby The ruby interpreter
  71. The source block regexp `litorgy-src-block-regexp' is updated
  72. when a new interpreter is added to this list through the
  73. customize interface. To add interpreters to this variable from
  74. lisp code use the `litorgy-add-interpreter' function."
  75. :group 'litorgy
  76. :set 'litorgy-set-interpreters
  77. :type '(set :greedy t
  78. (const "R")
  79. (const "emacs-lisp")
  80. (const "sh")
  81. (const "perl")
  82. (const "python")
  83. (const "ruby")))
  84. ;;; functions
  85. (defun litorgy-execute-src-block (&optional arg info params)
  86. "Execute the current source code block, and dump the results
  87. into the buffer immediately following the block. Results are
  88. commented by `org-toggle-fixed-width-section'. With optional
  89. prefix don't dump results into buffer but rather return the
  90. results in raw elisp (this is useful for automated execution of a
  91. source block).
  92. Optionally supply a value for INFO in the form returned by
  93. `litorgy-get-src-block-info'.
  94. Optionally supply a value for PARAMS which will be merged with
  95. the header arguments specified at the source code block."
  96. (interactive)
  97. (let* ((info (or info (litorgy-get-src-block-info)))
  98. (lang (first info))
  99. (body (second info))
  100. (params (org-combine-plists (third info) params))
  101. (cmd (intern (concat "litorgy-execute:" lang)))
  102. result)
  103. ;; (message (format "params=%S" params)) ;; debugging statement
  104. (unless (member lang litorgy-interpreters)
  105. (error "Language is not in `litorgy-interpreters': %s" lang))
  106. (setq result (funcall cmd body params))
  107. ;; possibly force result into a vector
  108. (if (and (not (listp result)) (cdr (assoc :results params))
  109. (member "vector" (split-string (cdr (assoc :results params)))))
  110. (setq result (list result)))
  111. (if arg
  112. (message (format "%S" result))
  113. (litorgy-insert-result result (cdr (assoc :results params))))
  114. result))
  115. (defun litorgy-eval-buffer (&optional arg)
  116. "Replace EVAL snippets in the entire buffer."
  117. (interactive "P")
  118. (save-excursion
  119. (goto-char (point-min))
  120. (while (re-search-forward litorgy-regexp nil t)
  121. (litorgy-eval-src-block arg))))
  122. (defun litorgy-eval-subtree (&optional arg)
  123. "Replace EVAL snippets in the entire subtree."
  124. (interactive "P")
  125. (save-excursion
  126. (org-narrow-to-subtree)
  127. (litorgy-eval-buffer)
  128. (widen)))
  129. (defun litorgy-get-src-block-name ()
  130. "Return the name of the current source block if one exists"
  131. (let ((case-fold-search t))
  132. (save-excursion
  133. (goto-char (litorgy-where-is-src-block-head))
  134. (if (save-excursion (forward-line -1)
  135. (looking-at "#\\+srcname:[ \f\t\n\r\v]*\\([^ \f\t\n\r\v]+\\)"))
  136. (litorgy-clean-text-properties (match-string 1))))))
  137. (defun litorgy-get-src-block-info ()
  138. "Return the information of the current source block as a list
  139. of the following form. (language body header-arguments-alist)"
  140. (let ((case-fold-search t) head)
  141. (if (setq head (litorgy-where-is-src-block-head))
  142. (save-excursion (goto-char head) (litorgy-parse-src-block-match))
  143. (if (save-excursion ;; inline source block
  144. (re-search-backward "[ \f\t\n\r\v]" nil t)
  145. (forward-char 1)
  146. (looking-at litorgy-inline-src-block-regexp))
  147. (litorgy-parse-inline-src-block-match)
  148. nil)))) ;; indicate that no source block was found
  149. (defun litorgy-parse-src-block-match ()
  150. (list (litorgy-clean-text-properties (match-string 1))
  151. (litorgy-clean-text-properties (match-string 4))
  152. (org-combine-plists litorgy-default-header-args
  153. (litorgy-parse-header-arguments (litorgy-clean-text-properties (or (match-string 3) ""))))))
  154. (defun litorgy-parse-inline-src-block-match ()
  155. (list (litorgy-clean-text-properties (match-string 1))
  156. (litorgy-clean-text-properties (match-string 4))
  157. (org-combine-plists litorgy-default-inline-header-args
  158. (litorgy-parse-header-arguments (litorgy-clean-text-properties (or (match-string 3) ""))))))
  159. (defun litorgy-parse-header-arguments (arg-string)
  160. "Parse a string of header arguments returning an alist."
  161. (delq nil
  162. (mapcar
  163. (lambda (arg) (if (string-match "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]*\\([^ \f\t\n\r\v]+.*\\)" arg)
  164. (cons (intern (concat ":" (match-string 1 arg))) (match-string 2 arg))))
  165. (split-string (concat " " arg-string) "[ \f\t\n\r\v]+:" t))))
  166. (defun litorgy-where-is-src-block-head ()
  167. "Return the point at the beginning of the current source
  168. block. Specifically at the beginning of the #+BEGIN_SRC line.
  169. If the point is not on a source block then return nil."
  170. (let ((initial (point)) top bottom)
  171. (or
  172. (save-excursion ;; on a #+srcname: line
  173. (beginning-of-line 1)
  174. (and (looking-at "#\\+srcname") (forward-line 1)
  175. (looking-at litorgy-src-block-regexp)
  176. (point)))
  177. (save-excursion ;; on a #+begin_src line
  178. (beginning-of-line 1)
  179. (and (looking-at litorgy-src-block-regexp)
  180. (point)))
  181. (save-excursion ;; inside a src block
  182. (and
  183. (re-search-backward "#\\+begin_src" nil t) (setq top (point))
  184. (re-search-forward "#\\+end_src" nil t) (setq bottom (point))
  185. (< top initial) (< initial bottom)
  186. (goto-char top) (looking-at litorgy-src-block-regexp)
  187. (point))))))
  188. (defun litorgy-find-named-result (name)
  189. "Return the location of the result named NAME in the current
  190. buffer or nil if no such result exists."
  191. (save-excursion
  192. (goto-char (point-min))
  193. (when (re-search-forward (concat "#\\+resname:[ \t]*" (regexp-quote name)) nil t)
  194. (move-beginning-of-line 1) (point))))
  195. (defun litorgy-where-is-src-block-result ()
  196. "Return the point at the beginning of the result of the current
  197. source block. Specifically at the beginning of the #+RESNAME:
  198. line. If no result exists for this block then create a
  199. #+RESNAME: line following the source block."
  200. (save-excursion
  201. (goto-char (litorgy-where-is-src-block-head))
  202. (let ((name (litorgy-get-src-block-name)) end head)
  203. (or (and name (message name) (litorgy-find-named-result name))
  204. (and (re-search-forward "#\\+end_src" nil t)
  205. (progn (move-end-of-line 1) (forward-char 1) (setq end (point))
  206. (or (progn ;; either an unnamed #+resname: line already exists
  207. (re-search-forward "[^ \f\t\n\r\v]" nil t)
  208. (move-beginning-of-line 1) (looking-at "#\\+resname:"))
  209. (progn ;; or we need to back up and make one ourselves
  210. (goto-char end) (open-line 2) (forward-char 1)
  211. (insert (concat "#+resname:" (if name (concat " " name))))
  212. (move-beginning-of-line 1) t)))
  213. (point))))))
  214. (defun litorgy-insert-result (result &optional insert)
  215. "Insert RESULT into the current buffer after the end of the
  216. current source block. With optional argument INSERT controls
  217. insertion of results in the org-mode file. INSERT can take the
  218. following values...
  219. t ------ the default options, simply insert the results after the
  220. source block
  221. replace - insert results after the source block replacing any
  222. previously inserted results
  223. silent -- no results are inserted"
  224. (if insert (setq insert (split-string insert)))
  225. (if (stringp result)
  226. (progn
  227. (setq result (litorgy-clean-text-properties result))
  228. (if (member "file" insert) (setq result (litorgy-result-to-file result))))
  229. (unless (listp result) (setq result (format "%S" result))))
  230. (if (and insert (member "replace" insert)) (litorgy-remove-result))
  231. (if (= (length result) 0)
  232. (message "no result returned by source block")
  233. (if (and insert (member "silent" insert))
  234. (progn (message (format "%S" result)) result)
  235. (when (and (stringp result) ;; ensure results end in a newline
  236. (not (or (string-equal (substring result -1) "\n")
  237. (string-equal (substring result -1) "\r"))))
  238. (setq result (concat result "\n")))
  239. (save-excursion
  240. (goto-char (litorgy-where-is-src-block-result)) (forward-line 1)
  241. (if (stringp result) ;; assume the result is a table if it's not a string
  242. (if (member "file" insert)
  243. (insert result)
  244. (litorgy-examplize-region (point) (progn (insert result) (point))))
  245. (progn
  246. (insert
  247. (concat (orgtbl-to-orgtbl
  248. (if (consp (car result)) result (list result))
  249. '(:fmt (lambda (cell) (format "%S" cell)))) "\n"))
  250. (forward-line -1)
  251. (org-cycle))))
  252. (message "finished"))))
  253. (defun litorgy-result-to-org-string (result)
  254. "Return RESULT as a string in org-mode format. This function
  255. relies on `litorgy-insert-result'."
  256. (with-temp-buffer (litorgy-insert-result result) (buffer-string)))
  257. (defun litorgy-remove-result ()
  258. "Remove the result of the current source block."
  259. (save-excursion
  260. (goto-char (litorgy-where-is-src-block-result)) (forward-line 1)
  261. (delete-region (point)
  262. (save-excursion
  263. (if (org-at-table-p)
  264. (org-table-end)
  265. (while (if (looking-at "\\(: \\|\\[\\[\\)")
  266. (progn (while (looking-at "\\(: \\|\\[\\[\\)")
  267. (forward-line 1)) t))
  268. (forward-line 1))
  269. (forward-line -1)
  270. (point))))))
  271. (defun litorgy-result-to-file (result)
  272. "Return an `org-mode' link with the path being the value or
  273. RESULT, and the display being the `file-name-nondirectory' if
  274. non-nil."
  275. (let ((name (file-name-nondirectory result)))
  276. (concat "[[" result (if name (concat "][" name "]]") "]]"))))
  277. (defun litorgy-examplize-region (beg end)
  278. "Comment out region using the ': ' org example quote."
  279. (interactive "*r")
  280. (let ((size (abs (- (line-number-at-pos end)
  281. (line-number-at-pos beg)))))
  282. (if (= size 0)
  283. (let ((result (buffer-substring beg end)))
  284. (delete-region beg end)
  285. (insert (concat ": " result)))
  286. (save-excursion
  287. (goto-char beg)
  288. (dotimes (n size)
  289. (move-beginning-of-line 1) (insert ": ") (forward-line 1))))))
  290. (defun litorgy-clean-text-properties (text)
  291. "Strip all properties from text return."
  292. (set-text-properties 0 (length text) nil text) text)
  293. (defun litorgy-read (cell)
  294. "Convert the string value of CELL to a number if appropriate.
  295. Otherwise if cell looks like a list (meaning it starts with a
  296. '(') then read it as lisp, otherwise return it unmodified as a
  297. string.
  298. This is taken almost directly from `org-read-prop'."
  299. (if (and (stringp cell) (not (equal cell "")))
  300. (if (litorgy-number-p cell)
  301. (string-to-number cell)
  302. (if (or (equal "(" (substring cell 0 1))
  303. (equal "'" (substring cell 0 1)))
  304. (read cell)
  305. (progn (set-text-properties 0 (length cell) nil cell) cell)))
  306. cell))
  307. (defun litorgy-number-p (string)
  308. "Return t if STRING represents a number"
  309. (string-match "^[[:digit:]]*\\.?[[:digit:]]*$" string))
  310. (defun litorgy-chomp (string &optional regexp)
  311. "Remove any trailing space or carriage returns characters from
  312. STRING. Default regexp used is \"[ \f\t\n\r\v]\" but can be
  313. overwritten by specifying a regexp as a second argument."
  314. (while (string-match "[ \f\t\n\r\v]" (substring results -1))
  315. (setq results (substring results 0 -1)))
  316. results)
  317. (provide 'litorgy)
  318. ;;; litorgy.el ends here