ob.el 66 KB

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