ob.el 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063
  1. ;;; ob.el --- working with code blocks in org-mode
  2. ;; Copyright (C) 2009, 2010 Free Software Foundation, Inc.
  3. ;; Author: Eric Schulte, Dan Davison
  4. ;; Keywords: literate programming, reproducible research
  5. ;; Homepage: http://orgmode.org
  6. ;; Version: 7.4
  7. ;; This file is part of GNU Emacs.
  8. ;; GNU Emacs is free software: you can redistribute it and/or modify
  9. ;; it under the terms of the GNU General Public License as published by
  10. ;; the Free Software Foundation, either version 3 of the License, or
  11. ;; (at your option) any later version.
  12. ;; GNU Emacs is distributed in the hope that it will be useful,
  13. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. ;; GNU General Public License for more details.
  16. ;; You should have received a copy of the GNU General Public License
  17. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  18. ;;; Commentary:
  19. ;; See the online documentation for more information
  20. ;;
  21. ;; http://orgmode.org/worg/org-contrib/babel/
  22. ;;; Code:
  23. (eval-when-compile
  24. (require 'cl))
  25. (require 'ob-eval)
  26. (require 'org-macs)
  27. (defvar org-babel-call-process-region-original)
  28. (declare-function show-all "outline" ())
  29. (declare-function tramp-compat-make-temp-file "tramp-compat"
  30. (filename &optional dir-flag))
  31. (declare-function tramp-dissect-file-name "tramp" (name &optional nodefault))
  32. (declare-function tramp-file-name-user "tramp" (vec))
  33. (declare-function tramp-file-name-host "tramp" (vec))
  34. (declare-function with-parsed-tramp-file-name "tramp" (filename var &rest body))
  35. (declare-function org-icompleting-read "org" (&rest args))
  36. (declare-function org-edit-src-code "org-src"
  37. (&optional context code edit-buffer-name quietp))
  38. (declare-function org-edit-src-exit "org-src" (&optional context))
  39. (declare-function org-open-at-point "org" (&optional in-emacs reference-buffer))
  40. (declare-function org-save-outline-visibility "org" (use-markers &rest body))
  41. (declare-function org-outline-overlay-data "org" (&optional use-markers))
  42. (declare-function org-set-outline-overlay-data "org" (data))
  43. (declare-function org-narrow-to-subtree "org" ())
  44. (declare-function org-entry-get "org"
  45. (pom property &optional inherit literal-nil))
  46. (declare-function org-make-options-regexp "org" (kwds &optional extra))
  47. (declare-function org-do-remove-indentation "org" (&optional n))
  48. (declare-function org-show-context "org" (&optional key))
  49. (declare-function org-at-table-p "org" (&optional table-type))
  50. (declare-function org-cycle "org" (&optional arg))
  51. (declare-function org-uniquify "org" (list))
  52. (declare-function org-current-level "org" ())
  53. (declare-function org-table-import "org-table" (file arg))
  54. (declare-function org-add-hook "org-compat"
  55. (hook function &optional append local))
  56. (declare-function org-table-align "org-table" ())
  57. (declare-function org-table-end "org-table" (&optional table-type))
  58. (declare-function orgtbl-to-generic "org-table" (table params))
  59. (declare-function orgtbl-to-orgtbl "org-table" (table params))
  60. (declare-function org-babel-lob-get-info "ob-lob" nil)
  61. (declare-function org-babel-ref-split-args "ob-ref" (arg-string))
  62. (declare-function org-babel-ref-parse "ob-ref" (assignment))
  63. (declare-function org-babel-ref-resolve "ob-ref" (ref))
  64. (declare-function org-babel-lob-execute-maybe "ob-lob" ())
  65. (declare-function org-number-sequence "org-compat" (from &optional to inc))
  66. (declare-function org-in-item-p "org-list" ())
  67. (declare-function org-list-parse-list "org-list" (&optional delete))
  68. (declare-function org-list-to-generic "org-list" (LIST PARAMS))
  69. (declare-function org-list-bottom-point "org-list" ())
  70. (defgroup org-babel nil
  71. "Code block evaluation and management in `org-mode' documents."
  72. :tag "Babel"
  73. :group 'org)
  74. (defcustom org-confirm-babel-evaluate t
  75. "Confirm before evaluation.
  76. Require confirmation before interactively evaluating code
  77. blocks in Org-mode buffers. The default value of this variable
  78. is t, meaning confirmation is required for any code block
  79. evaluation. This variable can be set to nil to inhibit any
  80. future confirmation requests. This variable can also be set to a
  81. function which takes two arguments the language of the code block
  82. and the body of the code block. Such a function should then
  83. return a non-nil value if the user should be prompted for
  84. execution or nil if no prompt is required.
  85. Warning: Disabling confirmation may result in accidental
  86. evaluation of potentially harmful code. It may be advisable
  87. remove code block execution from C-c C-c as further protection
  88. against accidental code block evaluation. The
  89. `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
  90. remove code block execution from the C-c C-c keybinding."
  91. :group 'org-babel
  92. :type '(choice boolean function))
  93. ;; don't allow this variable to be changed through file settings
  94. (put 'org-confirm-babel-evaluate 'safe-local-variable (lambda (x) (eq x t)))
  95. (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
  96. "Remove code block evaluation from the C-c C-c key binding."
  97. :group 'org-babel
  98. :type 'boolean)
  99. (defvar org-babel-src-name-regexp
  100. "^[ \t]*#\\+\\(srcname\\|source\\|function\\):[ \t]*"
  101. "Regular expression used to match a source name line.")
  102. (defvar org-babel-multi-line-header-regexp
  103. "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
  104. "Regular expression used to match multi-line header arguments.")
  105. (defvar org-babel-src-name-w-name-regexp
  106. (concat org-babel-src-name-regexp
  107. "\\("
  108. org-babel-multi-line-header-regexp
  109. "\\)*"
  110. "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)")
  111. "Regular expression matching source name lines with a name.")
  112. (defvar org-babel-src-block-regexp
  113. (concat
  114. ;; (1) indentation (2) lang
  115. "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
  116. ;; (3) switches
  117. "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
  118. ;; (4) header arguments
  119. "\\([^\n]*\\)\n"
  120. ;; (5) body
  121. "\\([^\000]+?\n\\)[ \t]*#\\+end_src")
  122. "Regexp used to identify code blocks.")
  123. (defvar org-babel-inline-src-block-regexp
  124. (concat
  125. ;; (1) replacement target (2) lang
  126. "[^-[:alnum:]]\\(src_\\([^ \f\t\n\r\v]+\\)"
  127. ;; (3,4) (unused, headers)
  128. "\\(\\|\\[\\(.*?\\)\\]\\)"
  129. ;; (5) body
  130. "{\\([^\f\n\r\v]+?\\)}\\)")
  131. "Regexp used to identify inline src-blocks.")
  132. (defun org-babel-get-header (params key &optional others)
  133. "Select only header argument of type KEY from a list.
  134. Optional argument OTHERS indicates that only the header that do
  135. not match KEY should be returned."
  136. (delq nil
  137. (mapcar
  138. (lambda (p) (when (funcall (if others #'not #'identity) (eq (car p) key)) p))
  139. params)))
  140. (defun org-babel-get-src-block-info (&optional light)
  141. "Get information on the current source block.
  142. Optional argument LIGHT does not resolve remote variable
  143. references; a process which could likely result in the execution
  144. of other code blocks.
  145. Returns a list
  146. (language body header-arguments-alist switches name indent)."
  147. (let ((case-fold-search t) head info name indent)
  148. ;; full code block
  149. (if (setq head (org-babel-where-is-src-block-head))
  150. (save-excursion
  151. (goto-char head)
  152. (setq info (org-babel-parse-src-block-match))
  153. (setq indent (car (last info)))
  154. (setq info (butlast info))
  155. (while (and (forward-line -1)
  156. (looking-at org-babel-multi-line-header-regexp))
  157. (setf (nth 2 info)
  158. (org-babel-merge-params
  159. (nth 2 info)
  160. (org-babel-parse-header-arguments (match-string 1)))))
  161. (when (looking-at org-babel-src-name-w-name-regexp)
  162. (setq name (org-babel-clean-text-properties (match-string 4)))
  163. (when (match-string 6)
  164. (setf (nth 2 info) ;; merge functional-syntax vars and header-args
  165. (org-babel-merge-params
  166. (mapcar (lambda (ref) (cons :var ref))
  167. (org-babel-ref-split-args (match-string 6)))
  168. (nth 2 info))))))
  169. ;; inline source block
  170. (when (save-excursion (re-search-backward "[ \f\t\n\r\v]" nil t)
  171. (looking-at org-babel-inline-src-block-regexp))
  172. (setq info (org-babel-parse-inline-src-block-match))))
  173. ;; resolve variable references and add summary parameters
  174. (when (and info (not light))
  175. (setf (nth 2 info) (org-babel-process-params (nth 2 info))))
  176. (when info (append info (list name indent)))))
  177. (defun org-babel-confirm-evaluate (info)
  178. "Confirm evaluation of the code block INFO.
  179. This behavior can be suppressed by setting the value of
  180. `org-confirm-babel-evaluate' to nil, in which case all future
  181. interactive code block evaluations will proceed without any
  182. confirmation from the user.
  183. Note disabling confirmation may result in accidental evaluation
  184. of potentially harmful code."
  185. (let* ((eval (or (cdr (assoc :eval (nth 2 info)))
  186. (when (assoc :noeval (nth 2 info)) "no")))
  187. (query (cond ((equal eval "query") t)
  188. ((functionp org-confirm-babel-evaluate)
  189. (funcall org-confirm-babel-evaluate
  190. (nth 0 info) (nth 1 info)))
  191. (t org-confirm-babel-evaluate))))
  192. (if (or (equal eval "never") (equal eval "no")
  193. (and query
  194. (not (yes-or-no-p
  195. (format "Evaluate this%scode block%son your system? "
  196. (if info (format " %s " (nth 0 info)) " ")
  197. (if (nth 4 info)
  198. (format " (%s) " (nth 4 info)) " "))))))
  199. (prog1 nil (message "Evaluation %s"
  200. (if (or (equal eval "never") (equal eval "no"))
  201. "Disabled" "Aborted")))
  202. t)))
  203. ;;;###autoload
  204. (defun org-babel-execute-safely-maybe ()
  205. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  206. (org-babel-execute-maybe)))
  207. (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-execute-safely-maybe)
  208. ;;;###autoload
  209. (defun org-babel-execute-maybe ()
  210. (interactive)
  211. (or (org-babel-execute-src-block-maybe)
  212. (org-babel-lob-execute-maybe)))
  213. (defun org-babel-execute-src-block-maybe ()
  214. "Conditionally execute a source block.
  215. Detect if this is context for a Babel src-block and if so
  216. then run `org-babel-execute-src-block'."
  217. (interactive)
  218. (let ((info (org-babel-get-src-block-info)))
  219. (if info
  220. (progn (org-babel-eval-wipe-error-buffer)
  221. (org-babel-execute-src-block current-prefix-arg info) t) nil)))
  222. ;;;###autoload
  223. (defun org-babel-expand-src-block-maybe ()
  224. "Conditionally expand a source block.
  225. Detect if this is context for a org-babel src-block and if so
  226. then run `org-babel-expand-src-block'."
  227. (interactive)
  228. (let ((info (org-babel-get-src-block-info)))
  229. (if info
  230. (progn (org-babel-expand-src-block current-prefix-arg info) t)
  231. nil)))
  232. ;;;###autoload
  233. (defun org-babel-load-in-session-maybe ()
  234. "Conditionally load a source block in a session.
  235. Detect if this is context for a org-babel src-block and if so
  236. then run `org-babel-load-in-session'."
  237. (interactive)
  238. (let ((info (org-babel-get-src-block-info)))
  239. (if info
  240. (progn (org-babel-load-in-session current-prefix-arg info) t)
  241. nil)))
  242. (add-hook 'org-metaup-hook 'org-babel-load-in-session-maybe)
  243. ;;;###autoload
  244. (defun org-babel-pop-to-session-maybe ()
  245. "Conditionally pop to a session.
  246. Detect if this is context for a org-babel src-block and if so
  247. then run `org-babel-pop-to-session'."
  248. (interactive)
  249. (let ((info (org-babel-get-src-block-info)))
  250. (if info (progn (org-babel-pop-to-session current-prefix-arg info) t) nil)))
  251. (add-hook 'org-metadown-hook 'org-babel-pop-to-session-maybe)
  252. (defconst org-babel-header-arg-names
  253. '(cache cmdline colnames dir exports file noweb results
  254. session tangle var eval noeval comments no-expand)
  255. "Common header arguments used by org-babel.
  256. Note that individual languages may define their own language
  257. specific header arguments as well.")
  258. (defvar org-babel-default-header-args
  259. '((:session . "none") (:results . "replace") (:exports . "code")
  260. (:cache . "no") (:noweb . "no") (:hlines . "no") (:tangle . "no"))
  261. "Default arguments to use when evaluating a source block.")
  262. (defvar org-babel-default-inline-header-args
  263. '((:session . "none") (:results . "replace") (:exports . "results"))
  264. "Default arguments to use when evaluating an inline source block.")
  265. (defvar org-babel-current-buffer-properties nil
  266. "Local cache for buffer properties.")
  267. (make-variable-buffer-local 'org-babel-current-buffer-properties)
  268. (defvar org-babel-result-regexp
  269. "^[ \t]*#\\+res\\(ults\\|name\\)\\(\\[\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*"
  270. "Regular expression used to match result lines.
  271. If the results are associated with a hash key then the hash will
  272. be saved in the second match data.")
  273. (defvar org-babel-result-w-name-regexp
  274. (concat org-babel-result-regexp
  275. "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
  276. (defvar org-babel-min-lines-for-block-output 10
  277. "The minimum number of lines for block output.
  278. If number of lines of output is equal to or exceeds this
  279. value, the output is placed in a #+begin_example...#+end_example
  280. block. Otherwise the output is marked as literal by inserting
  281. colons at the starts of the lines. This variable only takes
  282. effect if the :results output option is in effect.")
  283. (defvar org-babel-noweb-error-langs nil
  284. "Languages for which Babel will raise literate programming errors.
  285. List of languages for which errors should be raised when the
  286. source code block satisfying a noweb reference in this language
  287. can not be resolved.")
  288. (defvar org-babel-hash-show 4
  289. "Number of initial characters to show of a hidden results hash.")
  290. (defvar org-babel-after-execute-hook nil
  291. "Hook for functions to be called after `org-babel-execute-src-block'")
  292. (defun org-babel-named-src-block-regexp-for-name (name)
  293. "This generates a regexp used to match a src block named NAME."
  294. (concat org-babel-src-name-regexp (regexp-quote name) "[ \t\n]*"
  295. (substring org-babel-src-block-regexp 1)))
  296. ;;; functions
  297. (defvar call-process-region)
  298. ;;;###autoload
  299. (defun org-babel-execute-src-block (&optional arg info params)
  300. "Execute the current source code block.
  301. Insert the results of execution into the buffer. Source code
  302. execution and the collection and formatting of results can be
  303. controlled through a variety of header arguments.
  304. With prefix argument ARG, force re-execution even if a an
  305. existing result cached in the buffer would otherwise have been
  306. returned.
  307. Optionally supply a value for INFO in the form returned by
  308. `org-babel-get-src-block-info'.
  309. Optionally supply a value for PARAMS which will be merged with
  310. the header arguments specified at the front of the source code
  311. block."
  312. (interactive)
  313. (let ((info (or info (org-babel-get-src-block-info))))
  314. (when (org-babel-confirm-evaluate info)
  315. (let* ((lang (nth 0 info))
  316. (params (if params
  317. (org-babel-process-params
  318. (org-babel-merge-params (nth 2 info) params))
  319. (nth 2 info)))
  320. (cache? (and (not arg) (cdr (assoc :cache params))
  321. (string= "yes" (cdr (assoc :cache params)))))
  322. (result-params (cdr (assoc :result-params params)))
  323. (new-hash (when cache? (org-babel-sha1-hash info)))
  324. (old-hash (when cache? (org-babel-result-hash info)))
  325. (body (setf (nth 1 info)
  326. (let ((noweb (cdr (assoc :noweb params))))
  327. (if (and noweb
  328. (or (string= "yes" noweb)
  329. (string= "tangle" noweb)))
  330. (org-babel-expand-noweb-references info)
  331. (nth 1 info)))))
  332. (dir (cdr (assoc :dir params)))
  333. (default-directory
  334. (or (and dir (file-name-as-directory dir)) default-directory))
  335. (org-babel-call-process-region-original
  336. (if (boundp 'org-babel-call-process-region-original)
  337. org-babel-call-process-region-original
  338. (symbol-function 'call-process-region)))
  339. (indent (car (last info)))
  340. result cmd)
  341. (unwind-protect
  342. (flet ((call-process-region (&rest args)
  343. (apply 'org-babel-tramp-handle-call-process-region args)))
  344. (flet ((lang-check (f)
  345. (let ((f (intern (concat "org-babel-execute:" f))))
  346. (when (fboundp f) f))))
  347. (setq cmd
  348. (or (lang-check lang)
  349. (lang-check (symbol-name
  350. (cdr (assoc lang org-src-lang-modes))))
  351. (error "No org-babel-execute function for %s!" lang))))
  352. (if (and (not arg) new-hash (equal new-hash old-hash))
  353. (save-excursion ;; return cached result
  354. (goto-char (org-babel-where-is-src-block-result nil info))
  355. (end-of-line 1) (forward-char 1)
  356. (setq result (org-babel-read-result))
  357. (message (replace-regexp-in-string
  358. "%" "%%" (format "%S" result))) result)
  359. (message "executing %s code block%s..."
  360. (capitalize lang)
  361. (if (nth 4 info) (format " (%s)" (nth 4 info)) ""))
  362. (setq result
  363. ((lambda (result)
  364. (if (and (eq (cdr (assoc :result-type params)) 'value)
  365. (or (member "vector" result-params)
  366. (member "table" result-params))
  367. (not (listp result)))
  368. (list (list result)) result))
  369. (funcall cmd body params)))
  370. ;; if non-empty result and :file then write to :file
  371. (when (cdr (assoc :file params))
  372. (when result
  373. (with-temp-file (cdr (assoc :file params))
  374. (insert
  375. (org-babel-format-result
  376. result (cdr (assoc :sep (nth 2 info)))))))
  377. (setq result (cdr (assoc :file params))))
  378. (org-babel-insert-result
  379. result result-params info new-hash indent lang)
  380. (run-hooks 'org-babel-after-execute-hook)
  381. result))
  382. (setq call-process-region 'org-babel-call-process-region-original))))))
  383. (defun org-babel-expand-body:generic (body params &optional var-lines)
  384. "Expand BODY with PARAMS.
  385. Expand a block of code with org-babel according to it's header
  386. arguments. This generic implementation of body expansion is
  387. called for languages which have not defined their own specific
  388. org-babel-expand-body:lang function."
  389. (mapconcat #'identity (append var-lines (list body)) "\n"))
  390. ;;;###autoload
  391. (defun org-babel-expand-src-block (&optional arg info params)
  392. "Expand the current source code block.
  393. Expand according to the source code block's header
  394. arguments and pop open the results in a preview buffer."
  395. (interactive)
  396. (let* ((info (or info (org-babel-get-src-block-info)))
  397. (lang (nth 0 info))
  398. (params (setf (nth 2 info)
  399. (sort (org-babel-merge-params (nth 2 info) params)
  400. (lambda (el1 el2) (string< (symbol-name (car el1))
  401. (symbol-name (car el2)))))))
  402. (body (setf (nth 1 info)
  403. (if (and (cdr (assoc :noweb params))
  404. (string= "yes" (cdr (assoc :noweb params))))
  405. (org-babel-expand-noweb-references info) (nth 1 info))))
  406. (expand-cmd (intern (concat "org-babel-expand-body:" lang)))
  407. (assignments-cmd (intern (concat "org-babel-variable-assignments:" lang)))
  408. (expanded
  409. (if (fboundp expand-cmd) (funcall expand-cmd body params)
  410. (org-babel-expand-body:generic
  411. body params (and (fboundp assignments-cmd) (funcall assignments-cmd params))))))
  412. (org-edit-src-code
  413. nil expanded (concat "*Org-Babel Preview " (buffer-name) "[ " lang " ]*"))))
  414. ;;;###autoload
  415. (defun org-babel-load-in-session (&optional arg info)
  416. "Load the body of the current source-code block.
  417. Evaluate the header arguments for the source block before
  418. entering the session. After loading the body this pops open the
  419. session."
  420. (interactive)
  421. (let* ((info (or info (org-babel-get-src-block-info)))
  422. (lang (nth 0 info))
  423. (params (nth 2 info))
  424. (body (setf (nth 1 info)
  425. (if (and (cdr (assoc :noweb params))
  426. (string= "yes" (cdr (assoc :noweb params))))
  427. (org-babel-expand-noweb-references info)
  428. (nth 1 info))))
  429. (session (cdr (assoc :session params)))
  430. (dir (cdr (assoc :dir params)))
  431. (default-directory
  432. (or (and dir (file-name-as-directory dir)) default-directory))
  433. (cmd (intern (concat "org-babel-load-session:" lang))))
  434. (unless (fboundp cmd)
  435. (error "No org-babel-load-session function for %s!" lang))
  436. (pop-to-buffer (funcall cmd session body params))
  437. (end-of-line 1)))
  438. ;;;###autoload
  439. (defun org-babel-initiate-session (&optional arg info)
  440. "Initiate session for current code block.
  441. If called with a prefix argument then resolve any variable
  442. references in the header arguments and assign these variables in
  443. the session. Copy the body of the code block to the kill ring."
  444. (interactive "P")
  445. (let* ((info (or info (org-babel-get-src-block-info (not arg))))
  446. (lang (nth 0 info))
  447. (body (nth 1 info))
  448. (params (nth 2 info))
  449. (session (cdr (assoc :session params)))
  450. (dir (cdr (assoc :dir params)))
  451. (default-directory
  452. (or (and dir (file-name-as-directory dir)) default-directory))
  453. (init-cmd (intern (format "org-babel-%s-initiate-session" lang)))
  454. (prep-cmd (intern (concat "org-babel-prep-session:" lang))))
  455. (if (and (stringp session) (string= session "none"))
  456. (error "This block is not using a session!"))
  457. (unless (fboundp init-cmd)
  458. (error "No org-babel-initiate-session function for %s!" lang))
  459. (with-temp-buffer (insert (org-babel-trim body))
  460. (copy-region-as-kill (point-min) (point-max)))
  461. (when arg
  462. (unless (fboundp prep-cmd)
  463. (error "No org-babel-prep-session function for %s!" lang))
  464. (funcall prep-cmd session params))
  465. (funcall init-cmd session params)))
  466. ;;;###autoload
  467. (defun org-babel-switch-to-session (&optional arg info)
  468. "Switch to the session of the current code block.
  469. Uses `org-babel-initiate-session' to start the session. If called
  470. with a prefix argument then this is passed on to
  471. `org-babel-initiate-session'."
  472. (interactive "P")
  473. (pop-to-buffer (org-babel-initiate-session arg info))
  474. (end-of-line 1))
  475. (defalias 'org-babel-pop-to-session 'org-babel-switch-to-session)
  476. ;;;###autoload
  477. (defun org-babel-switch-to-session-with-code (&optional arg info)
  478. "Switch to code buffer and display session."
  479. (interactive "P")
  480. (flet ((swap-windows
  481. ()
  482. (let ((other-window-buffer (window-buffer (next-window))))
  483. (set-window-buffer (next-window) (current-buffer))
  484. (set-window-buffer (selected-window) other-window-buffer))
  485. (other-window 1)))
  486. (let ((info (org-babel-get-src-block-info))
  487. (org-src-window-setup 'reorganize-frame))
  488. (save-excursion
  489. (org-babel-switch-to-session arg info))
  490. (org-edit-src-code))
  491. (swap-windows)))
  492. (defmacro org-babel-do-in-edit-buffer (&rest body)
  493. "Evaluate BODY in edit buffer if there is a code block at point.
  494. Return t if a code block was found at point, nil otherwise."
  495. `(let ((org-src-window-setup 'switch-invisibly))
  496. (when (and (org-babel-where-is-src-block-head)
  497. (org-edit-src-code nil nil nil))
  498. (unwind-protect (progn ,@body)
  499. (if (org-bound-and-true-p org-edit-src-from-org-mode)
  500. (org-edit-src-exit)))
  501. t)))
  502. (defun org-babel-do-key-sequence-in-edit-buffer (key)
  503. "Read key sequence and execute the command in edit buffer.
  504. Enter a key sequence to be executed in the language major-mode
  505. edit buffer. For example, TAB will alter the contents of the
  506. Org-mode code block according to the effect of TAB in the
  507. language major-mode buffer. For languages that support
  508. interactive sessions, this can be used to send code from the Org
  509. buffer to the session for evaluation using the native major-mode
  510. evaluation mechanisms."
  511. (interactive "kEnter key-sequence to execute in edit buffer: ")
  512. (org-babel-do-in-edit-buffer
  513. (call-interactively
  514. (key-binding (or key (read-key-sequence nil))))))
  515. (defvar org-bracket-link-regexp)
  516. ;;;###autoload
  517. (defun org-babel-open-src-block-result (&optional re-run)
  518. "If `point' is on a src block then open the results of the
  519. source code block, otherwise return nil. With optional prefix
  520. argument RE-RUN the source-code block is evaluated even if
  521. results already exist."
  522. (interactive "P")
  523. (let ((info (org-babel-get-src-block-info)))
  524. (when info
  525. (save-excursion
  526. ;; go to the results, if there aren't any then run the block
  527. (goto-char (or (and (not re-run) (org-babel-where-is-src-block-result))
  528. (progn (org-babel-execute-src-block)
  529. (org-babel-where-is-src-block-result))))
  530. (end-of-line 1)
  531. (while (looking-at "[\n\r\t\f ]") (forward-char 1))
  532. ;; open the results
  533. (if (looking-at org-bracket-link-regexp)
  534. ;; file results
  535. (org-open-at-point)
  536. (let ((r (org-babel-format-result
  537. (org-babel-read-result) (cdr (assoc :sep (nth 2 info))))))
  538. (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
  539. (delete-region (point-min) (point-max))
  540. (insert r)))
  541. t))))
  542. ;;;###autoload
  543. (defmacro org-babel-map-src-blocks (file &rest body)
  544. "Evaluate BODY forms on each source-block in FILE.
  545. If FILE is nil evaluate BODY forms on source blocks in current
  546. buffer. During evaluation of BODY the following local variables
  547. are set relative to the currently matched code block.
  548. full-block ------- string holding the entirety of the code block
  549. beg-block -------- point at the beginning of the code block
  550. end-block -------- point at the end of the matched code block
  551. lang ------------- string holding the language of the code block
  552. beg-lang --------- point at the beginning of the lang
  553. end-lang --------- point at the end of the lang
  554. switches --------- string holding the switches
  555. beg-switches ----- point at the beginning of the switches
  556. end-switches ----- point at the end of the switches
  557. header-args ------ string holding the header-args
  558. beg-header-args -- point at the beginning of the header-args
  559. end-header-args -- point at the end of the header-args
  560. body ------------- string holding the body of the code block
  561. beg-body --------- point at the beginning of the body
  562. end-body --------- point at the end of the body"
  563. (declare (indent 1))
  564. (let ((tempvar (make-symbol "file")))
  565. `(let* ((,tempvar ,file)
  566. (visited-p (or (null ,tempvar)
  567. (get-file-buffer (expand-file-name ,tempvar))))
  568. (point (point)) to-be-removed)
  569. (save-window-excursion
  570. (when ,tempvar (find-file ,tempvar))
  571. (setq to-be-removed (current-buffer))
  572. (goto-char (point-min))
  573. (while (re-search-forward org-babel-src-block-regexp nil t)
  574. (goto-char (match-beginning 0))
  575. (let ((full-block (match-string 0))
  576. (beg-block (match-beginning 0))
  577. (end-block (match-end 0))
  578. (lang (match-string 2))
  579. (beg-lang (match-beginning 2))
  580. (end-lang (match-end 2))
  581. (switches (match-string 3))
  582. (beg-switches (match-beginning 3))
  583. (end-switches (match-end 3))
  584. (header-args (match-string 4))
  585. (beg-header-args (match-beginning 4))
  586. (end-header-args (match-end 4))
  587. (body (match-string 5))
  588. (beg-body (match-beginning 5))
  589. (end-body (match-end 5)))
  590. ,@body
  591. (goto-char end-block))))
  592. (unless visited-p (kill-buffer to-be-removed))
  593. (goto-char point))))
  594. ;;;###autoload
  595. (defmacro org-babel-map-inline-src-blocks (file &rest body)
  596. "Evaluate BODY forms on each inline source-block in FILE.
  597. If FILE is nil evaluate BODY forms on source blocks in current
  598. buffer."
  599. (declare (indent 1))
  600. (let ((tempvar (make-symbol "file")))
  601. `(let* ((,tempvar ,file)
  602. (visited-p (or (null ,tempvar)
  603. (get-file-buffer (expand-file-name ,tempvar))))
  604. (point (point)) to-be-removed)
  605. (save-window-excursion
  606. (when ,tempvar (find-file ,tempvar))
  607. (setq to-be-removed (current-buffer))
  608. (goto-char (point-min))
  609. (while (re-search-forward org-babel-inline-src-block-regexp nil t)
  610. (goto-char (match-beginning 1))
  611. (save-match-data ,@body)
  612. (goto-char (match-end 0))))
  613. (unless visited-p (kill-buffer to-be-removed))
  614. (goto-char point))))
  615. ;;;###autoload
  616. (defun org-babel-execute-buffer (&optional arg)
  617. "Execute source code blocks in a buffer.
  618. Call `org-babel-execute-src-block' on every source block in
  619. the current buffer."
  620. (interactive "P")
  621. (org-babel-eval-wipe-error-buffer)
  622. (org-save-outline-visibility t
  623. (org-babel-map-src-blocks nil
  624. (org-babel-execute-src-block arg))
  625. (org-babel-map-inline-src-blocks nil
  626. (org-babel-execute-src-block arg))))
  627. ;;;###autoload
  628. (defun org-babel-execute-subtree (&optional arg)
  629. "Execute source code blocks in a subtree.
  630. Call `org-babel-execute-src-block' on every source block in
  631. the current subtree."
  632. (interactive "P")
  633. (save-restriction
  634. (save-excursion
  635. (org-narrow-to-subtree)
  636. (org-babel-execute-buffer arg)
  637. (widen))))
  638. ;;;###autoload
  639. (defun org-babel-sha1-hash (&optional info)
  640. "Generate an sha1 hash based on the value of info."
  641. (interactive)
  642. (let ((print-level nil)
  643. (info (or info (org-babel-get-src-block-info))))
  644. (setf (nth 2 info)
  645. (sort (copy-sequence (nth 2 info))
  646. (lambda (a b) (string< (car a) (car b)))))
  647. (let ((hash (sha1
  648. (format "%s-%s"
  649. (mapconcat
  650. #'identity
  651. (delq nil
  652. (mapcar
  653. (lambda (arg)
  654. (let ((v (cdr arg)))
  655. (when (and v (not (and (sequencep v)
  656. (not (consp v))
  657. (= (length v) 0))))
  658. (format "%S" v))))
  659. (nth 2 info))) ":")
  660. (nth 1 info)))))
  661. (when (interactive-p) (message hash))
  662. hash)))
  663. (defun org-babel-result-hash (&optional info)
  664. "Return the in-buffer hash associated with INFO."
  665. (org-babel-where-is-src-block-result nil info)
  666. (org-babel-clean-text-properties (match-string 3)))
  667. (defun org-babel-hide-hash ()
  668. "Hide the hash in the current results line.
  669. Only the initial `org-babel-hash-show' characters of the hash
  670. will remain visible."
  671. (add-to-invisibility-spec '(org-babel-hide-hash . t))
  672. (save-excursion
  673. (when (and (re-search-forward org-babel-result-regexp nil t)
  674. (match-string 3))
  675. (let* ((start (match-beginning 3))
  676. (hide-start (+ org-babel-hash-show start))
  677. (end (match-end 3))
  678. (hash (match-string 3))
  679. ov1 ov2)
  680. (setq ov1 (make-overlay start hide-start))
  681. (setq ov2 (make-overlay hide-start end))
  682. (overlay-put ov2 'invisible 'org-babel-hide-hash)
  683. (overlay-put ov1 'babel-hash hash)))))
  684. (defun org-babel-hide-all-hashes ()
  685. "Hide the hash in the current buffer.
  686. Only the initial `org-babel-hash-show' characters of each hash
  687. will remain visible. This function should be called as part of
  688. the `org-mode-hook'."
  689. (save-excursion
  690. (while (re-search-forward org-babel-result-regexp nil t)
  691. (goto-char (match-beginning 0))
  692. (org-babel-hide-hash)
  693. (goto-char (match-end 0)))))
  694. (add-hook 'org-mode-hook 'org-babel-hide-all-hashes)
  695. (defun org-babel-hash-at-point (&optional point)
  696. "Return the value of the hash at POINT.
  697. The hash is also added as the last element of the kill ring.
  698. This can be called with C-c C-c."
  699. (interactive)
  700. (let ((hash (car (delq nil (mapcar
  701. (lambda (ol) (overlay-get ol 'babel-hash))
  702. (overlays-at (or point (point))))))))
  703. (when hash (kill-new hash) (message hash))))
  704. (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-hash-at-point)
  705. (defun org-babel-result-hide-spec ()
  706. "Hide portions of results lines.
  707. Add `org-babel-hide-result' as an invisibility spec for hiding
  708. portions of results lines."
  709. (add-to-invisibility-spec '(org-babel-hide-result . t)))
  710. (add-hook 'org-mode-hook 'org-babel-result-hide-spec)
  711. (defvar org-babel-hide-result-overlays nil
  712. "Overlays hiding results.")
  713. (defun org-babel-result-hide-all ()
  714. "Fold all results in the current buffer."
  715. (interactive)
  716. (org-babel-show-result-all)
  717. (save-excursion
  718. (while (re-search-forward org-babel-result-regexp nil t)
  719. (save-excursion (goto-char (match-beginning 0))
  720. (org-babel-hide-result-toggle-maybe)))))
  721. (defun org-babel-show-result-all ()
  722. "Unfold all results in the current buffer."
  723. (mapc 'delete-overlay org-babel-hide-result-overlays)
  724. (setq org-babel-hide-result-overlays nil))
  725. ;;;###autoload
  726. (defun org-babel-hide-result-toggle-maybe ()
  727. "Toggle visibility of result at point."
  728. (interactive)
  729. (let ((case-fold-search t))
  730. (if (save-excursion
  731. (beginning-of-line 1)
  732. (looking-at org-babel-result-regexp))
  733. (progn (org-babel-hide-result-toggle)
  734. t) ;; to signal that we took action
  735. nil))) ;; to signal that we did not
  736. (defun org-babel-hide-result-toggle (&optional force)
  737. "Toggle the visibility of the current result."
  738. (interactive)
  739. (save-excursion
  740. (beginning-of-line)
  741. (if (re-search-forward org-babel-result-regexp nil t)
  742. (let ((start (progn (beginning-of-line 2) (- (point) 1)))
  743. (end (progn (goto-char (- (org-babel-result-end) 1)) (point)))
  744. ov)
  745. (if (memq t (mapcar (lambda (overlay)
  746. (eq (overlay-get overlay 'invisible)
  747. 'org-babel-hide-result))
  748. (overlays-at start)))
  749. (if (or (not force) (eq force 'off))
  750. (mapc (lambda (ov)
  751. (when (member ov org-babel-hide-result-overlays)
  752. (setq org-babel-hide-result-overlays
  753. (delq ov org-babel-hide-result-overlays)))
  754. (when (eq (overlay-get ov 'invisible)
  755. 'org-babel-hide-result)
  756. (delete-overlay ov)))
  757. (overlays-at start)))
  758. (setq ov (make-overlay start end))
  759. (overlay-put ov 'invisible 'org-babel-hide-result)
  760. ;; make the block accessible to isearch
  761. (overlay-put
  762. ov 'isearch-open-invisible
  763. (lambda (ov)
  764. (when (member ov org-babel-hide-result-overlays)
  765. (setq org-babel-hide-result-overlays
  766. (delq ov org-babel-hide-result-overlays)))
  767. (when (eq (overlay-get ov 'invisible)
  768. 'org-babel-hide-result)
  769. (delete-overlay ov))))
  770. (push ov org-babel-hide-result-overlays)))
  771. (error "Not looking at a result line"))))
  772. ;; org-tab-after-check-for-cycling-hook
  773. (add-hook 'org-tab-first-hook 'org-babel-hide-result-toggle-maybe)
  774. ;; Remove overlays when changing major mode
  775. (add-hook 'org-mode-hook
  776. (lambda () (org-add-hook 'change-major-mode-hook
  777. 'org-babel-show-result-all 'append 'local)))
  778. (defvar org-file-properties)
  779. (defun org-babel-params-from-properties (&optional lang)
  780. "Retrieve parameters specified as properties.
  781. Return an association list of any source block params which
  782. may be specified in the properties of the current outline entry."
  783. (save-match-data
  784. (let (val sym)
  785. (delq nil
  786. (mapcar
  787. (lambda (header-arg)
  788. (and (setq val
  789. (or (org-entry-get (point) header-arg t)
  790. (org-entry-get (point) (concat ":" header-arg) t)))
  791. (cons (intern (concat ":" header-arg))
  792. (org-babel-read val))))
  793. (mapcar
  794. 'symbol-name
  795. (append
  796. org-babel-header-arg-names
  797. (progn
  798. (setq sym (intern (concat "org-babel-header-arg-names:" lang)))
  799. (and (boundp sym) (eval sym))))))))))
  800. (defun org-babel-params-from-buffer ()
  801. "Retrieve per-buffer parameters.
  802. Return an association list of any source block params which
  803. may be specified in the current buffer."
  804. (or org-babel-current-buffer-properties
  805. (save-match-data
  806. (save-excursion
  807. (save-restriction
  808. (widen)
  809. (goto-char (point-min))
  810. (while (re-search-forward
  811. (org-make-options-regexp (list "BABEL")) nil t)
  812. (setq org-babel-current-buffer-properties
  813. (org-babel-merge-params
  814. org-babel-current-buffer-properties
  815. (org-babel-parse-header-arguments
  816. (org-match-string-no-properties 2)))))
  817. org-babel-current-buffer-properties)))))
  818. (defvar org-src-preserve-indentation)
  819. (defun org-babel-parse-src-block-match ()
  820. "Parse the results from a match of the `org-babel-src-block-regexp'."
  821. (let* ((block-indentation (length (match-string 1)))
  822. (lang (org-babel-clean-text-properties (match-string 2)))
  823. (lang-headers (intern (concat "org-babel-default-header-args:" lang)))
  824. (switches (match-string 3))
  825. (body (org-babel-clean-text-properties (match-string 5)))
  826. (preserve-indentation (or org-src-preserve-indentation
  827. (string-match "-i\\>" switches))))
  828. (list lang
  829. ;; get block body less properties, protective commas, and indentation
  830. (with-temp-buffer
  831. (save-match-data
  832. (insert (org-babel-strip-protective-commas body))
  833. (unless preserve-indentation (org-do-remove-indentation))
  834. (buffer-string)))
  835. (org-babel-merge-params
  836. org-babel-default-header-args
  837. (org-babel-params-from-buffer)
  838. (org-babel-params-from-properties lang)
  839. (if (boundp lang-headers) (eval lang-headers) nil)
  840. (org-babel-parse-header-arguments
  841. (org-babel-clean-text-properties (or (match-string 4) ""))))
  842. switches
  843. block-indentation)))
  844. (defun org-babel-parse-inline-src-block-match ()
  845. "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
  846. (let* ((lang (org-babel-clean-text-properties (match-string 2)))
  847. (lang-headers (intern (concat "org-babel-default-header-args:" lang))))
  848. (list lang
  849. (org-babel-strip-protective-commas
  850. (org-babel-clean-text-properties (match-string 5)))
  851. (org-babel-merge-params
  852. org-babel-default-inline-header-args
  853. (org-babel-params-from-buffer)
  854. (org-babel-params-from-properties lang)
  855. (if (boundp lang-headers) (eval lang-headers) nil)
  856. (org-babel-parse-header-arguments
  857. (org-babel-clean-text-properties (or (match-string 4) "")))))))
  858. (defun org-babel-parse-header-arguments (arg-string)
  859. "Parse a string of header arguments returning an alist."
  860. (when (> (length arg-string) 0)
  861. (delq nil
  862. (mapcar
  863. (lambda (arg)
  864. (if (string-match
  865. "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
  866. arg)
  867. (cons (intern (match-string 1 arg))
  868. (org-babel-read (org-babel-chomp (match-string 2 arg))))
  869. (cons (intern (org-babel-chomp arg)) nil)))
  870. (let ((balance 0) (partial nil) (lst nil) (last 0))
  871. (mapc (lambda (ch) ; split on [] balanced instances of [ \t]:
  872. (setq balance (+ balance
  873. (cond ((equal 91 ch) 1)
  874. ((equal 93 ch) -1)
  875. (t 0))))
  876. (setq partial (cons ch partial))
  877. (when (and (= ch 58) (= balance 0)
  878. (or (= last 32) (= last 9)))
  879. (setq lst (cons (apply #'string (nreverse (cddr partial)))
  880. lst))
  881. (setq partial (list ch)))
  882. (setq last ch))
  883. (string-to-list arg-string))
  884. (nreverse (cons (apply #'string (nreverse partial)) lst)))))))
  885. (defun org-babel-process-params (params)
  886. "Expand variables in PARAMS and add summary parameters."
  887. (let* ((vars-and-names (org-babel-disassemble-tables
  888. (mapcar (lambda (el)
  889. (if (consp (cdr el))
  890. (cdr el) (org-babel-ref-parse (cdr el))))
  891. (org-babel-get-header params :var))
  892. (cdr (assoc :hlines params))
  893. (cdr (assoc :colnames params))
  894. (cdr (assoc :rownames params))))
  895. (result-params (append
  896. (split-string (or (cdr (assoc :results params)) ""))
  897. (cdr (assoc :result-params params)))))
  898. (append
  899. (mapcar (lambda (var) (cons :var var)) (car vars-and-names))
  900. (list
  901. (cons :colname-names (cadr vars-and-names))
  902. (cons :rowname-names (caddr vars-and-names))
  903. (cons :result-params result-params)
  904. (cons :result-type (cond ((member "output" result-params) 'output)
  905. ((member "value" result-params) 'value)
  906. (t 'value))))
  907. (org-babel-get-header params :var 'other))))
  908. ;; row and column names
  909. (defun org-babel-del-hlines (table)
  910. "Remove all 'hlines from TABLE."
  911. (remove 'hline table))
  912. (defun org-babel-get-colnames (table)
  913. "Return the column names of TABLE.
  914. Return a cons cell, the `car' of which contains the TABLE less
  915. colnames, and the `cdr' of which contains a list of the column
  916. names."
  917. (if (equal 'hline (nth 1 table))
  918. (cons (cddr table) (car table))
  919. (cons (cdr table) (car table))))
  920. (defun org-babel-get-rownames (table)
  921. "Return the row names of TABLE.
  922. Return a cons cell, the `car' of which contains the TABLE less
  923. colnames, and the `cdr' of which contains a list of the column
  924. names. Note: this function removes any hlines in TABLE."
  925. (flet ((trans (table) (apply #'mapcar* #'list table)))
  926. (let* ((width (apply 'max
  927. (mapcar (lambda (el) (if (listp el) (length el) 0)) table)))
  928. (table (trans (mapcar (lambda (row)
  929. (if (not (equal row 'hline))
  930. row
  931. (setq row '())
  932. (dotimes (n width)
  933. (setq row (cons 'hline row)))
  934. row))
  935. table))))
  936. (cons (mapcar (lambda (row) (if (equal (car row) 'hline) 'hline row))
  937. (trans (cdr table)))
  938. (remove 'hline (car table))))))
  939. (defun org-babel-put-colnames (table colnames)
  940. "Add COLNAMES to TABLE if they exist."
  941. (if colnames (apply 'list colnames 'hline table) table))
  942. (defun org-babel-put-rownames (table rownames)
  943. "Add ROWNAMES to TABLE if they exist."
  944. (if rownames
  945. (mapcar (lambda (row)
  946. (if (listp row)
  947. (cons (or (pop rownames) "") row)
  948. row)) table)
  949. table))
  950. (defun org-babel-pick-name (names selector)
  951. "Select one out of an alist of row or column names.
  952. SELECTOR can be either a list of names in which case those names
  953. will be returned directly, or an index into the list NAMES in
  954. which case the indexed names will be return."
  955. (if (listp selector)
  956. selector
  957. (when names
  958. (if (and selector (symbolp selector) (not (equal t selector)))
  959. (cdr (assoc selector names))
  960. (if (integerp selector)
  961. (nth (- selector 1) names)
  962. (cdr (car (last names))))))))
  963. (defun org-babel-disassemble-tables (vars hlines colnames rownames)
  964. "Parse tables for further processing.
  965. Process the variables in VARS according to the HLINES,
  966. ROWNAMES and COLNAMES header arguments. Return a list consisting
  967. of the vars, cnames and rnames."
  968. (let (cnames rnames)
  969. (list
  970. (mapcar
  971. (lambda (var)
  972. (when (listp (cdr var))
  973. (when (and (not (equal colnames "no"))
  974. (or colnames (and (equal (nth 1 (cdr var)) 'hline)
  975. (not (member 'hline (cddr (cdr var)))))))
  976. (let ((both (org-babel-get-colnames (cdr var))))
  977. (setq cnames (cons (cons (car var) (cdr both))
  978. cnames))
  979. (setq var (cons (car var) (car both)))))
  980. (when (and rownames (not (equal rownames "no")))
  981. (let ((both (org-babel-get-rownames (cdr var))))
  982. (setq rnames (cons (cons (car var) (cdr both))
  983. rnames))
  984. (setq var (cons (car var) (car both)))))
  985. (when (and hlines (not (equal hlines "yes")))
  986. (setq var (cons (car var) (org-babel-del-hlines (cdr var))))))
  987. var)
  988. vars)
  989. cnames rnames)))
  990. (defun org-babel-reassemble-table (table colnames rownames)
  991. "Add column and row names to a table.
  992. Given a TABLE and set of COLNAMES and ROWNAMES add the names
  993. to the table for reinsertion to org-mode."
  994. (if (listp table)
  995. ((lambda (table)
  996. (if (and colnames (listp (car table)) (= (length (car table))
  997. (length colnames)))
  998. (org-babel-put-colnames table colnames) table))
  999. (if (and rownames (= (length table) (length rownames)))
  1000. (org-babel-put-rownames table rownames) table))
  1001. table))
  1002. (defun org-babel-where-is-src-block-head ()
  1003. "Find where the current source block begins.
  1004. Return the point at the beginning of the current source
  1005. block. Specifically at the beginning of the #+BEGIN_SRC line.
  1006. If the point is not on a source block then return nil."
  1007. (let ((initial (point)) top bottom)
  1008. (or
  1009. (save-excursion ;; on a source name line or a #+header line
  1010. (beginning-of-line 1)
  1011. (and (or (looking-at org-babel-src-name-regexp)
  1012. (looking-at org-babel-multi-line-header-regexp))
  1013. (progn
  1014. (while (and (forward-line 1)
  1015. (looking-at org-babel-multi-line-header-regexp)))
  1016. (looking-at org-babel-src-block-regexp))
  1017. (point)))
  1018. (save-excursion ;; on a #+begin_src line
  1019. (beginning-of-line 1)
  1020. (and (looking-at org-babel-src-block-regexp)
  1021. (point)))
  1022. (save-excursion ;; inside a src block
  1023. (and
  1024. (re-search-backward "^[ \t]*#\\+begin_src" nil t) (setq top (point))
  1025. (re-search-forward "^[ \t]*#\\+end_src" nil t) (setq bottom (point))
  1026. (< top initial) (< initial bottom)
  1027. (progn (goto-char top) (beginning-of-line 1)
  1028. (looking-at org-babel-src-block-regexp))
  1029. (point))))))
  1030. ;;;###autoload
  1031. (defun org-babel-goto-src-block-head ()
  1032. "Go to the beginning of the current code block."
  1033. (interactive)
  1034. ((lambda (head)
  1035. (if head (goto-char head) (error "not currently in a code block")))
  1036. (org-babel-where-is-src-block-head)))
  1037. ;;;###autoload
  1038. (defun org-babel-goto-named-src-block (name)
  1039. "Go to a named source-code block."
  1040. (interactive
  1041. (let ((completion-ignore-case t))
  1042. (list (org-icompleting-read "source-block name: "
  1043. (org-babel-src-block-names) nil t))))
  1044. (let ((point (org-babel-find-named-block name)))
  1045. (if point
  1046. ;; taken from `org-open-at-point'
  1047. (progn (goto-char point) (org-show-context))
  1048. (message "source-code block '%s' not found in this buffer" name))))
  1049. (defun org-babel-find-named-block (name)
  1050. "Find a named source-code block.
  1051. Return the location of the source block identified by source
  1052. NAME, or nil if no such block exists. Set match data according to
  1053. org-babel-named-src-block-regexp."
  1054. (save-excursion
  1055. (let ((case-fold-search t)
  1056. (regexp (org-babel-named-src-block-regexp-for-name name)) msg)
  1057. (goto-char (point-min))
  1058. (when (or (re-search-forward regexp nil t)
  1059. (re-search-backward regexp nil t))
  1060. (match-beginning 0)))))
  1061. (defun org-babel-src-block-names (&optional file)
  1062. "Returns the names of source blocks in FILE or the current buffer."
  1063. (save-excursion
  1064. (when file (find-file file)) (goto-char (point-min))
  1065. (let (names)
  1066. (while (re-search-forward org-babel-src-name-w-name-regexp nil t)
  1067. (setq names (cons (match-string 4) names)))
  1068. names)))
  1069. ;;;###autoload
  1070. (defun org-babel-goto-named-result (name)
  1071. "Go to a named result."
  1072. (interactive
  1073. (let ((completion-ignore-case t))
  1074. (list (org-icompleting-read "source-block name: "
  1075. (org-babel-result-names) nil t))))
  1076. (let ((point (org-babel-find-named-result name)))
  1077. (if point
  1078. ;; taken from `org-open-at-point'
  1079. (progn (goto-char point) (org-show-context))
  1080. (message "result '%s' not found in this buffer" name))))
  1081. (defun org-babel-find-named-result (name)
  1082. "Find a named result.
  1083. Return the location of the result named NAME in the current
  1084. buffer or nil if no such result exists."
  1085. (save-excursion
  1086. (goto-char (point-min))
  1087. (when (re-search-forward
  1088. (concat org-babel-result-regexp
  1089. "[ \t]" (regexp-quote name) "[ \t\n\f\v\r]") nil t)
  1090. (beginning-of-line 0) (point))))
  1091. (defun org-babel-result-names (&optional file)
  1092. "Returns the names of results in FILE or the current buffer."
  1093. (save-excursion
  1094. (when file (find-file file)) (goto-char (point-min))
  1095. (let (names)
  1096. (while (re-search-forward org-babel-result-w-name-regexp nil t)
  1097. (setq names (cons (match-string 4) names)))
  1098. names)))
  1099. ;;;###autoload
  1100. (defun org-babel-next-src-block (&optional arg)
  1101. "Jump to the next source block.
  1102. With optional prefix argument ARG, jump forward ARG many source blocks."
  1103. (interactive "P")
  1104. (when (looking-at org-babel-src-block-regexp) (forward-char 1))
  1105. (condition-case nil
  1106. (re-search-forward org-babel-src-block-regexp nil nil (or arg 1))
  1107. (error (error "No further code blocks")))
  1108. (goto-char (match-beginning 0)) (org-show-context))
  1109. ;;;###autoload
  1110. (defun org-babel-previous-src-block (&optional arg)
  1111. "Jump to the previous source block.
  1112. With optional prefix argument ARG, jump backward ARG many source blocks."
  1113. (interactive "P")
  1114. (condition-case nil
  1115. (re-search-backward org-babel-src-block-regexp nil nil (or arg 1))
  1116. (error (error "No previous code blocks")))
  1117. (goto-char (match-beginning 0)) (org-show-context))
  1118. (defvar org-babel-load-languages)
  1119. ;;;###autoload
  1120. (defun org-babel-mark-block ()
  1121. "Mark current src block"
  1122. (interactive)
  1123. ((lambda (head)
  1124. (when head
  1125. (save-excursion
  1126. (goto-char head)
  1127. (looking-at org-babel-src-block-regexp))
  1128. (push-mark (match-end 5) nil t)
  1129. (goto-char (match-beginning 5))))
  1130. (org-babel-where-is-src-block-head)))
  1131. (defun org-babel-demarcate-block (&optional arg)
  1132. "Wrap or split the code in the region or on the point.
  1133. When called from inside of a code block the current block is
  1134. split. When called from outside of a code block a new code block
  1135. is created. In both cases if the region is demarcated and if the
  1136. region is not active then the point is demarcated."
  1137. (interactive "P")
  1138. (let ((info (org-babel-get-src-block-info 'light))
  1139. (stars (concat (make-string (or (org-current-level) 1) ?*) " ")))
  1140. (if info
  1141. (mapc
  1142. (lambda (place)
  1143. (save-excursion
  1144. (goto-char place)
  1145. (let ((lang (nth 0 info))
  1146. (indent (make-string (nth 5 info) ? )))
  1147. (when (string-match "^[[:space:]]*$"
  1148. (buffer-substring (point-at-bol)
  1149. (point-at-eol)))
  1150. (delete-region (point-at-bol) (point-at-eol)))
  1151. (insert (concat (if (looking-at "^") "" "\n")
  1152. indent "#+end_src\n"
  1153. (if arg stars indent) "\n"
  1154. indent "#+begin_src " lang
  1155. (if (looking-at "[\n\r]") "" "\n")))))
  1156. (move-end-of-line 2))
  1157. (sort (if (region-active-p) (list (mark) (point)) (list (point))) #'>))
  1158. (let ((start (point))
  1159. (lang (org-icompleting-read "Lang: "
  1160. (mapcar (lambda (el) (symbol-name (car el)))
  1161. org-babel-load-languages)))
  1162. (body (delete-and-extract-region
  1163. (if (region-active-p) (mark) (point)) (point))))
  1164. (insert (concat (if (looking-at "^") "" "\n")
  1165. (if arg (concat stars "\n") "")
  1166. "#+begin_src " lang "\n"
  1167. body
  1168. (if (or (= (length body) 0)
  1169. (string-match "[\r\n]$" body)) "" "\n")
  1170. "#+end_src\n"))
  1171. (goto-char start) (move-end-of-line 1)))))
  1172. (defvar org-babel-lob-one-liner-regexp)
  1173. (defun org-babel-where-is-src-block-result (&optional insert info hash indent)
  1174. "Find where the current source block results begin.
  1175. Return the point at the beginning of the result of the current
  1176. source block. Specifically at the beginning of the results line.
  1177. If no result exists for this block then create a results line
  1178. following the source block."
  1179. (save-excursion
  1180. (let* ((on-lob-line (save-excursion
  1181. (beginning-of-line 1)
  1182. (looking-at org-babel-lob-one-liner-regexp)))
  1183. (inlinep (save-excursion
  1184. (re-search-backward "[ \f\t\n\r\v]" nil t)
  1185. (when (looking-at org-babel-inline-src-block-regexp)
  1186. (match-end 0))))
  1187. (name (if on-lob-line
  1188. (nth 0 (org-babel-lob-get-info))
  1189. (nth 4 (or info (org-babel-get-src-block-info)))))
  1190. (head (unless on-lob-line (org-babel-where-is-src-block-head)))
  1191. found beg end)
  1192. (when head (goto-char head))
  1193. (setq
  1194. found ;; was there a result (before we potentially insert one)
  1195. (or
  1196. inlinep
  1197. (and
  1198. ;; named results:
  1199. ;; - return t if it is found, else return nil
  1200. ;; - if it does not need to be rebuilt, then don't set end
  1201. ;; - if it does need to be rebuilt then do set end
  1202. name (setq beg (org-babel-find-named-result name))
  1203. (prog1 beg
  1204. (when (and hash (not (string= hash (match-string 3))))
  1205. (goto-char beg) (setq end beg) ;; beginning of result
  1206. (forward-line 1)
  1207. (delete-region end (org-babel-result-end)) nil)))
  1208. (and
  1209. ;; unnamed results:
  1210. ;; - return t if it is found, else return nil
  1211. ;; - if it is found, and the hash doesn't match, delete and set end
  1212. (or on-lob-line (re-search-forward "^[ \t]*#\\+end_src" nil t))
  1213. (progn (end-of-line 1)
  1214. (if (eobp) (insert "\n") (forward-char 1))
  1215. (setq end (point))
  1216. (or (and (not name)
  1217. (progn ;; unnamed results line already exists
  1218. (re-search-forward "[^ \f\t\n\r\v]" nil t)
  1219. (beginning-of-line 1)
  1220. (looking-at
  1221. (concat org-babel-result-regexp "\n")))
  1222. (prog1 (point)
  1223. ;; must remove and rebuild if hash!=old-hash
  1224. (if (and hash (not (string= hash (match-string 3))))
  1225. (prog1 nil
  1226. (forward-line 1)
  1227. (delete-region
  1228. end (org-babel-result-end)))
  1229. (setq end nil)))))))))
  1230. (if (and insert end)
  1231. (progn
  1232. (goto-char end)
  1233. (unless beg
  1234. (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
  1235. (insert (concat
  1236. (if indent
  1237. (mapconcat
  1238. (lambda (el) " ")
  1239. (org-number-sequence 1 indent) "")
  1240. "")
  1241. "#+results"
  1242. (when hash (concat "["hash"]"))
  1243. ":"
  1244. (when name (concat " " name)) "\n"))
  1245. (unless beg (insert "\n") (backward-char))
  1246. (beginning-of-line 0)
  1247. (if hash (org-babel-hide-hash))
  1248. (point))
  1249. found))))
  1250. (defvar org-block-regexp)
  1251. (defun org-babel-read-result ()
  1252. "Read the result at `point' into emacs-lisp."
  1253. (let ((case-fold-search t) result-string)
  1254. (cond
  1255. ((org-at-table-p) (org-babel-read-table))
  1256. ((org-in-item-p) (org-babel-read-list))
  1257. ((looking-at org-bracket-link-regexp) (org-babel-read-link))
  1258. ((looking-at org-block-regexp) (org-babel-trim (match-string 4)))
  1259. ((looking-at "^[ \t]*: ")
  1260. (setq result-string
  1261. (org-babel-trim
  1262. (mapconcat (lambda (line)
  1263. (if (and (> (length line) 1)
  1264. (string-match "^[ \t]*: \\(.+\\)" line))
  1265. (match-string 1 line)
  1266. line))
  1267. (split-string
  1268. (buffer-substring
  1269. (point) (org-babel-result-end)) "[\r\n]+")
  1270. "\n")))
  1271. (or (org-babel-number-p result-string) result-string))
  1272. ((looking-at org-babel-result-regexp)
  1273. (save-excursion (forward-line 1) (org-babel-read-result))))))
  1274. (defun org-babel-read-table ()
  1275. "Read the table at `point' into emacs-lisp."
  1276. (mapcar (lambda (row)
  1277. (if (and (symbolp row) (equal row 'hline)) row
  1278. (mapcar #'org-babel-read row)))
  1279. (org-table-to-lisp)))
  1280. (defun org-babel-read-list ()
  1281. "Read the list at `point' into emacs-lisp."
  1282. (mapcar #'org-babel-read (cdr (org-list-parse-list))))
  1283. (defvar org-link-types-re)
  1284. (defun org-babel-read-link ()
  1285. "Read the link at `point' into emacs-lisp.
  1286. If the path of the link is a file path it is expanded using
  1287. `expand-file-name'."
  1288. (let* ((case-fold-search t)
  1289. (raw (and (looking-at org-bracket-link-regexp)
  1290. (org-babel-clean-text-properties (match-string 1))))
  1291. (type (and (string-match org-link-types-re raw)
  1292. (match-string 1 raw))))
  1293. (cond
  1294. ((not type) (expand-file-name raw))
  1295. ((string= type "file")
  1296. (and (string-match "file\\(.*\\):\\(.+\\)" raw)
  1297. (expand-file-name (match-string 2 raw))))
  1298. (t raw))))
  1299. (defun org-babel-format-result (result &optional sep)
  1300. "Format RESULT for writing to file."
  1301. (flet ((echo-res (result)
  1302. (if (stringp result) result (format "%S" result))))
  1303. (if (listp result)
  1304. ;; table result
  1305. (orgtbl-to-generic
  1306. result
  1307. (list
  1308. :sep (or sep "\t")
  1309. :fmt 'echo-res))
  1310. ;; scalar result
  1311. (echo-res result))))
  1312. (defun org-babel-insert-result
  1313. (result &optional result-params info hash indent lang)
  1314. "Insert RESULT into the current buffer.
  1315. By default RESULT is inserted after the end of the
  1316. current source block. With optional argument RESULT-PARAMS
  1317. controls insertion of results in the org-mode file.
  1318. RESULT-PARAMS can take the following values...
  1319. replace - (default option) insert results after the source block
  1320. replacing any previously inserted results
  1321. silent -- no results are inserted
  1322. file ---- the results are interpreted as a file path, and are
  1323. inserted into the buffer using the Org-mode file syntax
  1324. list ---- the results are interpreted as an Org-mode list.
  1325. raw ----- results are added directly to the Org-mode file. This
  1326. is a good option if you code block will output org-mode
  1327. formatted text.
  1328. org ----- similar in effect to raw, only the results are wrapped
  1329. in an org code block. Similar to the raw option, on
  1330. export the results will be interpreted as org-formatted
  1331. text, however by wrapping the results in an org code
  1332. block they can be replaced upon re-execution of the
  1333. code block.
  1334. html ---- results are added inside of a #+BEGIN_HTML block. This
  1335. is a good option if you code block will output html
  1336. formatted text.
  1337. latex --- results are added inside of a #+BEGIN_LATEX block.
  1338. This is a good option if you code block will output
  1339. latex formatted text.
  1340. code ---- the results are extracted in the syntax of the source
  1341. code of the language being evaluated and are added
  1342. inside of a #+BEGIN_SRC block with the source-code
  1343. language set appropriately. Note this relies on the
  1344. optional LANG argument."
  1345. (if (stringp result)
  1346. (progn
  1347. (setq result (org-babel-clean-text-properties result))
  1348. (when (member "file" result-params)
  1349. (setq result (org-babel-result-to-file result))))
  1350. (unless (listp result) (setq result (format "%S" result))))
  1351. (if (and result-params (member "silent" result-params))
  1352. (progn
  1353. (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
  1354. result)
  1355. (save-excursion
  1356. (let* ((inlinep (save-excursion
  1357. (re-search-backward "[ \f\t\n\r\v]" nil t)
  1358. (when (looking-at org-babel-inline-src-block-regexp)
  1359. (goto-char (match-end 0))
  1360. (insert (if (listp result) "\n" " "))
  1361. (point))))
  1362. (existing-result (unless inlinep
  1363. (org-babel-where-is-src-block-result
  1364. t info hash indent)))
  1365. (results-switches
  1366. (cdr (assoc :results_switches (nth 2 info))))
  1367. beg end)
  1368. (when (and (stringp result) ; ensure results end in a newline
  1369. (not inlinep)
  1370. (> (length result) 0)
  1371. (not (or (string-equal (substring result -1) "\n")
  1372. (string-equal (substring result -1) "\r"))))
  1373. (setq result (concat result "\n")))
  1374. (if (not existing-result)
  1375. (setq beg (or inlinep (point)))
  1376. (goto-char existing-result)
  1377. (save-excursion
  1378. (re-search-forward "#" nil t)
  1379. (setq indent (- (current-column) 1)))
  1380. (forward-line 1)
  1381. (setq beg (point))
  1382. (cond
  1383. ((member "replace" result-params)
  1384. (delete-region (point) (org-babel-result-end)))
  1385. ((member "append" result-params)
  1386. (goto-char (org-babel-result-end)) (setq beg (point-marker)))
  1387. ((member "prepend" result-params)))) ; already there
  1388. (setq results-switches
  1389. (if results-switches (concat " " results-switches) ""))
  1390. ;; insert results based on type
  1391. (cond
  1392. ;; do nothing for an empty result
  1393. ((= (length result) 0))
  1394. ;; insert a list if preferred
  1395. ((member "list" result-params)
  1396. (insert
  1397. (org-babel-trim
  1398. (org-list-to-generic (cons 'unordered
  1399. (if (listp result) result (list result)))
  1400. '(:splicep nil :istart "- " :iend "\n")))))
  1401. ;; assume the result is a table if it's not a string
  1402. ((not (stringp result))
  1403. (goto-char beg)
  1404. (insert (concat (orgtbl-to-orgtbl
  1405. (if (or (eq 'hline (car result))
  1406. (and (listp (car result))
  1407. (listp (cdr (car result)))))
  1408. result (list result))
  1409. '(:fmt (lambda (cell) (format "%s" cell)))) "\n"))
  1410. (goto-char beg) (when (org-at-table-p) (org-table-align)))
  1411. ((member "file" result-params)
  1412. (insert result))
  1413. (t (goto-char beg) (insert result)))
  1414. (when (listp result) (goto-char (org-table-end)))
  1415. (setq end (point-marker))
  1416. ;; possibly wrap result
  1417. (flet ((wrap (start finish)
  1418. (goto-char beg) (insert (concat start "\n"))
  1419. (goto-char end) (insert (concat finish "\n"))
  1420. (setq end (point-marker))))
  1421. (cond
  1422. ((member "html" result-params)
  1423. (wrap "#+BEGIN_HTML" "#+END_HTML"))
  1424. ((member "latex" result-params)
  1425. (wrap "#+BEGIN_LaTeX" "#+END_LaTeX"))
  1426. ((member "code" result-params)
  1427. (wrap (format "#+BEGIN_SRC %s%s" (or lang "none") results-switches)
  1428. "#+END_SRC"))
  1429. ((member "org" result-params)
  1430. (wrap "#+BEGIN_ORG" "#+END_ORG"))
  1431. ((member "raw" result-params)
  1432. (goto-char beg) (if (org-at-table-p) (org-cycle)))
  1433. ((member "wrap" result-params)
  1434. (when (and (stringp result) (not (member "file" result-params)))
  1435. (org-babel-examplize-region beg end results-switches))
  1436. (wrap "#+BEGIN_RESULT" "#+END_RESULT"))
  1437. ((and (stringp result) (not (member "file" result-params)))
  1438. (org-babel-examplize-region beg end results-switches)
  1439. (setq end (point)))))
  1440. ;; possibly indent the results to match the #+results line
  1441. (when (and (not inlinep) (numberp indent) indent (> indent 0)
  1442. ;; in this case `table-align' does the work for us
  1443. (not (and (listp result)
  1444. (member "append" result-params))))
  1445. (indent-rigidly beg end indent))))
  1446. (if (= (length result) 0)
  1447. (if (member "value" result-params)
  1448. (message "Code block returned no value.")
  1449. (message "Code block produced no output."))
  1450. (message "Code block evaluation complete."))))
  1451. (defun org-babel-remove-result (&optional info)
  1452. "Remove the result of the current source block."
  1453. (interactive)
  1454. (let ((location (org-babel-where-is-src-block-result nil info)) start)
  1455. (when location
  1456. (save-excursion
  1457. (goto-char location) (setq start (point)) (forward-line 1)
  1458. (delete-region start (org-babel-result-end))))))
  1459. (defun org-babel-result-end ()
  1460. "Return the point at the end of the current set of results"
  1461. (save-excursion
  1462. (cond
  1463. ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
  1464. ((org-at-item-p) (- (org-list-bottom-point) 1))
  1465. (t
  1466. (let ((case-fold-search t)
  1467. (blocks-re (regexp-opt
  1468. (list "latex" "html" "example" "src" "result" "org"))))
  1469. (if (looking-at (concat "[ \t]*#\\+begin_" blocks-re))
  1470. (progn (re-search-forward (concat "[ \t]*#\\+end_" blocks-re) nil t)
  1471. (forward-char 1))
  1472. (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
  1473. (forward-line 1))))
  1474. (point)))))
  1475. (defun org-babel-result-to-file (result)
  1476. "Convert RESULT into an `org-mode' link.
  1477. If the `default-directory' is different from the containing
  1478. file's directory then expand relative links."
  1479. (flet ((cond-exp (file)
  1480. (if (and default-directory
  1481. buffer-file-name
  1482. (not (string= (expand-file-name default-directory)
  1483. (expand-file-name
  1484. (file-name-directory buffer-file-name)))))
  1485. (expand-file-name file default-directory)
  1486. file)))
  1487. (if (stringp result)
  1488. (format "[[file:%s]]" (cond-exp result))
  1489. (when (and (listp result) (= 2 (length result))
  1490. (stringp (car result)) (stringp (cadr result)))
  1491. (format "[[file:%s][%s]]" (car result) (cadr result))))))
  1492. (defun org-babel-examplize-region (beg end &optional results-switches)
  1493. "Comment out region using the inline '==' or ': ' org example quote."
  1494. (interactive "*r")
  1495. (flet ((chars-between (b e) (string-match "[\\S]" (buffer-substring b e))))
  1496. (if (or (chars-between (save-excursion (goto-char beg) (point-at-bol)) beg)
  1497. (chars-between end (save-excursion (goto-char end) (point-at-eol))))
  1498. (save-excursion
  1499. (goto-char beg)
  1500. (insert (format "=%s=" (prog1 (buffer-substring beg end)
  1501. (delete-region beg end)))))
  1502. (let ((size (count-lines beg end)))
  1503. (save-excursion
  1504. (cond ((= size 0)) ; do nothing for an empty result
  1505. ((< size org-babel-min-lines-for-block-output)
  1506. (goto-char beg)
  1507. (dotimes (n size)
  1508. (beginning-of-line 1) (insert ": ") (forward-line 1)))
  1509. (t
  1510. (goto-char beg)
  1511. (insert (if results-switches
  1512. (format "#+begin_example%s\n" results-switches)
  1513. "#+begin_example\n"))
  1514. (if (markerp end) (goto-char end) (forward-char (- end beg)))
  1515. (insert "#+end_example\n"))))))))
  1516. (defun org-babel-update-block-body (new-body)
  1517. "Update the body of the current code block to NEW-BODY."
  1518. (if (not (org-babel-where-is-src-block-head))
  1519. (error "not in source block")
  1520. (save-match-data
  1521. (replace-match (concat (org-babel-trim new-body) "\n") nil t nil 5))
  1522. (indent-rigidly (match-beginning 5) (match-end 5) 2)))
  1523. (defun org-babel-merge-params (&rest plists)
  1524. "Combine all parameter association lists in PLISTS.
  1525. Later elements of PLISTS override the values of previous elements.
  1526. This takes into account some special considerations for certain
  1527. parameters when merging lists."
  1528. (let ((results-exclusive-groups
  1529. '(("file" "list" "vector" "table" "scalar" "raw" "org"
  1530. "html" "latex" "code" "pp" "wrap")
  1531. ("replace" "silent" "append" "prepend")
  1532. ("output" "value")))
  1533. (exports-exclusive-groups
  1534. '(("code" "results" "both" "none")))
  1535. params results exports tangle noweb cache vars shebang comments)
  1536. (flet ((e-merge (exclusive-groups &rest result-params)
  1537. ;; maintain exclusivity of mutually exclusive parameters
  1538. (let (output)
  1539. (mapc (lambda (new-params)
  1540. (mapc (lambda (new-param)
  1541. (mapc (lambda (exclusive-group)
  1542. (when (member new-param exclusive-group)
  1543. (mapcar (lambda (excluded-param)
  1544. (setq output
  1545. (delete
  1546. excluded-param
  1547. output)))
  1548. exclusive-group)))
  1549. exclusive-groups)
  1550. (setq output (org-uniquify
  1551. (cons new-param output))))
  1552. new-params))
  1553. result-params)
  1554. output)))
  1555. (mapc
  1556. (lambda (plist)
  1557. (mapc
  1558. (lambda (pair)
  1559. (case (car pair)
  1560. (:var
  1561. (let ((name (if (listp (cdr pair))
  1562. (cadr pair)
  1563. (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
  1564. (cdr pair))
  1565. (intern (match-string 1 (cdr pair)))))))
  1566. (when name
  1567. (setq vars
  1568. (cons (cons name pair)
  1569. (if (member name (mapcar #'car vars))
  1570. (delq nil
  1571. (mapcar
  1572. (lambda (p) (unless (equal (car p) name) p))
  1573. vars))
  1574. vars))))))
  1575. (:results
  1576. (setq results (e-merge results-exclusive-groups
  1577. results (split-string (cdr pair)))))
  1578. (:file
  1579. (when (cdr pair)
  1580. (setq results (e-merge results-exclusive-groups
  1581. results '("file")))
  1582. (unless (or (member "both" exports)
  1583. (member "none" exports)
  1584. (member "code" exports))
  1585. (setq exports (e-merge exports-exclusive-groups
  1586. exports '("results"))))
  1587. (setq params (cons pair (assq-delete-all (car pair) params)))))
  1588. (:exports
  1589. (setq exports (e-merge exports-exclusive-groups
  1590. exports (split-string (cdr pair)))))
  1591. (:tangle ;; take the latest -- always overwrite
  1592. (setq tangle (or (list (cdr pair)) tangle)))
  1593. (:noweb
  1594. (setq noweb (e-merge '(("yes" "no" "tangle")) noweb
  1595. (split-string (or (cdr pair) "")))))
  1596. (:cache
  1597. (setq cache (e-merge '(("yes" "no")) cache
  1598. (split-string (or (cdr pair) "")))))
  1599. (:shebang ;; take the latest -- always overwrite
  1600. (setq shebang (or (list (cdr pair)) shebang)))
  1601. (:comments
  1602. (setq comments (e-merge '(("yes" "no")) comments
  1603. (split-string (or (cdr pair) "")))))
  1604. (t ;; replace: this covers e.g. :session
  1605. (setq params (cons pair (assq-delete-all (car pair) params))))))
  1606. plist))
  1607. plists))
  1608. (while vars (setq params (cons (cons :var (cddr (pop vars))) params)))
  1609. (cons (cons :comments (mapconcat 'identity comments " "))
  1610. (cons (cons :shebang (mapconcat 'identity shebang " "))
  1611. (cons (cons :cache (mapconcat 'identity cache " "))
  1612. (cons (cons :noweb (mapconcat 'identity noweb " "))
  1613. (cons (cons :tangle (mapconcat 'identity tangle " "))
  1614. (cons (cons :exports
  1615. (mapconcat 'identity exports " "))
  1616. (cons
  1617. (cons :results
  1618. (mapconcat 'identity results " "))
  1619. params)))))))))
  1620. (defun org-babel-expand-noweb-references (&optional info parent-buffer)
  1621. "Expand Noweb references in the body of the current source code block.
  1622. For example the following reference would be replaced with the
  1623. body of the source-code block named 'example-block'.
  1624. <<example-block>>
  1625. Note that any text preceding the <<foo>> construct on a line will
  1626. be interposed between the lines of the replacement text. So for
  1627. example if <<foo>> is placed behind a comment, then the entire
  1628. replacement text will also be commented.
  1629. This function must be called from inside of the buffer containing
  1630. the source-code block which holds BODY.
  1631. In addition the following syntax can be used to insert the
  1632. results of evaluating the source-code block named 'example-block'.
  1633. <<example-block()>>
  1634. Any optional arguments can be passed to example-block by placing
  1635. the arguments inside the parenthesis following the convention
  1636. defined by `org-babel-lob'. For example
  1637. <<example-block(a=9)>>
  1638. would set the value of argument \"a\" equal to \"9\". Note that
  1639. these arguments are not evaluated in the current source-code
  1640. block but are passed literally to the \"example-block\"."
  1641. (let* ((parent-buffer (or parent-buffer (current-buffer)))
  1642. (info (or info (org-babel-get-src-block-info)))
  1643. (lang (nth 0 info))
  1644. (body (nth 1 info))
  1645. (comment (string= "noweb" (cdr (assoc :comments (nth 2 info)))))
  1646. (new-body "") index source-name evaluate prefix)
  1647. (flet ((nb-add (text) (setq new-body (concat new-body text)))
  1648. (c-wrap (text)
  1649. (with-temp-buffer
  1650. (funcall (intern (concat lang "-mode")))
  1651. (comment-region (point) (progn (insert text) (point)))
  1652. (org-babel-trim (buffer-string)))))
  1653. (with-temp-buffer
  1654. (insert body) (goto-char (point-min))
  1655. (setq index (point))
  1656. (while (and (re-search-forward "<<\\(.+?\\)>>" nil t))
  1657. (save-match-data (setf source-name (match-string 1)))
  1658. (save-match-data (setq evaluate (string-match "\(.*\)" source-name)))
  1659. (save-match-data
  1660. (setq prefix
  1661. (buffer-substring (match-beginning 0)
  1662. (save-excursion
  1663. (beginning-of-line 1) (point)))))
  1664. ;; add interval to new-body (removing noweb reference)
  1665. (goto-char (match-beginning 0))
  1666. (nb-add (buffer-substring index (point)))
  1667. (goto-char (match-end 0))
  1668. (setq index (point))
  1669. (nb-add
  1670. (with-current-buffer parent-buffer
  1671. (mapconcat ;; interpose PREFIX between every line
  1672. #'identity
  1673. (split-string
  1674. (if evaluate
  1675. (let ((raw (org-babel-ref-resolve source-name)))
  1676. (if (stringp raw) raw (format "%S" raw)))
  1677. (or (nth 2 (assoc (intern source-name)
  1678. org-babel-library-of-babel))
  1679. (save-restriction
  1680. (widen)
  1681. (let ((point (org-babel-find-named-block
  1682. source-name)))
  1683. (if point
  1684. (save-excursion
  1685. (goto-char point)
  1686. ;; possibly wrap body in comments
  1687. (let* ((i (org-babel-get-src-block-info 'light))
  1688. (body (org-babel-trim
  1689. (org-babel-expand-noweb-references
  1690. i))))
  1691. (if comment
  1692. ((lambda (cs) (concat (c-wrap (car cs)) "\n"
  1693. body
  1694. "\n" (c-wrap (cadr cs))))
  1695. (org-babel-tangle-comment-links i))
  1696. body)))
  1697. ;; optionally raise an error if named
  1698. ;; source-block doesn't exist
  1699. (if (member lang org-babel-noweb-error-langs)
  1700. (error "%s"
  1701. (concat
  1702. "<<" source-name ">> "
  1703. "could not be resolved (see "
  1704. "`org-babel-noweb-error-langs')"))
  1705. ""))))))
  1706. "[\n\r]") (concat "\n" prefix)))))
  1707. (nb-add (buffer-substring index (point-max)))))
  1708. new-body))
  1709. (defun org-babel-clean-text-properties (text)
  1710. "Strip all properties from text return."
  1711. (when text
  1712. (set-text-properties 0 (length text) nil text) text))
  1713. (defun org-babel-strip-protective-commas (body)
  1714. "Strip protective commas from bodies of source blocks."
  1715. (replace-regexp-in-string "^,#" "#" body))
  1716. (defun org-babel-script-escape (str)
  1717. "Safely convert tables into elisp lists."
  1718. (let (in-single in-double out)
  1719. (org-babel-read
  1720. (if (and (stringp str)
  1721. (> (length str) 2)
  1722. (string-equal "[" (substring str 0 1))
  1723. (string-equal "]" (substring str -1)))
  1724. (org-babel-read
  1725. (concat
  1726. "'"
  1727. (progn
  1728. (mapc
  1729. (lambda (ch)
  1730. (setq
  1731. out
  1732. (case ch
  1733. (91 (if (or in-double in-single) ; [
  1734. (cons 91 out)
  1735. (cons 40 out)))
  1736. (93 (if (or in-double in-single) ; ]
  1737. (cons 93 out)
  1738. (cons 41 out)))
  1739. (44 (if (or in-double in-single) ; ,
  1740. (cons 44 out) (cons 32 out)))
  1741. (39 (if in-double ; '
  1742. (cons 39 out)
  1743. (setq in-single (not in-single)) (cons 34 out)))
  1744. (34 (if in-single ; "
  1745. (append (list 34 32) out)
  1746. (setq in-double (not in-double)) (cons 34 out)))
  1747. (t (cons ch out)))))
  1748. (string-to-list str))
  1749. (apply #'string (reverse out)))))
  1750. str))))
  1751. (defun org-babel-read (cell)
  1752. "Convert the string value of CELL to a number if appropriate.
  1753. Otherwise if cell looks like lisp (meaning it starts with a
  1754. \"(\" or a \"'\") then read it as lisp, otherwise return it
  1755. unmodified as a string.
  1756. This is taken almost directly from `org-read-prop'."
  1757. (if (and (stringp cell) (not (equal cell "")))
  1758. (or (org-babel-number-p cell)
  1759. (if (or (equal "(" (substring cell 0 1))
  1760. (equal "'" (substring cell 0 1))
  1761. (equal "`" (substring cell 0 1)))
  1762. (eval (read cell))
  1763. (progn (set-text-properties 0 (length cell) nil cell) cell)))
  1764. cell))
  1765. (defun org-babel-number-p (string)
  1766. "If STRING represents a number return it's value."
  1767. (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string)
  1768. (= (length (substring string (match-beginning 0)
  1769. (match-end 0)))
  1770. (length string)))
  1771. (string-to-number string)))
  1772. (defun org-babel-import-elisp-from-file (file-name &optional separator)
  1773. "Read the results located at FILE-NAME into an elisp table.
  1774. If the table is trivial, then return it as a scalar."
  1775. (let (result)
  1776. (save-window-excursion
  1777. (with-temp-buffer
  1778. (condition-case nil
  1779. (progn
  1780. (org-table-import file-name separator)
  1781. (delete-file file-name)
  1782. (setq result (mapcar (lambda (row)
  1783. (mapcar #'org-babel-string-read row))
  1784. (org-table-to-lisp))))
  1785. (error nil)))
  1786. (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
  1787. (if (consp (car result))
  1788. (if (null (cdr (car result)))
  1789. (caar result)
  1790. result)
  1791. (car result))
  1792. result))))
  1793. (defun org-babel-string-read (cell)
  1794. "Strip nested \"s from around strings."
  1795. (org-babel-read (or (and (stringp cell)
  1796. (string-match "\\\"\\(.+\\)\\\"" cell)
  1797. (match-string 1 cell))
  1798. cell)))
  1799. (defun org-babel-reverse-string (string)
  1800. "Return the reverse of STRING."
  1801. (apply 'string (reverse (string-to-list string))))
  1802. (defun org-babel-chomp (string &optional regexp)
  1803. "Strip trailing spaces and carriage returns from STRING.
  1804. Default regexp used is \"[ \f\t\n\r\v]\" but can be
  1805. overwritten by specifying a regexp as a second argument."
  1806. (let ((regexp (or regexp "[ \f\t\n\r\v]")))
  1807. (while (and (> (length string) 0)
  1808. (string-match regexp (substring string -1)))
  1809. (setq string (substring string 0 -1)))
  1810. string))
  1811. (defun org-babel-trim (string &optional regexp)
  1812. "Strip leading and trailing spaces and carriage returns from STRING.
  1813. Like `org-babel-chomp' only it runs on both the front and back
  1814. of the string."
  1815. (org-babel-chomp (org-babel-reverse-string
  1816. (org-babel-chomp (org-babel-reverse-string string) regexp))
  1817. regexp))
  1818. (defvar org-babel-org-babel-call-process-region-original nil)
  1819. (defun org-babel-tramp-handle-call-process-region
  1820. (start end program &optional delete buffer display &rest args)
  1821. "Use tramp to handle call-process-region.
  1822. Fixes a bug in `tramp-handle-call-process-region'."
  1823. (if (and (featurep 'tramp) (file-remote-p default-directory))
  1824. (let ((tmpfile (tramp-compat-make-temp-file "")))
  1825. (write-region start end tmpfile)
  1826. (when delete (delete-region start end))
  1827. (unwind-protect
  1828. ;; (apply 'call-process program tmpfile buffer display args)
  1829. ;; bug in tramp
  1830. (apply 'process-file program tmpfile buffer display args)
  1831. (delete-file tmpfile)))
  1832. ;; org-babel-call-process-region-original is the original emacs
  1833. ;; definition. It is in scope from the let binding in
  1834. ;; org-babel-execute-src-block
  1835. (apply org-babel-call-process-region-original
  1836. start end program delete buffer display args)))
  1837. (defun org-babel-local-file-name (file)
  1838. "Return the local name component of FILE."
  1839. (if (file-remote-p file)
  1840. (let (localname)
  1841. (with-parsed-tramp-file-name file nil
  1842. localname))
  1843. file))
  1844. (defun org-babel-process-file-name (name &optional no-quote-p)
  1845. "Prepare NAME to be used in an external process.
  1846. If NAME specifies a remote location, the remote portion of the
  1847. name is removed, since in that case the process will be executing
  1848. remotely. The file name is then processed by
  1849. `expand-file-name'. Unless second argument NO-QUOTE-P is non-nil,
  1850. the file name is additionally processed by
  1851. `shell-quote-argument'"
  1852. ((lambda (f) (if no-quote-p f (shell-quote-argument f)))
  1853. (expand-file-name (org-babel-local-file-name name))))
  1854. (defvar org-babel-temporary-directory)
  1855. (unless (or noninteractive (boundp 'org-babel-temporary-directory))
  1856. (defvar org-babel-temporary-directory
  1857. (or (and (boundp 'org-babel-temporary-directory)
  1858. (file-exists-p org-babel-temporary-directory)
  1859. org-babel-temporary-directory)
  1860. (make-temp-file "babel-" t))
  1861. "Directory to hold temporary files created to execute code blocks.
  1862. Used by `org-babel-temp-file'. This directory will be removed on
  1863. Emacs shutdown."))
  1864. (defun org-babel-temp-file (prefix &optional suffix)
  1865. "Create a temporary file in the `org-babel-temporary-directory'.
  1866. Passes PREFIX and SUFFIX directly to `make-temp-file' with the
  1867. value of `temporary-file-directory' temporarily set to the value
  1868. of `org-babel-temporary-directory'."
  1869. (if (file-remote-p default-directory)
  1870. (make-temp-file
  1871. (concat (file-remote-p default-directory)
  1872. (expand-file-name
  1873. prefix temporary-file-directory)
  1874. nil suffix))
  1875. (let ((temporary-file-directory
  1876. (or (and (boundp 'org-babel-temporary-directory)
  1877. (file-exists-p org-babel-temporary-directory)
  1878. org-babel-temporary-directory)
  1879. temporary-file-directory)))
  1880. (make-temp-file prefix nil suffix))))
  1881. (defun org-babel-remove-temporary-directory ()
  1882. "Remove `org-babel-temporary-directory' on Emacs shutdown."
  1883. (when (and (boundp 'org-babel-temporary-directory)
  1884. (file-exists-p org-babel-temporary-directory))
  1885. ;; taken from `delete-directory' in files.el
  1886. (condition-case nil
  1887. (progn
  1888. (mapc (lambda (file)
  1889. ;; This test is equivalent to
  1890. ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
  1891. ;; but more efficient
  1892. (if (eq t (car (file-attributes file)))
  1893. (delete-directory file)
  1894. (delete-file file)))
  1895. ;; We do not want to delete "." and "..".
  1896. (directory-files org-babel-temporary-directory 'full
  1897. "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
  1898. (delete-directory org-babel-temporary-directory))
  1899. (error
  1900. (message "Failed to remove temporary Org-babel directory %s"
  1901. (if (boundp 'org-babel-temporary-directory)
  1902. org-babel-temporary-directory
  1903. "[directory not defined]"))))))
  1904. (add-hook 'kill-emacs-hook 'org-babel-remove-temporary-directory)
  1905. (provide 'ob)
  1906. ;; arch-tag: 01a7ebee-06c5-4ee4-a709-e660d28c0af1
  1907. ;;; ob.el ends here