org-babel.el 64 KB

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