litorgy.el 14 KB

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