litorgy.el 14 KB

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