ob.el 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614
  1. ;;; ob.el --- working with code blocks in org-mode
  2. ;; Copyright (C) 2009, 2010 Free Software Foundation, Inc.
  3. ;; Author: Eric Schulte, Dan Davison
  4. ;; Keywords: literate programming, reproducible research
  5. ;; Homepage: http://orgmode.org
  6. ;; Version: 0.01
  7. ;; This file is part of GNU Emacs.
  8. ;; GNU Emacs 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 of the License, or
  11. ;; (at your option) any later version.
  12. ;; GNU Emacs is distributed in the hope that it will be useful,
  13. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. ;; GNU General Public License for more details.
  16. ;; You should have received a copy of the GNU General Public License
  17. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  18. ;;; Commentary:
  19. ;; See the online documentation for more information
  20. ;;
  21. ;; http://orgmode.org/worg/org-contrib/babel/
  22. ;;; Code:
  23. (eval-when-compile (require 'cl))
  24. (eval-and-compile
  25. (unless (fboundp 'declare-function)
  26. (defmacro declare-function (fn file &optional arglist fileonly))))
  27. (defvar org-babel-call-process-region-original)
  28. (declare-function show-all "outline" ())
  29. (declare-function tramp-compat-make-temp-file "tramp" (filename &optional dir-flag))
  30. (declare-function tramp-dissect-file-name "tramp" (name &optional nodefault))
  31. (declare-function tramp-file-name-user "tramp" (vec))
  32. (declare-function tramp-file-name-host "tramp" (vec))
  33. (declare-function org-edit-src-code "org" (context code edit-buffer-name))
  34. (declare-function org-open-at-point "org" (&optional in-emacs reference-buffer))
  35. (declare-function org-save-outline-visibility "org" (use-markers &rest body))
  36. (declare-function org-narrow-to-subtree "org" ())
  37. (declare-function org-entry-get "org" (pom property &optional inherit))
  38. (declare-function org-make-options-regexp "org" (kwds &optional extra))
  39. (declare-function org-match-string-no-properties "org" (num &optional string))
  40. (declare-function org-do-remove-indentation "org" (&optional n))
  41. (declare-function org-show-context "org" (&optional key))
  42. (declare-function org-at-table-p "org" (&optional table-type))
  43. (declare-function org-cycle "org" (&optional arg))
  44. (declare-function org-uniquify "org" (list))
  45. (declare-function org-table-import "org" (file arg))
  46. (declare-function org-add-hook "org-compat" (hook function &optional append local))
  47. (declare-function org-table-align "org-table" ())
  48. (declare-function org-table-end "org-table" (&optional table-type))
  49. (declare-function orgtbl-to-generic "org-table" (table params))
  50. (declare-function orgtbl-to-orgtbl "org-table" (table params))
  51. (declare-function org-babel-lob-get-info "ob-lob" nil)
  52. (declare-function org-babel-ref-split-args "ob-ref" (arg-string))
  53. (declare-function org-babel-ref-variables "ob-ref" (params))
  54. (declare-function org-babel-ref-resolve-reference "ob-ref" (ref &optional params))
  55. (defvar org-babel-source-name-regexp
  56. "^[ \t]*#\\+\\(srcname\\|source\\|function\\):[ \t]*"
  57. "Regular expression used to match a source name line.")
  58. (defvar org-babel-src-block-regexp
  59. (concat
  60. ;; (1) indentation (2) lang
  61. "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
  62. ;; (3) switches
  63. "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
  64. ;; (4) header arguments
  65. "\\([^\n]*\\)\n"
  66. ;; (5) body
  67. "\\([^\000]+?\n\\)[ \t]*#\\+end_src")
  68. "Regexp used to identify code blocks.")
  69. (defvar org-babel-inline-src-block-regexp
  70. (concat
  71. ;; (1) replacement target (2) lang
  72. "[ \f\t\n\r\v]\\(src_\\([^ \f\t\n\r\v]+\\)"
  73. ;; (3,4) (unused, headers)
  74. "\\(\\|\\[\\(.*?\\)\\]\\)"
  75. ;; (5) body
  76. "{\\([^\f\n\r\v]+?\\)}\\)")
  77. "Regexp used to identify inline src-blocks.")
  78. (defun org-babel-get-src-block-info (&optional header-vars-only)
  79. "Get information of the current source block.
  80. Returns a list
  81. (language body header-arguments-alist switches name function-args indent).
  82. Unless HEADER-VARS-ONLY is non-nil, any variable
  83. references provided in 'function call style' (i.e. in a
  84. parenthesised argument list following the src block name) are
  85. added to the header-arguments-alist."
  86. (let ((case-fold-search t) head info args indent)
  87. (if (setq head (org-babel-where-is-src-block-head))
  88. (save-excursion
  89. (goto-char head)
  90. (setq info (org-babel-parse-src-block-match))
  91. (setq indent (car (last info)))
  92. (setq info (butlast info))
  93. (forward-line -1)
  94. (if (looking-at
  95. (concat org-babel-source-name-regexp
  96. "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
  97. (progn
  98. (setq info (append info (list (org-babel-clean-text-properties
  99. (match-string 2)))))
  100. ;; Note that e.g. "name()" and "name( )" result in
  101. ;; ((:var . "")). We maintain that behaviour, and the
  102. ;; resulting non-nil sixth element is relied upon in
  103. ;; org-babel-exp-code to detect a functional-style
  104. ;; block in those cases. However, "name" without any
  105. ;; parentheses would result in the same thing, so we
  106. ;; explicitly avoid that.
  107. (if (setq args (match-string 4))
  108. (setq info
  109. (append info (list
  110. (mapcar
  111. (lambda (ref) (cons :var ref))
  112. (org-babel-ref-split-args args))))))
  113. (unless header-vars-only
  114. (setf (nth 2 info)
  115. (org-babel-merge-params (nth 5 info) (nth 2 info)))))
  116. (setq info (append info (list nil nil))))
  117. (append info (list indent)))
  118. (if (save-excursion ;; inline source block
  119. (re-search-backward "[ \f\t\n\r\v]" nil t)
  120. (looking-at org-babel-inline-src-block-regexp))
  121. (org-babel-parse-inline-src-block-match)
  122. nil))))
  123. ;;;###autoload
  124. (defun org-babel-execute-src-block-maybe ()
  125. "Detect if this is context for a org-babel src-block and if so
  126. then run `org-babel-execute-src-block'."
  127. (interactive)
  128. (let ((info (org-babel-get-src-block-info)))
  129. (if info
  130. (progn (org-babel-execute-src-block current-prefix-arg info) t) nil)))
  131. (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-execute-src-block-maybe)
  132. ;;;###autoload
  133. (defun org-babel-expand-src-block-maybe ()
  134. "Detect if this is context for a org-babel src-block and if so
  135. then run `org-babel-expand-src-block'."
  136. (interactive)
  137. (let ((info (org-babel-get-src-block-info)))
  138. (if info
  139. (progn (org-babel-expand-src-block current-prefix-arg info) t)
  140. nil)))
  141. ;;;###autoload
  142. (defun org-babel-load-in-session-maybe ()
  143. "Detect if this is context for a org-babel src-block and if so
  144. then run `org-babel-load-in-session'."
  145. (interactive)
  146. (let ((info (org-babel-get-src-block-info)))
  147. (if info
  148. (progn (org-babel-load-in-session current-prefix-arg info) t)
  149. nil)))
  150. (add-hook 'org-metaup-hook 'org-babel-load-in-session-maybe)
  151. ;;;###autoload
  152. (defun org-babel-pop-to-session-maybe ()
  153. "Detect if this is context for a org-babel src-block and if so
  154. then run `org-babel-pop-to-session'."
  155. (interactive)
  156. (let ((info (org-babel-get-src-block-info)))
  157. (if info (progn (org-babel-pop-to-session current-prefix-arg info) t) nil)))
  158. (add-hook 'org-metadown-hook 'org-babel-pop-to-session-maybe)
  159. (defconst org-babel-header-arg-names
  160. '(cache cmdline colnames dir exports file noweb results
  161. session tangle var noeval)
  162. "Common header arguments used by org-babel. Note that
  163. individual languages may define their own language specific
  164. header arguments as well.")
  165. (defvar org-babel-default-header-args
  166. '((:session . "none") (:results . "replace") (:exports . "code")
  167. (:cache . "no") (:noweb . "no") (:hlines . "no"))
  168. "Default arguments to use when evaluating a source block.")
  169. (defvar org-babel-default-inline-header-args
  170. '((:session . "none") (:results . "silent") (:exports . "results"))
  171. "Default arguments to use when evaluating an inline source block.")
  172. (defvar org-babel-current-buffer-properties)
  173. (make-variable-buffer-local 'org-babel-current-buffer-properties)
  174. (defvar org-babel-result-regexp
  175. "^[ \t]*#\\+res\\(ults\\|name\\)\\(\\[\\([[:alnum:]]+\\)\\]\\)?\\:"
  176. "Regular expression used to match result lines. If the
  177. results are associated with a hash key then the hash will be
  178. saved in the second match data.")
  179. (defvar org-babel-min-lines-for-block-output 10
  180. "If number of lines of output is equal to or exceeds this
  181. value, the output is placed in a #+begin_example...#+end_example
  182. block. Otherwise the output is marked as literal by inserting
  183. colons at the starts of the lines. This variable only takes
  184. effect if the :results output option is in effect.")
  185. (defvar org-babel-noweb-error-langs nil
  186. "List of language for which errors should be raised when the
  187. source code block satisfying a noweb reference in this language
  188. can not be resolved.")
  189. (defvar org-babel-hash-show 4
  190. "Number of initial characters to show of a hidden results hash.")
  191. (defvar org-babel-after-execute-hook nil
  192. "Hook for functions to be called after `org-babel-execute-src-block'")
  193. (defun org-babel-named-src-block-regexp-for-name (name)
  194. "This generates a regexp used to match a src block named NAME."
  195. (concat org-babel-source-name-regexp (regexp-quote name) "[ \t\n]*"
  196. (substring org-babel-src-block-regexp 1)))
  197. ;;; functions
  198. (defvar call-process-region)
  199. ;;;###autoload
  200. (defun org-babel-execute-src-block (&optional arg info params)
  201. "Execute the current source code block, and insert the results
  202. into the buffer. Source code execution and the collection and
  203. formatting of results can be controlled through a variety of
  204. header arguments.
  205. Optionally supply a value for INFO in the form returned by
  206. `org-babel-get-src-block-info'.
  207. Optionally supply a value for PARAMS which will be merged with
  208. the header arguments specified at the front of the source code
  209. block."
  210. (interactive)
  211. (let* ((info (or info (org-babel-get-src-block-info)))
  212. (lang (nth 0 info))
  213. (params (setf (nth 2 info)
  214. (sort (org-babel-merge-params (nth 2 info) params)
  215. (lambda (el1 el2) (string< (symbol-name (car el1))
  216. (symbol-name (car el2)))))))
  217. (new-hash
  218. (if (and (cdr (assoc :cache params))
  219. (string= "yes" (cdr (assoc :cache params))))
  220. (org-babel-sha1-hash info)))
  221. (old-hash (org-babel-result-hash info))
  222. (body (setf (nth 1 info)
  223. (if (and (cdr (assoc :noweb params))
  224. (string= "yes" (cdr (assoc :noweb params))))
  225. (org-babel-expand-noweb-references info)
  226. (nth 1 info))))
  227. (result-params (split-string (or (cdr (assoc :results params)) "")))
  228. (result-type (cond ((member "output" result-params) 'output)
  229. ((member "value" result-params) 'value)
  230. (t 'value)))
  231. (cmd (intern (concat "org-babel-execute:" lang)))
  232. (dir (cdr (assoc :dir params)))
  233. (default-directory
  234. (or (and dir (file-name-as-directory dir)) default-directory))
  235. (org-babel-call-process-region-original
  236. (if (boundp 'org-babel-call-process-region-original) org-babel-call-process-region-original
  237. (symbol-function 'call-process-region)))
  238. (indent (car (last info)))
  239. result)
  240. (unwind-protect
  241. (flet ((call-process-region (&rest args)
  242. (apply 'org-babel-tramp-handle-call-process-region args)))
  243. (unless (fboundp cmd)
  244. (error "No org-babel-execute function for %s!" lang))
  245. (if (and (not arg) new-hash (equal new-hash old-hash))
  246. (save-excursion ;; return cached result
  247. (goto-char (org-babel-where-is-src-block-result nil info))
  248. (end-of-line 1) (forward-char 1)
  249. (setq result (org-babel-read-result))
  250. (message (replace-regexp-in-string "%" "%%"
  251. (format "%S" result))) result)
  252. (setq result (funcall cmd body params))
  253. (if (eq result-type 'value)
  254. (setq result (if (and (or (member "vector" result-params)
  255. (member "table" result-params))
  256. (not (listp result)))
  257. (list (list result))
  258. result)))
  259. (org-babel-insert-result
  260. result result-params info new-hash indent lang)
  261. (run-hooks 'org-babel-after-execute-hook)
  262. result))
  263. (setq call-process-region 'org-babel-call-process-region-original))))
  264. (defun org-babel-expand-body:generic (body params &optional processed-params)
  265. "Expand a block of code with org-babel according to it's header
  266. arguments. This generic implementation of body expansion is
  267. called for languages which have not defined their own specific
  268. org-babel-expand-body:lang function." body)
  269. ;;;###autoload
  270. (defun org-babel-expand-src-block (&optional arg info params)
  271. "Expand the current source code block according to it's header
  272. arguments, and pop open the results in a preview buffer."
  273. (interactive)
  274. (let* ((info (or info (org-babel-get-src-block-info)))
  275. (lang (nth 0 info))
  276. (params (setf (nth 2 info)
  277. (sort (org-babel-merge-params (nth 2 info) params)
  278. (lambda (el1 el2) (string< (symbol-name (car el1))
  279. (symbol-name (car el2)))))))
  280. (body (setf (nth 1 info)
  281. (if (and (cdr (assoc :noweb params))
  282. (string= "yes" (cdr (assoc :noweb params))))
  283. (org-babel-expand-noweb-references info) (nth 1 info))))
  284. (cmd (intern (concat "org-babel-expand-body:" lang)))
  285. (expanded (funcall (if (fboundp cmd) cmd 'org-babel-expand-body:generic)
  286. body params)))
  287. (org-edit-src-code
  288. nil expanded (concat "*Org-Babel Preview " (buffer-name) "[ " lang " ]*"))))
  289. ;;;###autoload
  290. (defun org-babel-load-in-session (&optional arg info)
  291. "Load the body of the current source-code block. Evaluate the
  292. header arguments for the source block before entering the
  293. session. After loading the body this pops open the session."
  294. (interactive)
  295. (let* ((info (or info (org-babel-get-src-block-info)))
  296. (lang (nth 0 info))
  297. (body (nth 1 info))
  298. (params (nth 2 info))
  299. (session (cdr (assoc :session params)))
  300. (cmd (intern (concat "org-babel-load-session:" lang))))
  301. (unless (fboundp cmd)
  302. (error "No org-babel-load-session function for %s!" lang))
  303. (pop-to-buffer (funcall cmd session body params))
  304. (end-of-line 1)))
  305. ;;;###autoload
  306. (defun org-babel-switch-to-session (&optional arg info)
  307. "Switch to the session of the current source-code block.
  308. If called with a prefix argument then evaluate the header arguments
  309. for the source block before entering the session. Copy the body
  310. of the source block to the kill ring."
  311. (interactive)
  312. (let* ((info (or info (org-babel-get-src-block-info)))
  313. (lang (nth 0 info))
  314. (body (nth 1 info))
  315. (params (nth 2 info))
  316. (session (cdr (assoc :session params)))
  317. (dir (cdr (assoc :dir params)))
  318. (default-directory
  319. (or (and dir (file-name-as-directory dir)) default-directory))
  320. (cmd (intern (format "org-babel-%s-initiate-session" lang)))
  321. (cmd2 (intern (concat "org-babel-prep-session:" lang))))
  322. (unless (fboundp cmd)
  323. (error "No org-babel-initiate-session function for %s!" lang))
  324. ;; copy body to the kill ring
  325. (with-temp-buffer (insert (org-babel-trim body))
  326. (copy-region-as-kill (point-min) (point-max)))
  327. ;; if called with a prefix argument, then process header arguments
  328. (unless (fboundp cmd2)
  329. (error "No org-babel-prep-session function for %s!" lang))
  330. (when arg (funcall cmd2 session params))
  331. ;; just to the session using pop-to-buffer
  332. (pop-to-buffer (funcall cmd session params))
  333. (end-of-line 1)))
  334. (defalias 'org-babel-pop-to-session 'org-babel-switch-to-session)
  335. (defvar org-bracket-link-regexp)
  336. ;;;###autoload
  337. (defun org-babel-open-src-block-result (&optional re-run)
  338. "If `point' is on a src block then open the results of the
  339. source code block, otherwise return nil. With optional prefix
  340. argument RE-RUN the source-code block is evaluated even if
  341. results already exist."
  342. (interactive "P")
  343. (when (org-babel-get-src-block-info)
  344. (save-excursion
  345. ;; go to the results, if there aren't any then run the block
  346. (goto-char (or (and (not re-run) (org-babel-where-is-src-block-result))
  347. (progn (org-babel-execute-src-block)
  348. (org-babel-where-is-src-block-result))))
  349. (end-of-line 1)
  350. (while (looking-at "[\n\r\t\f ]") (forward-char 1))
  351. ;; open the results
  352. (if (looking-at org-bracket-link-regexp)
  353. ;; file results
  354. (org-open-at-point)
  355. (let ((results (org-babel-read-result)))
  356. (flet ((echo-res (result)
  357. (if (stringp result) result (format "%S" result))))
  358. (pop-to-buffer (get-buffer-create "org-babel-results"))
  359. (delete-region (point-min) (point-max))
  360. (if (listp results)
  361. ;; table result
  362. (insert (orgtbl-to-generic results '(:sep "\t" :fmt echo-res)))
  363. ;; scalar result
  364. (insert (echo-res results))))))
  365. t)))
  366. ;;;###autoload
  367. (defun org-babel-execute-buffer (&optional arg)
  368. "Call `org-babel-execute-src-block' on every source block in
  369. the current buffer."
  370. (interactive "P")
  371. (save-excursion
  372. (org-save-outline-visibility t
  373. (goto-char (point-min))
  374. (show-all)
  375. (while (re-search-forward org-babel-src-block-regexp nil t)
  376. (let ((pos-end (match-end 0)))
  377. (goto-char (match-beginning 0))
  378. (org-babel-execute-src-block arg)
  379. (goto-char pos-end))))))
  380. ;;;###autoload
  381. (defun org-babel-execute-subtree (&optional arg)
  382. "Call `org-babel-execute-src-block' on every source block in
  383. the current subtree."
  384. (interactive "P")
  385. (save-restriction
  386. (save-excursion
  387. (org-narrow-to-subtree)
  388. (org-babel-execute-buffer)
  389. (widen))))
  390. ;;;###autoload
  391. (defun org-babel-sha1-hash (&optional info)
  392. "Generate an sha1 hash based on the value of info."
  393. (interactive)
  394. (let* ((info (or info (org-babel-get-src-block-info)))
  395. (hash (sha1 (format "%s-%s" (mapconcat (lambda (arg) (format "%S" arg))
  396. (nth 2 info) ":")
  397. (nth 1 info)))))
  398. (when (interactive-p) (message hash))
  399. hash))
  400. (defun org-babel-result-hash (&optional info)
  401. "Return the in-buffer hash associated with the results
  402. specified in INFO."
  403. (org-babel-where-is-src-block-result nil info)
  404. (org-babel-clean-text-properties (match-string 3)))
  405. (defun org-babel-hide-hash ()
  406. "Hide the hash in the current results line. Only the initial
  407. `org-babel-hash-show' characters of the hash will remain
  408. visible."
  409. (add-to-invisibility-spec '(org-babel-hide-hash . t))
  410. (save-excursion
  411. (when (and (re-search-forward org-babel-result-regexp nil t)
  412. (match-string 3))
  413. (let* ((start (match-beginning 3))
  414. (hide-start (+ org-babel-hash-show start))
  415. (end (match-end 3))
  416. (hash (match-string 3))
  417. ov1 ov2)
  418. (setq ov1 (make-overlay start hide-start))
  419. (setq ov2 (make-overlay hide-start end))
  420. (overlay-put ov2 'invisible 'org-babel-hide-hash)
  421. (overlay-put ov1 'babel-hash hash)))))
  422. (defun org-babel-hide-all-hashes ()
  423. "Hide the hash in the current buffer. Only the initial
  424. `org-babel-hash-show' characters of each hash will remain
  425. visible. This function should be called as part of the
  426. `org-mode-hook'."
  427. (save-excursion
  428. (while (re-search-forward org-babel-result-regexp nil t)
  429. (goto-char (match-beginning 0))
  430. (org-babel-hide-hash)
  431. (goto-char (match-end 0)))))
  432. (add-hook 'org-mode-hook 'org-babel-hide-all-hashes)
  433. (defun org-babel-hash-at-point (&optional point)
  434. "Return the value of the hash at `point'. The hash is also
  435. added as the last element of the kill ring. This can be called
  436. with C-c C-c."
  437. (interactive)
  438. (let ((hash (car (delq nil (mapcar
  439. (lambda (ol) (overlay-get ol 'babel-hash))
  440. (overlays-at (or point (point))))))))
  441. (when hash (kill-new hash) (message hash))))
  442. (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-hash-at-point)
  443. (defun org-babel-result-hide-spec ()
  444. "Add `org-babel-hide-result' as an invisibility spec for hiding
  445. portions of results lines."
  446. (add-to-invisibility-spec '(org-babel-hide-result . t)))
  447. (add-hook 'org-mode-hook 'org-babel-result-hide-spec)
  448. (defvar org-babel-hide-result-overlays nil
  449. "Overlays hiding results.")
  450. (defun org-babel-result-hide-all ()
  451. "Fold all results in the current buffer."
  452. (interactive)
  453. (org-babel-show-result-all)
  454. (save-excursion
  455. (while (re-search-forward org-babel-result-regexp nil t)
  456. (save-excursion (goto-char (match-beginning 0))
  457. (org-babel-hide-result-toggle-maybe)))))
  458. (defun org-babel-show-result-all ()
  459. "Unfold all results in the current buffer."
  460. (mapc 'delete-overlay org-babel-hide-result-overlays)
  461. (setq org-babel-hide-result-overlays nil))
  462. ;;;###autoload
  463. (defun org-babel-hide-result-toggle-maybe ()
  464. "Toggle visibility of result at point."
  465. (interactive)
  466. (let ((case-fold-search t))
  467. (if (save-excursion
  468. (beginning-of-line 1)
  469. (looking-at org-babel-result-regexp))
  470. (progn (org-babel-hide-result-toggle)
  471. t) ;; to signal that we took action
  472. nil))) ;; to signal that we did not
  473. (defun org-babel-hide-result-toggle (&optional force)
  474. "Toggle the visibility of the current result."
  475. (interactive)
  476. (save-excursion
  477. (beginning-of-line)
  478. (if (re-search-forward org-babel-result-regexp nil t)
  479. (let ((start (progn (beginning-of-line 2) (- (point) 1)))
  480. (end (progn (goto-char (- (org-babel-result-end) 1)) (point)))
  481. ov)
  482. (if (memq t (mapcar (lambda (overlay)
  483. (eq (overlay-get overlay 'invisible)
  484. 'org-babel-hide-result))
  485. (overlays-at start)))
  486. (if (or (not force) (eq force 'off))
  487. (mapc (lambda (ov)
  488. (when (member ov org-babel-hide-result-overlays)
  489. (setq org-babel-hide-result-overlays
  490. (delq ov org-babel-hide-result-overlays)))
  491. (when (eq (overlay-get ov 'invisible)
  492. 'org-babel-hide-result)
  493. (delete-overlay ov)))
  494. (overlays-at start)))
  495. (setq ov (make-overlay start end))
  496. (overlay-put ov 'invisible 'org-babel-hide-result)
  497. ;; make the block accessible to isearch
  498. (overlay-put
  499. ov 'isearch-open-invisible
  500. (lambda (ov)
  501. (when (member ov org-babel-hide-result-overlays)
  502. (setq org-babel-hide-result-overlays
  503. (delq ov org-babel-hide-result-overlays)))
  504. (when (eq (overlay-get ov 'invisible)
  505. 'org-babel-hide-result)
  506. (delete-overlay ov))))
  507. (push ov org-babel-hide-result-overlays)))
  508. (error "Not looking at a result line"))))
  509. ;; org-tab-after-check-for-cycling-hook
  510. (add-hook 'org-tab-first-hook 'org-babel-hide-result-toggle-maybe)
  511. ;; Remove overlays when changing major mode
  512. (add-hook 'org-mode-hook
  513. (lambda () (org-add-hook 'change-major-mode-hook
  514. 'org-babel-show-result-all 'append 'local)))
  515. (defmacro org-babel-map-source-blocks (file &rest body)
  516. "Evaluate BODY forms on each source-block in FILE."
  517. (declare (indent 1))
  518. `(let ((visited-p (get-file-buffer (expand-file-name ,file)))
  519. to-be-removed)
  520. (save-window-excursion
  521. (find-file ,file)
  522. (setq to-be-removed (current-buffer))
  523. (goto-char (point-min))
  524. (while (re-search-forward org-babel-src-block-regexp nil t)
  525. (goto-char (match-beginning 0))
  526. (save-match-data ,@body)
  527. (goto-char (match-end 0))))
  528. (unless visited-p
  529. (kill-buffer to-be-removed))))
  530. (defvar org-file-properties)
  531. (defun org-babel-params-from-properties (&optional lang)
  532. "Return an association list of any source block params which
  533. may be specified in the properties of the current outline entry."
  534. (save-match-data
  535. (let (val sym)
  536. (delq nil
  537. (mapcar
  538. (lambda (header-arg)
  539. (and (setq val
  540. (or (condition-case nil
  541. (org-entry-get (point) header-arg t)
  542. (error nil))
  543. (cdr (assoc header-arg org-file-properties))))
  544. (cons (intern (concat ":" header-arg)) val)))
  545. (mapcar
  546. 'symbol-name
  547. (append
  548. org-babel-header-arg-names
  549. (progn
  550. (setq sym (intern (concat "org-babel-header-arg-names:" lang)))
  551. (and (boundp sym) (eval sym))))))))))
  552. (defun org-babel-params-from-buffer ()
  553. "Return an association list of any source block params which
  554. may be specified at the top of the current buffer."
  555. (or org-babel-current-buffer-properties
  556. (setq org-babel-current-buffer-properties
  557. (save-match-data
  558. (save-excursion
  559. (save-restriction
  560. (widen)
  561. (goto-char (point-min))
  562. (when (re-search-forward
  563. (org-make-options-regexp (list "BABEL")) nil t)
  564. (org-babel-parse-header-arguments
  565. (org-match-string-no-properties 2)))))))))
  566. (defvar org-src-preserve-indentation)
  567. (defun org-babel-parse-src-block-match ()
  568. "Parse the match data resulting from a match of the
  569. `org-babel-src-block-regexp'."
  570. (let* ((block-indentation (length (match-string 1)))
  571. (lang (org-babel-clean-text-properties (match-string 2)))
  572. (lang-headers (intern (concat "org-babel-default-header-args:" lang)))
  573. (switches (match-string 3))
  574. (body (org-babel-clean-text-properties (match-string 5)))
  575. (preserve-indentation (or org-src-preserve-indentation
  576. (string-match "-i\\>" switches))))
  577. (list lang
  578. ;; get block body less properties, protective commas, and indentation
  579. (with-temp-buffer
  580. (save-match-data
  581. (insert (org-babel-strip-protective-commas body))
  582. (unless preserve-indentation (org-do-remove-indentation))
  583. (buffer-string)))
  584. (org-babel-merge-params
  585. org-babel-default-header-args
  586. (org-babel-params-from-buffer)
  587. (org-babel-params-from-properties lang)
  588. (if (boundp lang-headers) (eval lang-headers) nil)
  589. (org-babel-parse-header-arguments
  590. (org-babel-clean-text-properties (or (match-string 4) ""))))
  591. switches
  592. block-indentation)))
  593. (defun org-babel-parse-inline-src-block-match ()
  594. "Parse the match data resulting from a match of the
  595. `org-babel-inline-src-block-regexp'."
  596. (let* ((lang (org-babel-clean-text-properties (match-string 2)))
  597. (lang-headers (intern (concat "org-babel-default-header-args:" lang))))
  598. (list lang
  599. (org-babel-strip-protective-commas
  600. (org-babel-clean-text-properties (match-string 5)))
  601. (org-babel-merge-params
  602. org-babel-default-inline-header-args
  603. (org-babel-params-from-buffer)
  604. (org-babel-params-from-properties lang)
  605. (if (boundp lang-headers) (eval lang-headers) nil)
  606. (org-babel-parse-header-arguments
  607. (org-babel-clean-text-properties (or (match-string 4) "")))))))
  608. (defun org-babel-parse-header-arguments (arg-string)
  609. "Parse a string of header arguments returning an alist."
  610. (if (> (length arg-string) 0)
  611. (delq nil
  612. (mapcar
  613. (lambda (arg)
  614. (if (string-match
  615. "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
  616. arg)
  617. (cons (intern (concat ":" (match-string 1 arg)))
  618. (let ((raw (org-babel-chomp (match-string 2 arg))))
  619. (if (org-babel-number-p raw)
  620. raw (org-babel-read raw))))
  621. (cons (intern (concat ":" arg)) nil)))
  622. (split-string (concat " " arg-string) "[ \f\t\n\r\v]+:" t)))))
  623. (defun org-babel-process-params (params)
  624. "Parse params and resolve references.
  625. Return a list (session vars result-params result-type colnames rownames)."
  626. (let* ((session (cdr (assoc :session params)))
  627. (vars-and-names (org-babel-disassemble-tables
  628. (org-babel-ref-variables params)
  629. (cdr (assoc :hlines params))
  630. (cdr (assoc :colnames params))
  631. (cdr (assoc :rownames params))))
  632. (vars (car vars-and-names))
  633. (colnames (cadr vars-and-names))
  634. (rownames (caddr vars-and-names))
  635. (result-params (split-string (or (cdr (assoc :results params)) "")))
  636. (result-type (cond ((member "output" result-params) 'output)
  637. ((member "value" result-params) 'value)
  638. (t 'value))))
  639. (list session vars result-params result-type colnames rownames)))
  640. ;; row and column names
  641. (defun org-babel-del-hlines (table)
  642. "Remove all 'hlines from TABLE."
  643. (remove 'hline table))
  644. (defun org-babel-get-colnames (table)
  645. "Return a cons cell, the `car' of which contains the TABLE less
  646. colnames, and the `cdr' of which contains a list of the column
  647. names."
  648. (if (equal 'hline (nth 1 table))
  649. (cons (cddr table) (car table))
  650. (cons (cdr table) (car table))))
  651. (defun org-babel-get-rownames (table)
  652. "Return a cons cell, the `car' of which contains the TABLE less
  653. colnames, and the `cdr' of which contains a list of the column
  654. names. Note: this function removes any hlines in TABLE."
  655. (flet ((trans (table) (apply #'mapcar* #'list table)))
  656. (let* ((width (apply 'max (mapcar (lambda (el) (if (listp el) (length el) 0)) table)))
  657. (table (trans (mapcar (lambda (row)
  658. (if (not (equal row 'hline))
  659. row
  660. (setq row '())
  661. (dotimes (n width) (setq row (cons 'hline row)))
  662. row))
  663. table))))
  664. (cons (mapcar (lambda (row) (if (equal (car row) 'hline) 'hline row))
  665. (trans (cdr table)))
  666. (remove 'hline (car table))))))
  667. (defun org-babel-put-colnames (table colnames)
  668. "Add COLNAMES to TABLE if they exist."
  669. (if colnames (apply 'list colnames 'hline table) table))
  670. (defun org-babel-put-rownames (table rownames)
  671. "Add ROWNAMES to TABLE if they exist."
  672. (if rownames
  673. (mapcar (lambda (row)
  674. (if (listp row)
  675. (cons (or (pop rownames) "") row)
  676. row)) table)
  677. table))
  678. (defun org-babel-pick-name (names selector)
  679. "Select one out of an alist of row or column names."
  680. (when names
  681. (if (and selector (symbolp selector) (not (equal t selector)))
  682. (cdr (assoc selector names))
  683. (if (integerp selector)
  684. (nth (- selector 1) names)
  685. (cdr (car (last names)))))))
  686. (defun org-babel-disassemble-tables (vars hlines colnames rownames)
  687. "Process the variables in VARS according to the HLINES,
  688. ROWNAMES and COLNAMES header arguments. Return a list consisting
  689. of the vars, cnames and rnames."
  690. (let (cnames rnames)
  691. (list
  692. (mapcar
  693. (lambda (var)
  694. (when (listp (cdr var))
  695. (when (and (not (equal colnames "no"))
  696. (or colnames (and (equal (nth 1 (cdr var)) 'hline)
  697. (not (member 'hline (cddr (cdr var)))))))
  698. (let ((both (org-babel-get-colnames (cdr var))))
  699. (setq cnames (cons (cons (car var) (cdr both))
  700. cnames))
  701. (setq var (cons (car var) (car both)))))
  702. (when (and rownames (not (equal rownames "no")))
  703. (let ((both (org-babel-get-rownames (cdr var))))
  704. (setq rnames (cons (cons (car var) (cdr both))
  705. rnames))
  706. (setq var (cons (car var) (car both)))))
  707. (when (and hlines (not (equal hlines "yes")))
  708. (setq var (cons (car var) (org-babel-del-hlines (cdr var))))))
  709. var)
  710. vars)
  711. cnames rnames)))
  712. (defun org-babel-reassemble-table (table colnames rownames)
  713. "Given a TABLE and set of COLNAMES and ROWNAMES add the names
  714. to the table for reinsertion to org-mode."
  715. (if (listp table)
  716. ((lambda (table)
  717. (if (and colnames (listp (car table)) (= (length (car table))
  718. (length colnames)))
  719. (org-babel-put-colnames table colnames) table))
  720. (if (and rownames (= (length table) (length rownames)))
  721. (org-babel-put-rownames table rownames) table))
  722. table))
  723. (defun org-babel-where-is-src-block-head ()
  724. "Return the point at the beginning of the current source
  725. block. Specifically at the beginning of the #+BEGIN_SRC line.
  726. If the point is not on a source block then return nil."
  727. (let ((initial (point)) top bottom)
  728. (or
  729. (save-excursion ;; on a source name line
  730. (beginning-of-line 1)
  731. (and (looking-at org-babel-source-name-regexp) (forward-line 1)
  732. (looking-at org-babel-src-block-regexp)
  733. (point)))
  734. (save-excursion ;; on a #+begin_src line
  735. (beginning-of-line 1)
  736. (and (looking-at org-babel-src-block-regexp)
  737. (point)))
  738. (save-excursion ;; inside a src block
  739. (and
  740. (re-search-backward "^[ \t]*#\\+begin_src" nil t) (setq top (point))
  741. (re-search-forward "^[ \t]*#\\+end_src" nil t) (setq bottom (point))
  742. (< top initial) (< initial bottom)
  743. (progn (goto-char top) (beginning-of-line 1)
  744. (looking-at org-babel-src-block-regexp))
  745. (point))))))
  746. ;;;###autoload
  747. (defun org-babel-goto-named-source-block (&optional name)
  748. "Go to a named source-code block."
  749. (interactive "ssource-block name: ")
  750. (let ((point (org-babel-find-named-block name)))
  751. (if point
  752. ;; taken from `org-open-at-point'
  753. (progn (goto-char point) (org-show-context))
  754. (message "source-code block '%s' not found in this buffer" name))))
  755. (defun org-babel-find-named-block (name)
  756. "Find a named source-code block.
  757. Return the location of the source block identified by source
  758. NAME, or nil if no such block exists. Set match data according to
  759. org-babel-named-src-block-regexp."
  760. (save-excursion
  761. (let ((case-fold-search t)
  762. (regexp (org-babel-named-src-block-regexp-for-name name)) msg)
  763. (goto-char (point-min))
  764. (when (or (re-search-forward regexp nil t)
  765. (re-search-backward regexp nil t))
  766. (match-beginning 0)))))
  767. (defun org-babel-find-named-result (name)
  768. "Return the location of the result named NAME in the current
  769. buffer or nil if no such result exists."
  770. (save-excursion
  771. (goto-char (point-min))
  772. (when (re-search-forward
  773. (concat org-babel-result-regexp
  774. "[ \t]" (regexp-quote name) "[ \t\n\f\v\r]") nil t)
  775. (beginning-of-line 0) (point))))
  776. (defvar org-babel-lob-one-liner-regexp)
  777. (defun org-babel-where-is-src-block-result (&optional insert info hash indent)
  778. "Return the point at the beginning of the result of the current
  779. source block. Specifically at the beginning of the results line.
  780. If no result exists for this block then create a results line
  781. following the source block."
  782. (save-excursion
  783. (let* ((on-lob-line (progn (beginning-of-line 1)
  784. (looking-at org-babel-lob-one-liner-regexp)))
  785. (name (if on-lob-line
  786. (nth 0 (org-babel-lob-get-info))
  787. (nth 4 (or info (org-babel-get-src-block-info)))))
  788. (head (unless on-lob-line (org-babel-where-is-src-block-head))) end)
  789. (when head (goto-char head))
  790. (or (and name (org-babel-find-named-result name))
  791. (and (or on-lob-line (re-search-forward "^[ \t]*#\\+end_src" nil t))
  792. (progn (end-of-line 1)
  793. (if (eobp) (insert "\n") (forward-char 1))
  794. (setq end (point))
  795. (or (and (not name)
  796. (progn ;; unnamed results line already exists
  797. (re-search-forward "[^ \f\t\n\r\v]" nil t)
  798. (beginning-of-line 1)
  799. (looking-at
  800. (concat org-babel-result-regexp "\n"))))
  801. ;; or (with optional insert) back up and
  802. ;; make one ourselves
  803. (when insert
  804. (goto-char end)
  805. (if (looking-at "[\n\r]")
  806. (forward-char 1) (insert "\n"))
  807. (insert (concat
  808. (if indent
  809. (mapconcat
  810. (lambda (el) " ")
  811. (number-sequence 1 indent) "")
  812. "")
  813. "#+results"
  814. (when hash (concat "["hash"]"))
  815. ":"
  816. (when name (concat " " name)) "\n\n"))
  817. (backward-char)
  818. (beginning-of-line 0)
  819. (if hash (org-babel-hide-hash)) t)))
  820. (point))))))
  821. (defvar org-block-regexp)
  822. (defun org-babel-read-result ()
  823. "Read the result at `point' into emacs-lisp."
  824. (let ((case-fold-search t) result-string)
  825. (cond
  826. ((org-at-table-p) (org-babel-read-table))
  827. ((looking-at org-bracket-link-regexp) (org-babel-read-link))
  828. ((looking-at org-block-regexp) (org-babel-trim (match-string 4)))
  829. ((looking-at "^[ \t]*: ")
  830. (setq result-string
  831. (org-babel-trim
  832. (mapconcat (lambda (line)
  833. (if (and (> (length line) 1)
  834. (string-match "^[ \t]*: \\(.+\\)" line))
  835. (match-string 1 line)
  836. line))
  837. (split-string
  838. (buffer-substring
  839. (point) (org-babel-result-end)) "[\r\n]+")
  840. "\n")))
  841. (or (org-babel-number-p result-string) result-string))
  842. ((looking-at org-babel-result-regexp)
  843. (save-excursion (forward-line 1) (org-babel-read-result))))))
  844. (defun org-babel-read-table ()
  845. "Read the table at `point' into emacs-lisp."
  846. (mapcar (lambda (row)
  847. (if (and (symbolp row) (equal row 'hline)) row
  848. (mapcar #'org-babel-read row)))
  849. (org-table-to-lisp)))
  850. (defvar org-link-types-re)
  851. (defun org-babel-read-link ()
  852. "Read the link at `point' into emacs-lisp. If the path of the
  853. link is a file path it is expanded using `expand-file-name'."
  854. (let* ((case-fold-search t)
  855. (raw (and (looking-at org-bracket-link-regexp)
  856. (org-babel-clean-text-properties (match-string 1))))
  857. (type (and (string-match org-link-types-re raw)
  858. (match-string 1 raw))))
  859. (cond
  860. ((not type) (expand-file-name raw))
  861. ((string= type "file")
  862. (and (string-match "file\\(.*\\):\\(.+\\)" raw)
  863. (expand-file-name (match-string 2 raw))))
  864. (t raw))))
  865. (defun org-babel-insert-result
  866. (result &optional result-params info hash indent lang)
  867. "Insert RESULT into the current buffer after the end of the
  868. current source block. With optional argument RESULT-PARAMS
  869. controls insertion of results in the org-mode file.
  870. RESULT-PARAMS can take the following values...
  871. replace - (default option) insert results after the source block
  872. replacing any previously inserted results
  873. silent -- no results are inserted
  874. file ---- the results are interpreted as a file path, and are
  875. inserted into the buffer using the Org-mode file syntax
  876. raw ----- results are added directly to the org-mode file. This
  877. is a good option if you code block will output org-mode
  878. formatted text.
  879. org ----- this is the same as the 'raw' option
  880. html ---- results are added inside of a #+BEGIN_HTML block. This
  881. is a good option if you code block will output html
  882. formatted text.
  883. latex --- results are added inside of a #+BEGIN_LATEX block.
  884. This is a good option if you code block will output
  885. latex formatted text.
  886. code ---- the results are extracted in the syntax of the source
  887. code of the language being evaluated and are added
  888. inside of a #+BEGIN_SRC block with the source-code
  889. language set appropriately. Note this relies on the
  890. optional LANG argument."
  891. (if (stringp result)
  892. (progn
  893. (setq result (org-babel-clean-text-properties result))
  894. (when (member "file" result-params)
  895. (setq result (org-babel-result-to-file result))))
  896. (unless (listp result) (setq result (format "%S" result))))
  897. (if (= (length result) 0)
  898. (if (member "value" result-params)
  899. (message "No result returned by source block")
  900. (message "Source block produced no output"))
  901. (if (and result-params (member "silent" result-params))
  902. (progn
  903. (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
  904. result)
  905. (when (and (stringp result) ;; ensure results end in a newline
  906. (not (or (string-equal (substring result -1) "\n")
  907. (string-equal (substring result -1) "\r"))))
  908. (setq result (concat result "\n")))
  909. (save-excursion
  910. (let ((existing-result (org-babel-where-is-src-block-result
  911. t info hash indent))
  912. (results-switches
  913. (cdr (assoc :results_switches (nth 2 info))))
  914. beg end)
  915. (when existing-result
  916. (goto-char existing-result)
  917. (save-excursion
  918. (re-search-forward "#" nil t)
  919. (setq indent (- (current-column) 1)))
  920. (forward-line 1)
  921. (setq beg (point))
  922. (cond
  923. ((member "replace" result-params)
  924. (delete-region (point) (org-babel-result-end)))
  925. ((member "append" result-params)
  926. (goto-char (org-babel-result-end)) (setq beg (point)))
  927. ((member "prepend" result-params) ;; already there
  928. )))
  929. (setq results-switches
  930. (if results-switches (concat " " results-switches) ""))
  931. (cond
  932. ;; assume the result is a table if it's not a string
  933. ((not (stringp result))
  934. (insert (concat (orgtbl-to-orgtbl
  935. (if (or (eq 'hline (car result))
  936. (and (listp (car result))
  937. (listp (cdr (car result)))))
  938. result (list result))
  939. '(:fmt (lambda (cell) (format "%s" cell)))) "\n"))
  940. (goto-char beg) (org-table-align))
  941. ((member "file" result-params)
  942. (insert result))
  943. ((member "html" result-params)
  944. (insert (format "#+BEGIN_HTML%s\n%s#+END_HTML\n"
  945. results-switches result)))
  946. ((member "latex" result-params)
  947. (insert (format "#+BEGIN_LaTeX%s\n%s#+END_LaTeX\n"
  948. results-switches result)))
  949. ((member "code" result-params)
  950. (insert (format "#+BEGIN_SRC %s%s\n%s#+END_SRC\n"
  951. (or lang "none") results-switches result)))
  952. ((or (member "raw" result-params) (member "org" result-params))
  953. (save-excursion (insert result)) (if (org-at-table-p) (org-cycle)))
  954. (t
  955. (org-babel-examplize-region
  956. (point) (progn (insert result) (point)) results-switches)))
  957. ;; possibly indent the results to match the #+results line
  958. (setq end (if (listp result) (org-table-end) (point)))
  959. (when (and indent (> indent 0)
  960. ;; in this case `table-align' does the work for us
  961. (not (and (listp result)
  962. (member "append" result-params))))
  963. (indent-rigidly beg end indent))))
  964. (message "finished"))))
  965. (defun org-babel-remove-result (&optional info)
  966. "Remove the result of the current source block."
  967. (interactive)
  968. (let ((location (org-babel-where-is-src-block-result nil info)) start)
  969. (when location
  970. (save-excursion
  971. (goto-char location) (setq start (point)) (forward-line 1)
  972. (delete-region start (org-babel-result-end))))))
  973. (defun org-babel-result-end ()
  974. "Return the point at the end of the current set of results"
  975. (save-excursion
  976. (if (org-at-table-p)
  977. (progn (goto-char (org-table-end)) (point))
  978. (let ((case-fold-search t))
  979. (cond
  980. ((looking-at "[ \t]*#\\+begin_latex")
  981. (re-search-forward "[ \t]*#\\+end_latex" nil t)
  982. (forward-line 1))
  983. ((looking-at "[ \t]*#\\+begin_html")
  984. (re-search-forward "[ \t]*#\\+end_html" nil t)
  985. (forward-line 1))
  986. ((looking-at "[ \t]*#\\+begin_example")
  987. (re-search-forward "[ \t]*#\\+end_example" nil t)
  988. (forward-line 1))
  989. ((looking-at "[ \t]*#\\+begin_src")
  990. (re-search-forward "[ \t]*#\\+end_src" nil t)
  991. (forward-line 1))
  992. (t (progn (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
  993. (forward-line 1))))))
  994. (point))))
  995. (defun org-babel-result-to-file (result)
  996. "Convert RESULT into an `org-mode' link. If the
  997. `default-directory' is different from the containing file's
  998. directory then expand relative links."
  999. (format
  1000. "[[file:%s]]"
  1001. (if (and default-directory
  1002. buffer-file-name
  1003. (not (string= (expand-file-name default-directory)
  1004. (expand-file-name
  1005. (file-name-directory buffer-file-name)))))
  1006. (expand-file-name result default-directory)
  1007. result)))
  1008. (defun org-babel-examplize-region (beg end &optional results-switches)
  1009. "Comment out region using the ': ' org example quote."
  1010. (interactive "*r")
  1011. (let ((size (count-lines beg end)))
  1012. (save-excursion
  1013. (cond ((= size 0)
  1014. (error (concat "This should be impossible:"
  1015. "a newline was appended to result if missing")))
  1016. ((< size org-babel-min-lines-for-block-output)
  1017. (goto-char beg)
  1018. (dotimes (n size)
  1019. (beginning-of-line 1) (insert ": ") (forward-line 1)))
  1020. (t
  1021. (goto-char beg)
  1022. (insert (if results-switches
  1023. (format "#+begin_example%s\n" results-switches)
  1024. "#+begin_example\n"))
  1025. (forward-char (- end beg))
  1026. (insert "#+end_example\n"))))))
  1027. (defun org-babel-merge-params (&rest plists)
  1028. "Combine all parameter association lists in PLISTS. Later
  1029. elements of PLISTS override the values of previous element. This
  1030. takes into account some special considerations for certain
  1031. parameters when merging lists."
  1032. (let ((results-exclusive-groups
  1033. '(("file" "vector" "table" "scalar" "raw" "org"
  1034. "html" "latex" "code" "pp")
  1035. ("replace" "silent" "append" "prepend")
  1036. ("output" "value")))
  1037. (exports-exclusive-groups
  1038. '(("code" "results" "both" "none")))
  1039. params results exports tangle noweb cache vars var ref shebang comments)
  1040. (flet ((e-merge (exclusive-groups &rest result-params)
  1041. ;; maintain exclusivity of mutually exclusive parameters
  1042. (let (output)
  1043. (mapc (lambda (new-params)
  1044. (mapc (lambda (new-param)
  1045. (mapc (lambda (exclusive-group)
  1046. (when (member new-param exclusive-group)
  1047. (mapcar (lambda (excluded-param)
  1048. (setq output
  1049. (delete
  1050. excluded-param
  1051. output)))
  1052. exclusive-group)))
  1053. exclusive-groups)
  1054. (setq output (org-uniquify
  1055. (cons new-param output))))
  1056. new-params))
  1057. result-params)
  1058. output)))
  1059. (mapc (lambda (plist)
  1060. (mapc (lambda (pair)
  1061. (case (car pair)
  1062. (:var
  1063. ;; we want only one specification per variable
  1064. (when (string-match
  1065. (concat "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
  1066. "[ \t]*\\([^\f\n\r\v]+\\)$") (cdr pair))
  1067. ;; TODO: When is this not true?
  1068. (setq var (intern (match-string 1 (cdr pair)))
  1069. ref (match-string 2 (cdr pair))
  1070. vars (cons (cons var ref)
  1071. (assq-delete-all var vars)))))
  1072. (:results
  1073. (setq results
  1074. (e-merge results-exclusive-groups
  1075. results (split-string (cdr pair)))))
  1076. (:file
  1077. (when (cdr pair)
  1078. (setq results (e-merge results-exclusive-groups
  1079. results '("file")))
  1080. (unless (or (member "both" exports)
  1081. (member "none" exports)
  1082. (member "code" exports))
  1083. (setq exports (e-merge exports-exclusive-groups
  1084. exports '("results"))))
  1085. (setq params
  1086. (cons pair
  1087. (assq-delete-all (car pair) params)))))
  1088. (:exports
  1089. (setq exports
  1090. (e-merge exports-exclusive-groups
  1091. exports (split-string (cdr pair)))))
  1092. (:tangle ;; take the latest -- always overwrite
  1093. (setq tangle (or (list (cdr pair)) tangle)))
  1094. (:noweb
  1095. (setq noweb
  1096. (e-merge '(("yes" "no")) noweb
  1097. (split-string (or (cdr pair) "")))))
  1098. (:cache
  1099. (setq cache
  1100. (e-merge '(("yes" "no")) cache
  1101. (split-string (or (cdr pair) "")))))
  1102. (:shebang ;; take the latest -- always overwrite
  1103. (setq shebang (or (list (cdr pair)) shebang)))
  1104. (:comments
  1105. (setq comments
  1106. (e-merge '(("yes" "no")) comments
  1107. (split-string (or (cdr pair) "")))))
  1108. (t ;; replace: this covers e.g. :session
  1109. (setq params
  1110. (cons pair
  1111. (assq-delete-all (car pair) params))))))
  1112. plist))
  1113. plists))
  1114. (setq vars (mapcar (lambda (pair) (format "%s=%s" (car pair) (cdr pair))) vars))
  1115. (while vars (setq params (cons (cons :var (pop vars)) params)))
  1116. (cons (cons :comments (mapconcat 'identity comments " "))
  1117. (cons (cons :shebang (mapconcat 'identity shebang " "))
  1118. (cons (cons :cache (mapconcat 'identity cache " "))
  1119. (cons (cons :noweb (mapconcat 'identity noweb " "))
  1120. (cons (cons :tangle (mapconcat 'identity tangle " "))
  1121. (cons (cons :exports
  1122. (mapconcat 'identity exports " "))
  1123. (cons
  1124. (cons :results
  1125. (mapconcat 'identity results " "))
  1126. params)))))))))
  1127. (defun org-babel-expand-noweb-references (&optional info parent-buffer)
  1128. "This function expands Noweb style references in the body of
  1129. the current source-code block. For example the following
  1130. reference would be replaced with the body of the source-code
  1131. block named 'example-block'.
  1132. <<example-block>>
  1133. Note that any text preceding the <<foo>> construct on a line will
  1134. be interposed between the lines of the replacement text. So for
  1135. example if <<foo>> is placed behind a comment, then the entire
  1136. replacement text will also be commented.
  1137. This function must be called from inside of the buffer containing
  1138. the source-code block which holds BODY.
  1139. In addition the following syntax can be used to insert the
  1140. results of evaluating the source-code block named 'example-block'.
  1141. <<example-block()>>
  1142. Any optional arguments can be passed to example-block by placing
  1143. the arguments inside the parenthesis following the convention
  1144. defined by `org-babel-lob'. For example
  1145. <<example-block(a=9)>>
  1146. would set the value of argument \"a\" equal to \"9\". Note that
  1147. these arguments are not evaluated in the current source-code
  1148. block but are passed literally to the \"example-block\"."
  1149. (let* ((parent-buffer (or parent-buffer (current-buffer)))
  1150. (info (or info (org-babel-get-src-block-info)))
  1151. (lang (nth 0 info))
  1152. (body (nth 1 info))
  1153. (new-body "") index source-name evaluate prefix)
  1154. (flet ((nb-add (text)
  1155. (setq new-body (concat new-body text))))
  1156. (with-temp-buffer
  1157. (insert body) (goto-char (point-min))
  1158. (setq index (point))
  1159. (while (and (re-search-forward "<<\\(.+?\\)>>" nil t))
  1160. (save-match-data (setf source-name (match-string 1)))
  1161. (save-match-data (setq evaluate (string-match "\(.*\)" source-name)))
  1162. (save-match-data
  1163. (setq prefix
  1164. (buffer-substring (match-beginning 0)
  1165. (save-excursion
  1166. (beginning-of-line 1) (point)))))
  1167. ;; add interval to new-body (removing noweb reference)
  1168. (goto-char (match-beginning 0))
  1169. (nb-add (buffer-substring index (point)))
  1170. (goto-char (match-end 0))
  1171. (setq index (point))
  1172. (nb-add (save-current-buffer
  1173. (set-buffer parent-buffer)
  1174. (mapconcat ;; interpose `prefix' between every line
  1175. #'identity
  1176. (split-string
  1177. (if evaluate
  1178. (let ((raw (org-babel-ref-resolve-reference
  1179. source-name nil)))
  1180. (if (stringp raw) raw (format "%S" raw)))
  1181. (save-restriction
  1182. (widen)
  1183. (let ((point (org-babel-find-named-block source-name)))
  1184. (if point
  1185. (save-excursion
  1186. (goto-char point)
  1187. (org-babel-trim
  1188. (org-babel-expand-noweb-references
  1189. (org-babel-get-src-block-info))))
  1190. ;; optionally raise an error if named
  1191. ;; source-block doesn't exist
  1192. (if (member lang org-babel-noweb-error-langs)
  1193. (error
  1194. (concat "<<%s>> could not be resolved "
  1195. "(see `org-babel-noweb-error-langs')")
  1196. source-name)
  1197. "")))))
  1198. "[\n\r]") (concat "\n" prefix)))))
  1199. (nb-add (buffer-substring index (point-max)))))
  1200. new-body))
  1201. (defun org-babel-error-notify (exit-code stderr)
  1202. "Open a buffer containing information from STDERR with a
  1203. message about the value of EXIT-CODE."
  1204. (message (format "Shell command exited with code %d" exit-code))
  1205. (let ((buf (get-buffer-create "*Org-Babel Error Output*")))
  1206. (with-current-buffer buf
  1207. (goto-char (point-max))
  1208. (save-excursion (insert stderr)))
  1209. (display-buffer buf)))
  1210. (defun org-babel-clean-text-properties (text)
  1211. "Strip all properties from text return."
  1212. (when text
  1213. (set-text-properties 0 (length text) nil text) text))
  1214. (defun org-babel-strip-protective-commas (body)
  1215. "Strip protective commas from bodies of source blocks."
  1216. (replace-regexp-in-string "^,#" "#" body))
  1217. (defun org-babel-read (cell)
  1218. "Convert the string value of CELL to a number if appropriate.
  1219. Otherwise if cell looks like lisp (meaning it starts with a
  1220. \"(\" or a \"'\") then read it as lisp, otherwise return it
  1221. unmodified as a string.
  1222. This is taken almost directly from `org-read-prop'."
  1223. (if (and (stringp cell) (not (equal cell "")))
  1224. (or (org-babel-number-p cell)
  1225. (if (or (equal "(" (substring cell 0 1))
  1226. (equal "'" (substring cell 0 1))
  1227. (equal "`" (substring cell 0 1)))
  1228. (eval (read cell))
  1229. (progn (set-text-properties 0 (length cell) nil cell) cell)))
  1230. cell))
  1231. (defun org-babel-number-p (string)
  1232. "Return t if STRING represents a number."
  1233. (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string)
  1234. (= (length (substring string (match-beginning 0)
  1235. (match-end 0)))
  1236. (length string)))
  1237. (string-to-number string)))
  1238. (defun org-babel-import-elisp-from-file (file-name)
  1239. "Read the results located at FILE-NAME into an elisp table. If
  1240. the table is trivial, then return it as a scalar."
  1241. (let (result)
  1242. (save-window-excursion
  1243. (with-temp-buffer
  1244. (condition-case nil
  1245. (progn
  1246. (org-table-import file-name nil)
  1247. (delete-file file-name)
  1248. (setq result (mapcar (lambda (row)
  1249. (mapcar #'org-babel-string-read row))
  1250. (org-table-to-lisp))))
  1251. (error nil)))
  1252. (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
  1253. (if (consp (car result))
  1254. (if (null (cdr (car result)))
  1255. (caar result)
  1256. result)
  1257. (car result))
  1258. result))))
  1259. (defun org-babel-string-read (cell)
  1260. "Strip nested \"s from around strings."
  1261. (org-babel-read (or (and (stringp cell)
  1262. (string-match "\\\"\\(.+\\)\\\"" cell)
  1263. (match-string 1 cell))
  1264. cell)))
  1265. (defun org-babel-reverse-string (string)
  1266. "Return the reverse of STRING."
  1267. (apply 'string (reverse (string-to-list string))))
  1268. (defun org-babel-chomp (string &optional regexp)
  1269. "Remove any trailing space or carriage returns characters from
  1270. STRING. Default regexp used is \"[ \f\t\n\r\v]\" but can be
  1271. overwritten by specifying a regexp as a second argument."
  1272. (let ((regexp (or regexp "[ \f\t\n\r\v]")))
  1273. (while (and (> (length string) 0)
  1274. (string-match regexp (substring string -1)))
  1275. (setq string (substring string 0 -1)))
  1276. string))
  1277. (defun org-babel-trim (string &optional regexp)
  1278. "Like `org-babel-chomp' only it runs on both the front and back
  1279. of the string."
  1280. (org-babel-chomp (org-babel-reverse-string
  1281. (org-babel-chomp (org-babel-reverse-string string) regexp))
  1282. regexp))
  1283. (defvar org-babel-org-babel-call-process-region-original nil)
  1284. (defun org-babel-tramp-handle-call-process-region
  1285. (start end program &optional delete buffer display &rest args)
  1286. "Use tramp to handle call-process-region. Fixes a bug in
  1287. `tramp-handle-call-process-region'."
  1288. (if (and (featurep 'tramp) (file-remote-p default-directory))
  1289. (let ((tmpfile (tramp-compat-make-temp-file "")))
  1290. (write-region start end tmpfile)
  1291. (when delete (delete-region start end))
  1292. (unwind-protect
  1293. ;; (apply 'call-process program tmpfile buffer display args)
  1294. ;; bug in tramp
  1295. (apply 'process-file program tmpfile buffer display args)
  1296. (delete-file tmpfile)))
  1297. ;; org-babel-call-process-region-original is the original emacs definition. It
  1298. ;; is in scope from the let binding in org-babel-execute-src-block
  1299. (apply org-babel-call-process-region-original
  1300. start end program delete buffer display args)))
  1301. (defun org-babel-maybe-remote-file (file)
  1302. "If FILE specifies a remove file, then parse the information on
  1303. the remote connection."
  1304. (if (file-remote-p default-directory)
  1305. (let* ((vec (tramp-dissect-file-name default-directory))
  1306. (user (tramp-file-name-user vec))
  1307. (host (tramp-file-name-host vec)))
  1308. (concat "/" user (when user "@") host ":" file))
  1309. file))
  1310. (defun org-babel-shell-command-on-region (start end command
  1311. &optional output-buffer replace
  1312. error-buffer display-error-buffer)
  1313. "Execute string COMMAND in inferior shell with region as input.
  1314. Fixes bugs in the emacs 23.1.1 version of `shell-command-on-region'
  1315. Normally display output (if any) in temp buffer `*Shell Command Output*';
  1316. Prefix arg means replace the region with it. Return the exit code of
  1317. COMMAND.
  1318. To specify a coding system for converting non-ASCII characters in
  1319. the input and output to the shell command, use
  1320. \\[universal-coding-system-argument] before this command. By
  1321. default, the input (from the current buffer) is encoded in the
  1322. same coding system that will be used to save the file,
  1323. `buffer-file-coding-system'. If the output is going to replace
  1324. the region, then it is decoded from that same coding system.
  1325. The noninteractive arguments are START, END, COMMAND,
  1326. OUTPUT-BUFFER, REPLACE, ERROR-BUFFER, and DISPLAY-ERROR-BUFFER.
  1327. Noninteractive callers can specify coding systems by binding
  1328. `coding-system-for-read' and `coding-system-for-write'.
  1329. If the command generates output, the output may be displayed
  1330. in the echo area or in a buffer.
  1331. If the output is short enough to display in the echo area
  1332. \(determined by the variable `max-mini-window-height' if
  1333. `resize-mini-windows' is non-nil), it is shown there. Otherwise
  1334. it is displayed in the buffer `*Shell Command Output*'. The output
  1335. is available in that buffer in both cases.
  1336. If there is output and an error, a message about the error
  1337. appears at the end of the output.
  1338. If there is no output, or if output is inserted in the current buffer,
  1339. then `*Shell Command Output*' is deleted.
  1340. If the optional fourth argument OUTPUT-BUFFER is non-nil,
  1341. that says to put the output in some other buffer.
  1342. If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
  1343. If OUTPUT-BUFFER is not a buffer and not nil,
  1344. insert output in the current buffer.
  1345. In either case, the output is inserted after point (leaving mark after it).
  1346. If REPLACE, the optional fifth argument, is non-nil, that means insert
  1347. the output in place of text from START to END, putting point and mark
  1348. around it.
  1349. If optional sixth argument ERROR-BUFFER is non-nil, it is a buffer
  1350. or buffer name to which to direct the command's standard error output.
  1351. If it is nil, error output is mingled with regular output.
  1352. If DISPLAY-ERROR-BUFFER is non-nil, display the error buffer if there
  1353. were any errors. (This is always t, interactively.)
  1354. In an interactive call, the variable `shell-command-default-error-buffer'
  1355. specifies the value of ERROR-BUFFER."
  1356. (interactive (let (string)
  1357. (unless (mark)
  1358. (error "The mark is not set now, so there is no region"))
  1359. ;; Do this before calling region-beginning
  1360. ;; and region-end, in case subprocess output
  1361. ;; relocates them while we are in the minibuffer.
  1362. (setq string (read-shell-command "Shell command on region: "))
  1363. ;; call-interactively recognizes region-beginning and
  1364. ;; region-end specially, leaving them in the history.
  1365. (list (region-beginning) (region-end)
  1366. string
  1367. current-prefix-arg
  1368. current-prefix-arg
  1369. shell-command-default-error-buffer
  1370. t)))
  1371. (let ((error-file
  1372. (if error-buffer
  1373. (make-temp-file
  1374. (expand-file-name "scor"
  1375. (or (unless (featurep 'xemacs)
  1376. small-temporary-file-directory)
  1377. temporary-file-directory)))
  1378. nil))
  1379. exit-status)
  1380. (if (or replace
  1381. (and output-buffer
  1382. (not (or (bufferp output-buffer) (stringp output-buffer)))))
  1383. ;; Replace specified region with output from command.
  1384. (let ((swap (and replace (< start end))))
  1385. ;; Don't muck with mark unless REPLACE says we should.
  1386. (goto-char start)
  1387. (and replace (push-mark (point) 'nomsg))
  1388. (setq exit-status
  1389. (call-process-region start end shell-file-name t
  1390. (if error-file
  1391. (list output-buffer error-file)
  1392. t)
  1393. nil shell-command-switch command))
  1394. ;; It is rude to delete a buffer which the command is not using.
  1395. ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
  1396. ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
  1397. ;; (kill-buffer shell-buffer)))
  1398. ;; Don't muck with mark unless REPLACE says we should.
  1399. (and replace swap (exchange-point-and-mark)))
  1400. ;; No prefix argument: put the output in a temp buffer,
  1401. ;; replacing its entire contents.
  1402. (let ((buffer (get-buffer-create
  1403. (or output-buffer "*Shell Command Output*"))))
  1404. (unwind-protect
  1405. (if (eq buffer (current-buffer))
  1406. ;; If the input is the same buffer as the output,
  1407. ;; delete everything but the specified region,
  1408. ;; then replace that region with the output.
  1409. (progn (setq buffer-read-only nil)
  1410. (delete-region (max start end) (point-max))
  1411. (delete-region (point-min) (min start end))
  1412. (setq exit-status
  1413. (call-process-region (point-min) (point-max)
  1414. shell-file-name t
  1415. (if error-file
  1416. (list t error-file)
  1417. t)
  1418. nil shell-command-switch
  1419. command)))
  1420. ;; Clear the output buffer, then run the command with
  1421. ;; output there.
  1422. (let ((directory default-directory))
  1423. (save-current-buffer
  1424. (set-buffer buffer)
  1425. (setq buffer-read-only nil)
  1426. (if (not output-buffer)
  1427. (setq default-directory directory))
  1428. (erase-buffer)))
  1429. (setq exit-status
  1430. (call-process-region start end shell-file-name nil
  1431. (if error-file
  1432. (list buffer error-file)
  1433. buffer)
  1434. nil shell-command-switch command)))
  1435. ;; Report the output.
  1436. (with-current-buffer buffer
  1437. (setq mode-line-process
  1438. (cond ((null exit-status)
  1439. " - Error")
  1440. ((stringp exit-status)
  1441. (format " - Signal [%s]" exit-status))
  1442. ((not (equal 0 exit-status))
  1443. (format " - Exit [%d]" exit-status)))))
  1444. (if (with-current-buffer buffer (> (point-max) (point-min)))
  1445. ;; There's some output, display it
  1446. (display-message-or-buffer buffer)
  1447. ;; No output; error?
  1448. (let ((output
  1449. (if (and error-file
  1450. (< 0 (nth 7 (file-attributes error-file))))
  1451. "some error output"
  1452. "no output")))
  1453. (cond ((null exit-status)
  1454. (message "(Shell command failed with error)"))
  1455. ((equal 0 exit-status)
  1456. (message "(Shell command succeeded with %s)"
  1457. output))
  1458. ((stringp exit-status)
  1459. (message "(Shell command killed by signal %s)"
  1460. exit-status))
  1461. (t
  1462. (message "(Shell command failed with code %d and %s)"
  1463. exit-status output))))
  1464. ;; Don't kill: there might be useful info in the undo-log.
  1465. ;; (kill-buffer buffer)
  1466. ))))
  1467. (when (and error-file (file-exists-p error-file))
  1468. (if (< 0 (nth 7 (file-attributes error-file)))
  1469. (with-current-buffer (get-buffer-create error-buffer)
  1470. (let ((pos-from-end (- (point-max) (point))))
  1471. (or (bobp)
  1472. (insert "\f\n"))
  1473. ;; Do no formatting while reading error file,
  1474. ;; because that can run a shell command, and we
  1475. ;; don't want that to cause an infinite recursion.
  1476. (format-insert-file error-file nil)
  1477. ;; Put point after the inserted errors.
  1478. (goto-char (- (point-max) pos-from-end)))
  1479. (and display-error-buffer
  1480. (display-buffer (current-buffer)))))
  1481. (delete-file error-file))
  1482. exit-status))
  1483. (provide 'ob)
  1484. ;; arch-tag: 01a7ebee-06c5-4ee4-a709-e660d28c0af1
  1485. ;;; ob.el ends here