litorgy.el 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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. (if arg
  104. (message (format "%S" result))
  105. (litorgy-insert-result result (cdr (assoc :results params))))
  106. result))
  107. (defun litorgy-eval-buffer (&optional arg)
  108. "Replace EVAL snippets in the entire buffer."
  109. (interactive "P")
  110. (save-excursion
  111. (goto-char (point-min))
  112. (while (re-search-forward litorgy-regexp nil t)
  113. (litorgy-eval-src-block arg))))
  114. (defun litorgy-eval-subtree (&optional arg)
  115. "Replace EVAL snippets in the entire subtree."
  116. (interactive "P")
  117. (save-excursion
  118. (org-narrow-to-subtree)
  119. (litorgy-eval-buffer)
  120. (widen)))
  121. (defun litorgy-get-src-block-name ()
  122. "Return the name of the current source block if one exists"
  123. (let ((case-fold-search t))
  124. (save-excursion
  125. (goto-char (litorgy-where-is-src-block-head))
  126. (if (save-excursion (forward-line -1)
  127. (looking-at "#\\+srcname:[ \f\t\n\r\v]*\\([^ \f\t\n\r\v]+\\)"))
  128. (litorgy-clean-text-properties (match-string 1))))))
  129. (defun litorgy-get-src-block-info ()
  130. "Return the information of the current source block as a list
  131. of the following form. (language body header-arguments-alist)"
  132. (let ((case-fold-search t) head)
  133. (if (setq head (litorgy-where-is-src-block-head))
  134. (save-excursion (goto-char head) (litorgy-parse-src-block-match))
  135. (if (save-excursion ;; inline source block
  136. (re-search-backward "[ \f\t\n\r\v]" nil t)
  137. (forward-char 1)
  138. (looking-at litorgy-inline-src-block-regexp))
  139. (litorgy-parse-inline-src-block-match)
  140. nil)))) ;; indicate that no source block was found
  141. (defun litorgy-parse-src-block-match ()
  142. (list (litorgy-clean-text-properties (match-string 1))
  143. (litorgy-clean-text-properties (match-string 4))
  144. (litorgy-parse-header-arguments (litorgy-clean-text-properties (or (match-string 3) "")))))
  145. (defun litorgy-parse-inline-src-block-match ()
  146. (list (litorgy-clean-text-properties (match-string 1))
  147. (litorgy-clean-text-properties (match-string 4))
  148. (org-combine-plists litorgy-inline-header-args
  149. (litorgy-parse-header-arguments (litorgy-clean-text-properties (or (match-string 3) ""))))))
  150. (defun litorgy-parse-header-arguments (arg-string)
  151. "Parse a string of header arguments returning an alist."
  152. (delq nil
  153. (mapcar
  154. (lambda (arg) (if (string-match "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]*\\([^ \f\t\n\r\v]+.*\\)" arg)
  155. (cons (intern (concat ":" (match-string 1 arg))) (match-string 2 arg))))
  156. (split-string (concat " " arg-string) "[ \f\t\n\r\v]+:" t))))
  157. (defun litorgy-where-is-src-block-head ()
  158. "Return the point at the beginning of the current source
  159. block. Specifically at the beginning of the #+BEGIN_SRC line.
  160. If the point is not on a source block then return nil."
  161. (let ((initial (point)) top bottom)
  162. (or
  163. (save-excursion ;; on a #+srcname: line
  164. (beginning-of-line 1)
  165. (and (looking-at "#\\+srcname") (forward-line 1)
  166. (looking-at litorgy-src-block-regexp)
  167. (point)))
  168. (save-excursion ;; on a #+begin_src line
  169. (beginning-of-line 1)
  170. (and (looking-at litorgy-src-block-regexp)
  171. (point)))
  172. (save-excursion ;; inside a src block
  173. (and
  174. (re-search-backward "#\\+begin_src" nil t) (setq top (point))
  175. (re-search-forward "#\\+end_src" nil t) (setq bottom (point))
  176. (< top initial) (< initial bottom)
  177. (goto-char top) (looking-at litorgy-src-block-regexp)
  178. (point))))))
  179. (defun litorgy-find-named-result (name)
  180. "Return the location of the result named NAME in the current
  181. buffer or nil if no such result exists."
  182. (save-excursion
  183. (goto-char (point-min))
  184. (when (re-search-forward (concat "#\\+resname:[ \t]*" (regexp-quote name)) nil t)
  185. (move-beginning-of-line 1) (point))))
  186. (defun litorgy-where-is-src-block-result ()
  187. "Return the point at the beginning of the result of the current
  188. source block. Specifically at the beginning of the #+RESNAME:
  189. line. If no result exists for this block then create a
  190. #+RESNAME: line following the source block."
  191. (save-excursion
  192. (goto-char (litorgy-where-is-src-block-head))
  193. (let ((name (litorgy-get-src-block-name)) end head)
  194. (or (and name (message name) (litorgy-find-named-result name))
  195. (and (re-search-forward "#\\+end_src" nil t)
  196. (progn (move-end-of-line 1) (forward-char 1) (setq end (point))
  197. (or (progn ;; either an unnamed #+resname: line already exists
  198. (re-search-forward "[^ \f\t\n\r\v]" nil t)
  199. (move-beginning-of-line 1) (looking-at "#\\+resname:"))
  200. (progn ;; or we need to back up and make one ourselves
  201. (goto-char end) (open-line 2) (forward-char 1)
  202. (insert "#+resname:") (move-beginning-of-line 1) t)))
  203. (point))))))
  204. (defun litorgy-insert-result (result &optional insert)
  205. "Insert RESULT into the current buffer after the end of the
  206. current source block. With optional argument INSERT controls
  207. insertion of results in the org-mode file. INSERT can take the
  208. following values...
  209. t ------ the default options, simply insert the results after the
  210. source block
  211. replace - insert results after the source block replacing any
  212. previously inserted results
  213. silent -- no results are inserted"
  214. (if insert (setq insert (split-string insert)))
  215. (if (stringp result)
  216. (progn
  217. (setq result (litorgy-clean-text-properties result))
  218. (if (member "file" insert) (setq result (litorgy-result-to-file result))))
  219. (unless (listp result) (setq result (format "%S" result))))
  220. (if (and insert (member "replace" insert)) (litorgy-remove-result))
  221. (if (= (length result) 0)
  222. (message "no result returned by source block")
  223. (if (and insert (member "silent" insert))
  224. (progn (message (format "%S" result)) result)
  225. (when (and (stringp result) ;; ensure results end in a newline
  226. (not (or (string-equal (substring result -1) "\n")
  227. (string-equal (substring result -1) "\r"))))
  228. (setq result (concat result "\n")))
  229. (save-excursion
  230. (goto-char (litorgy-where-is-src-block-result)) (forward-line 1)
  231. (if (stringp result) ;; assume the result is a table if it's not a string
  232. (if (member "file" insert)
  233. (insert result)
  234. (litorgy-examplize-region (point) (progn (insert result) (point))))
  235. (progn
  236. (insert
  237. (concat (orgtbl-to-orgtbl
  238. (if (consp (car result)) result (list result))
  239. '(:fmt (lambda (cell) (format "%S" cell)))) "\n"))
  240. (forward-line -1)
  241. (org-cycle))))
  242. (message "finished"))))
  243. (defun litorgy-result-to-org-string (result)
  244. "Return RESULT as a string in org-mode format. This function
  245. relies on `litorgy-insert-result'."
  246. (with-temp-buffer (litorgy-insert-result result) (buffer-string)))
  247. (defun litorgy-remove-result ()
  248. "Remove the result of the current source block."
  249. (save-excursion
  250. (goto-char (litorgy-where-is-src-block-result)) (forward-line 1)
  251. (delete-region (point)
  252. (save-excursion
  253. (if (org-at-table-p)
  254. (org-table-end)
  255. (while (if (looking-at "\\(: \\|\\[\\[\\)")
  256. (progn (while (looking-at "\\(: \\|\\[\\[\\)")
  257. (forward-line 1)) t))
  258. (forward-line 1))
  259. (forward-line -1)
  260. (point))))))
  261. (defun litorgy-result-to-file (result)
  262. "Return an `org-mode' link with the path being the value or
  263. RESULT, and the display being the `file-name-nondirectory' if
  264. non-nil."
  265. (let ((name (file-name-nondirectory result)))
  266. (concat "[[" result (if name (concat "][" name "]]") "]]"))))
  267. (defun litorgy-examplize-region (beg end)
  268. "Comment out region using the ': ' org example quote."
  269. (interactive "*r")
  270. (let ((size (abs (- (line-number-at-pos end)
  271. (line-number-at-pos beg)))))
  272. (if (= size 0)
  273. (let ((result (buffer-substring beg end)))
  274. (delete-region beg end)
  275. (insert (concat ": " result)))
  276. (save-excursion
  277. (goto-char beg)
  278. (dotimes (n size)
  279. (move-beginning-of-line 1) (insert ": ") (forward-line 1))))))
  280. (defun litorgy-clean-text-properties (text)
  281. "Strip all properties from text return."
  282. (set-text-properties 0 (length text) nil text) text)
  283. (defun litorgy-read (cell)
  284. "Convert the string value of CELL to a number if appropriate.
  285. Otherwise if cell looks like a list (meaning it starts with a
  286. '(') then read it as lisp, otherwise return it unmodified as a
  287. string.
  288. This is taken almost directly from `org-read-prop'."
  289. (if (and (stringp cell) (not (equal cell "")))
  290. (if (litorgy-number-p cell)
  291. (string-to-number cell)
  292. (if (or (equal "(" (substring cell 0 1))
  293. (equal "'" (substring cell 0 1)))
  294. (read cell)
  295. (progn (set-text-properties 0 (length cell) nil cell) cell)))
  296. cell))
  297. (defun litorgy-number-p (string)
  298. "Return t if STRING represents a number"
  299. (string-match "^[[:digit:]]*\\.?[[:digit:]]*$" string))
  300. (defun litorgy-chomp (string &optional regexp)
  301. "Remove any trailing space or carriage returns characters from
  302. STRING. Default regexp used is \"[ \f\t\n\r\v]\" but can be
  303. overwritten by specifying a regexp as a second argument."
  304. (while (string-match "[ \f\t\n\r\v]" (substring results -1))
  305. (setq results (substring results 0 -1)))
  306. results)
  307. (provide 'litorgy)
  308. ;;; litorgy.el ends here