ob.el 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967
  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. "[ \f\t\n\r\v]\\(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. (org-babel-parse-header-arguments (match-string 1))
  160. (nth 2 info))))
  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 (or (equal eval "query")
  188. (if (functionp org-confirm-babel-evaluate)
  189. (funcall org-confirm-babel-evaluate
  190. (nth 0 info) (nth 1 info))
  191. 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)
  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 . "silent") (: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. (cmd (intern (concat "org-babel-execute:" lang)))
  333. (dir (cdr (assoc :dir params)))
  334. (default-directory
  335. (or (and dir (file-name-as-directory dir)) default-directory))
  336. (org-babel-call-process-region-original
  337. (if (boundp 'org-babel-call-process-region-original)
  338. org-babel-call-process-region-original
  339. (symbol-function 'call-process-region)))
  340. (indent (car (last info)))
  341. result)
  342. (unwind-protect
  343. (flet ((call-process-region (&rest args)
  344. (apply 'org-babel-tramp-handle-call-process-region args)))
  345. (unless (fboundp cmd)
  346. (error "No org-babel-execute function for %s!" lang))
  347. (if (and (not arg) new-hash (equal new-hash old-hash))
  348. (save-excursion ;; return cached result
  349. (goto-char (org-babel-where-is-src-block-result nil info))
  350. (end-of-line 1) (forward-char 1)
  351. (setq result (org-babel-read-result))
  352. (message (replace-regexp-in-string
  353. "%" "%%" (format "%S" result))) result)
  354. (message "executing %s code block%s..."
  355. (capitalize lang)
  356. (if (nth 4 info) (format " (%s)" (nth 4 info)) ""))
  357. (setq result
  358. ((lambda (result)
  359. (cond
  360. ((member "file" result-params)
  361. (cdr (assoc :file params)))
  362. ((and (eq (cdr (assoc :result-type params)) 'value)
  363. (or (member "vector" result-params)
  364. (member "table" result-params))
  365. (not (listp result)))
  366. (list (list result)))
  367. (t result)))
  368. (funcall cmd body params)))
  369. (org-babel-insert-result
  370. result result-params info new-hash indent lang)
  371. (run-hooks 'org-babel-after-execute-hook)
  372. result))
  373. (setq call-process-region 'org-babel-call-process-region-original))))))
  374. (defun org-babel-expand-body:generic (body params &optional var-lines)
  375. "Expand BODY with PARAMS.
  376. Expand a block of code with org-babel according to it's header
  377. arguments. This generic implementation of body expansion is
  378. called for languages which have not defined their own specific
  379. org-babel-expand-body:lang function."
  380. (mapconcat #'identity (append var-lines (list body)) "\n"))
  381. ;;;###autoload
  382. (defun org-babel-expand-src-block (&optional arg info params)
  383. "Expand the current source code block.
  384. Expand according to the source code block's header
  385. arguments and pop open the results in a preview buffer."
  386. (interactive)
  387. (let* ((info (or info (org-babel-get-src-block-info)))
  388. (lang (nth 0 info))
  389. (params (setf (nth 2 info)
  390. (sort (org-babel-merge-params (nth 2 info) params)
  391. (lambda (el1 el2) (string< (symbol-name (car el1))
  392. (symbol-name (car el2)))))))
  393. (body (setf (nth 1 info)
  394. (if (and (cdr (assoc :noweb params))
  395. (string= "yes" (cdr (assoc :noweb params))))
  396. (org-babel-expand-noweb-references info) (nth 1 info))))
  397. (expand-cmd (intern (concat "org-babel-expand-body:" lang)))
  398. (assignments-cmd (intern (concat "org-babel-variable-assignments:" lang)))
  399. (expanded
  400. (if (fboundp expand-cmd) (funcall expand-cmd body params)
  401. (org-babel-expand-body:generic
  402. body params (and (fboundp assignments-cmd) (funcall assignments-cmd params))))))
  403. (org-edit-src-code
  404. nil expanded (concat "*Org-Babel Preview " (buffer-name) "[ " lang " ]*"))))
  405. ;;;###autoload
  406. (defun org-babel-load-in-session (&optional arg info)
  407. "Load the body of the current source-code block.
  408. Evaluate the header arguments for the source block before
  409. entering the session. After loading the body this pops open the
  410. session."
  411. (interactive)
  412. (let* ((info (or info (org-babel-get-src-block-info)))
  413. (lang (nth 0 info))
  414. (params (nth 2 info))
  415. (body (setf (nth 1 info)
  416. (if (and (cdr (assoc :noweb params))
  417. (string= "yes" (cdr (assoc :noweb params))))
  418. (org-babel-expand-noweb-references info)
  419. (nth 1 info))))
  420. (session (cdr (assoc :session params)))
  421. (dir (cdr (assoc :dir params)))
  422. (default-directory
  423. (or (and dir (file-name-as-directory dir)) default-directory))
  424. (cmd (intern (concat "org-babel-load-session:" lang))))
  425. (unless (fboundp cmd)
  426. (error "No org-babel-load-session function for %s!" lang))
  427. (pop-to-buffer (funcall cmd session body params))
  428. (end-of-line 1)))
  429. ;;;###autoload
  430. (defun org-babel-initiate-session (&optional arg info)
  431. "Initiate session for current code block.
  432. If called with a prefix argument then resolve any variable
  433. references in the header arguments and assign these variables in
  434. the session. Copy the body of the code block to the kill ring."
  435. (interactive "P")
  436. (let* ((info (or info (org-babel-get-src-block-info (not arg))))
  437. (lang (nth 0 info))
  438. (body (nth 1 info))
  439. (params (nth 2 info))
  440. (session (cdr (assoc :session params)))
  441. (dir (cdr (assoc :dir params)))
  442. (default-directory
  443. (or (and dir (file-name-as-directory dir)) default-directory))
  444. (init-cmd (intern (format "org-babel-%s-initiate-session" lang)))
  445. (prep-cmd (intern (concat "org-babel-prep-session:" lang))))
  446. (if (and (stringp session) (string= session "none"))
  447. (error "This block is not using a session!"))
  448. (unless (fboundp init-cmd)
  449. (error "No org-babel-initiate-session function for %s!" lang))
  450. (with-temp-buffer (insert (org-babel-trim body))
  451. (copy-region-as-kill (point-min) (point-max)))
  452. (when arg
  453. (unless (fboundp prep-cmd)
  454. (error "No org-babel-prep-session function for %s!" lang))
  455. (funcall prep-cmd session params))
  456. (funcall init-cmd session params)))
  457. ;;;###autoload
  458. (defun org-babel-switch-to-session (&optional arg info)
  459. "Switch to the session of the current code block.
  460. Uses `org-babel-initiate-session' to start the session. If called
  461. with a prefix argument then this is passed on to
  462. `org-babel-initiate-session'."
  463. (interactive "P")
  464. (pop-to-buffer (org-babel-initiate-session arg info))
  465. (end-of-line 1))
  466. (defalias 'org-babel-pop-to-session 'org-babel-switch-to-session)
  467. ;;;###autoload
  468. (defun org-babel-switch-to-session-with-code (&optional arg info)
  469. "Switch to code buffer and display session."
  470. (interactive "P")
  471. (flet ((swap-windows
  472. ()
  473. (let ((other-window-buffer (window-buffer (next-window))))
  474. (set-window-buffer (next-window) (current-buffer))
  475. (set-window-buffer (selected-window) other-window-buffer))
  476. (other-window 1)))
  477. (let ((info (org-babel-get-src-block-info))
  478. (org-src-window-setup 'reorganize-frame))
  479. (save-excursion
  480. (org-babel-switch-to-session arg info))
  481. (org-edit-src-code))
  482. (swap-windows)))
  483. (defmacro org-babel-do-in-edit-buffer (&rest body)
  484. "Evaluate BODY in edit buffer if there is a code block at point.
  485. Return t if a code block was found at point, nil otherwise."
  486. `(let ((org-src-window-setup 'switch-invisibly))
  487. (when (and (org-babel-where-is-src-block-head)
  488. (org-edit-src-code nil nil nil 'quietly))
  489. (unwind-protect (progn ,@body)
  490. (if (org-bound-and-true-p org-edit-src-from-org-mode)
  491. (org-edit-src-exit)))
  492. t)))
  493. (defun org-babel-do-key-sequence-in-edit-buffer (key)
  494. "Read key sequence and execute the command in edit buffer.
  495. Enter a key sequence to be executed in the language major-mode
  496. edit buffer. For example, TAB will alter the contents of the
  497. Org-mode code block according to the effect of TAB in the
  498. language major-mode buffer. For languages that support
  499. interactive sessions, this can be used to send code from the Org
  500. buffer to the session for evaluation using the native major-mode
  501. evaluation mechanisms."
  502. (interactive "kEnter key-sequence to execute in edit buffer: ")
  503. (org-babel-do-in-edit-buffer
  504. (call-interactively
  505. (key-binding (or key (read-key-sequence nil))))))
  506. (defvar org-bracket-link-regexp)
  507. ;;;###autoload
  508. (defun org-babel-open-src-block-result (&optional re-run)
  509. "If `point' is on a src block then open the results of the
  510. source code block, otherwise return nil. With optional prefix
  511. argument RE-RUN the source-code block is evaluated even if
  512. results already exist."
  513. (interactive "P")
  514. (when (org-babel-get-src-block-info)
  515. (save-excursion
  516. ;; go to the results, if there aren't any then run the block
  517. (goto-char (or (and (not re-run) (org-babel-where-is-src-block-result))
  518. (progn (org-babel-execute-src-block)
  519. (org-babel-where-is-src-block-result))))
  520. (end-of-line 1)
  521. (while (looking-at "[\n\r\t\f ]") (forward-char 1))
  522. ;; open the results
  523. (if (looking-at org-bracket-link-regexp)
  524. ;; file results
  525. (org-open-at-point)
  526. (let ((results (org-babel-read-result)))
  527. (flet ((echo-res (result)
  528. (if (stringp result) result (format "%S" result))))
  529. (pop-to-buffer (get-buffer-create "org-babel-results"))
  530. (delete-region (point-min) (point-max))
  531. (if (listp results)
  532. ;; table result
  533. (insert (orgtbl-to-generic results '(:sep "\t" :fmt echo-res)))
  534. ;; scalar result
  535. (insert (echo-res results))))))
  536. t)))
  537. ;;;###autoload
  538. (defmacro org-babel-map-src-blocks (file &rest body)
  539. "Evaluate BODY forms on each source-block in FILE.
  540. If FILE is nil evaluate BODY forms on source blocks in current
  541. buffer. During evaluation of BODY the following local variables
  542. are set relative to the currently matched code block.
  543. full-block ------- string holding the entirety of the code block
  544. beg-block -------- point at the beginning of the code block
  545. end-block -------- point at the end of the matched code block
  546. lang ------------- string holding the language of the code block
  547. beg-lang --------- point at the beginning of the lang
  548. end-lang --------- point at the end of the lang
  549. switches --------- string holding the switches
  550. beg-switches ----- point at the beginning of the switches
  551. end-switches ----- point at the end of the switches
  552. header-args ------ string holding the header-args
  553. beg-header-args -- point at the beginning of the header-args
  554. end-header-args -- point at the end of the header-args
  555. body ------------- string holding the body of the code block
  556. beg-body --------- point at the beginning of the body
  557. end-body --------- point at the end of the body"
  558. (declare (indent 1))
  559. (let ((tempvar (make-symbol "file")))
  560. `(let* ((,tempvar ,file)
  561. (visited-p (or (null ,tempvar)
  562. (get-file-buffer (expand-file-name ,tempvar))))
  563. (point (point)) to-be-removed)
  564. (save-window-excursion
  565. (when ,tempvar (find-file ,tempvar))
  566. (setq to-be-removed (current-buffer))
  567. (goto-char (point-min))
  568. (while (re-search-forward org-babel-src-block-regexp nil t)
  569. (goto-char (match-beginning 0))
  570. (let ((full-block (match-string 0))
  571. (beg-block (match-beginning 0))
  572. (end-block (match-end 0))
  573. (lang (match-string 2))
  574. (beg-lang (match-beginning 2))
  575. (end-lang (match-end 2))
  576. (switches (match-string 3))
  577. (beg-switches (match-beginning 3))
  578. (end-switches (match-end 3))
  579. (header-args (match-string 4))
  580. (beg-header-args (match-beginning 4))
  581. (end-header-args (match-end 4))
  582. (body (match-string 5))
  583. (beg-body (match-beginning 5))
  584. (end-body (match-end 5)))
  585. ,@body
  586. (goto-char end-block))))
  587. (unless visited-p (kill-buffer to-be-removed))
  588. (goto-char point))))
  589. ;;;###autoload
  590. (defun org-babel-execute-buffer (&optional arg)
  591. "Execute source code blocks in a buffer.
  592. Call `org-babel-execute-src-block' on every source block in
  593. the current buffer."
  594. (interactive "P")
  595. (org-save-outline-visibility t
  596. (org-babel-map-src-blocks nil
  597. (org-babel-execute-src-block arg))))
  598. ;;;###autoload
  599. (defun org-babel-execute-subtree (&optional arg)
  600. "Execute source code blocks in a subtree.
  601. Call `org-babel-execute-src-block' on every source block in
  602. the current subtree."
  603. (interactive "P")
  604. (save-restriction
  605. (save-excursion
  606. (org-narrow-to-subtree)
  607. (org-babel-execute-buffer arg)
  608. (widen))))
  609. ;;;###autoload
  610. (defun org-babel-sha1-hash (&optional info)
  611. "Generate an sha1 hash based on the value of info."
  612. (interactive)
  613. (let ((print-level nil)
  614. (info (or info (org-babel-get-src-block-info))))
  615. (setf (nth 2 info)
  616. (sort (copy-sequence (nth 2 info))
  617. (lambda (a b) (string< (car a) (car b)))))
  618. (let ((hash (sha1
  619. (format "%s-%s"
  620. (mapconcat
  621. #'identity
  622. (delq nil
  623. (mapcar
  624. (lambda (arg)
  625. (let ((v (cdr arg)))
  626. (when (and v (not (and (sequencep v)
  627. (not (consp v))
  628. (= (length v) 0))))
  629. (format "%S" v))))
  630. (nth 2 info))) ":")
  631. (nth 1 info)))))
  632. (when (interactive-p) (message hash))
  633. hash)))
  634. (defun org-babel-result-hash (&optional info)
  635. "Return the in-buffer hash associated with INFO."
  636. (org-babel-where-is-src-block-result nil info)
  637. (org-babel-clean-text-properties (match-string 3)))
  638. (defun org-babel-hide-hash ()
  639. "Hide the hash in the current results line.
  640. Only the initial `org-babel-hash-show' characters of the hash
  641. will remain visible."
  642. (add-to-invisibility-spec '(org-babel-hide-hash . t))
  643. (save-excursion
  644. (when (and (re-search-forward org-babel-result-regexp nil t)
  645. (match-string 3))
  646. (let* ((start (match-beginning 3))
  647. (hide-start (+ org-babel-hash-show start))
  648. (end (match-end 3))
  649. (hash (match-string 3))
  650. ov1 ov2)
  651. (setq ov1 (make-overlay start hide-start))
  652. (setq ov2 (make-overlay hide-start end))
  653. (overlay-put ov2 'invisible 'org-babel-hide-hash)
  654. (overlay-put ov1 'babel-hash hash)))))
  655. (defun org-babel-hide-all-hashes ()
  656. "Hide the hash in the current buffer.
  657. Only the initial `org-babel-hash-show' characters of each hash
  658. will remain visible. This function should be called as part of
  659. the `org-mode-hook'."
  660. (save-excursion
  661. (while (re-search-forward org-babel-result-regexp nil t)
  662. (goto-char (match-beginning 0))
  663. (org-babel-hide-hash)
  664. (goto-char (match-end 0)))))
  665. (add-hook 'org-mode-hook 'org-babel-hide-all-hashes)
  666. (defun org-babel-hash-at-point (&optional point)
  667. "Return the value of the hash at POINT.
  668. The hash is also added as the last element of the kill ring.
  669. This can be called with C-c C-c."
  670. (interactive)
  671. (let ((hash (car (delq nil (mapcar
  672. (lambda (ol) (overlay-get ol 'babel-hash))
  673. (overlays-at (or point (point))))))))
  674. (when hash (kill-new hash) (message hash))))
  675. (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-hash-at-point)
  676. (defun org-babel-result-hide-spec ()
  677. "Hide portions of results lines.
  678. Add `org-babel-hide-result' as an invisibility spec for hiding
  679. portions of results lines."
  680. (add-to-invisibility-spec '(org-babel-hide-result . t)))
  681. (add-hook 'org-mode-hook 'org-babel-result-hide-spec)
  682. (defvar org-babel-hide-result-overlays nil
  683. "Overlays hiding results.")
  684. (defun org-babel-result-hide-all ()
  685. "Fold all results in the current buffer."
  686. (interactive)
  687. (org-babel-show-result-all)
  688. (save-excursion
  689. (while (re-search-forward org-babel-result-regexp nil t)
  690. (save-excursion (goto-char (match-beginning 0))
  691. (org-babel-hide-result-toggle-maybe)))))
  692. (defun org-babel-show-result-all ()
  693. "Unfold all results in the current buffer."
  694. (mapc 'delete-overlay org-babel-hide-result-overlays)
  695. (setq org-babel-hide-result-overlays nil))
  696. ;;;###autoload
  697. (defun org-babel-hide-result-toggle-maybe ()
  698. "Toggle visibility of result at point."
  699. (interactive)
  700. (let ((case-fold-search t))
  701. (if (save-excursion
  702. (beginning-of-line 1)
  703. (looking-at org-babel-result-regexp))
  704. (progn (org-babel-hide-result-toggle)
  705. t) ;; to signal that we took action
  706. nil))) ;; to signal that we did not
  707. (defun org-babel-hide-result-toggle (&optional force)
  708. "Toggle the visibility of the current result."
  709. (interactive)
  710. (save-excursion
  711. (beginning-of-line)
  712. (if (re-search-forward org-babel-result-regexp nil t)
  713. (let ((start (progn (beginning-of-line 2) (- (point) 1)))
  714. (end (progn (goto-char (- (org-babel-result-end) 1)) (point)))
  715. ov)
  716. (if (memq t (mapcar (lambda (overlay)
  717. (eq (overlay-get overlay 'invisible)
  718. 'org-babel-hide-result))
  719. (overlays-at start)))
  720. (if (or (not force) (eq force 'off))
  721. (mapc (lambda (ov)
  722. (when (member ov org-babel-hide-result-overlays)
  723. (setq org-babel-hide-result-overlays
  724. (delq ov org-babel-hide-result-overlays)))
  725. (when (eq (overlay-get ov 'invisible)
  726. 'org-babel-hide-result)
  727. (delete-overlay ov)))
  728. (overlays-at start)))
  729. (setq ov (make-overlay start end))
  730. (overlay-put ov 'invisible 'org-babel-hide-result)
  731. ;; make the block accessible to isearch
  732. (overlay-put
  733. ov 'isearch-open-invisible
  734. (lambda (ov)
  735. (when (member ov org-babel-hide-result-overlays)
  736. (setq org-babel-hide-result-overlays
  737. (delq ov org-babel-hide-result-overlays)))
  738. (when (eq (overlay-get ov 'invisible)
  739. 'org-babel-hide-result)
  740. (delete-overlay ov))))
  741. (push ov org-babel-hide-result-overlays)))
  742. (error "Not looking at a result line"))))
  743. ;; org-tab-after-check-for-cycling-hook
  744. (add-hook 'org-tab-first-hook 'org-babel-hide-result-toggle-maybe)
  745. ;; Remove overlays when changing major mode
  746. (add-hook 'org-mode-hook
  747. (lambda () (org-add-hook 'change-major-mode-hook
  748. 'org-babel-show-result-all 'append 'local)))
  749. (defvar org-file-properties)
  750. (defun org-babel-params-from-properties (&optional lang)
  751. "Retrieve parameters specified as properties.
  752. Return an association list of any source block params which
  753. may be specified in the properties of the current outline entry."
  754. (save-match-data
  755. (let (val sym)
  756. (delq nil
  757. (mapcar
  758. (lambda (header-arg)
  759. (and (setq val
  760. (or (condition-case nil
  761. (org-entry-get (point) header-arg t)
  762. (error nil))
  763. (cdr (assoc header-arg org-file-properties))))
  764. (cons (intern (concat ":" header-arg))
  765. (org-babel-read val))))
  766. (mapcar
  767. 'symbol-name
  768. (append
  769. org-babel-header-arg-names
  770. (progn
  771. (setq sym (intern (concat "org-babel-header-arg-names:" lang)))
  772. (and (boundp sym) (eval sym))))))))))
  773. (defun org-babel-params-from-buffer ()
  774. "Retrieve per-buffer parameters.
  775. Return an association list of any source block params which
  776. may be specified at the top of the current buffer."
  777. (or org-babel-current-buffer-properties
  778. (setq org-babel-current-buffer-properties
  779. (save-match-data
  780. (save-excursion
  781. (save-restriction
  782. (widen)
  783. (goto-char (point-min))
  784. (when (re-search-forward
  785. (org-make-options-regexp (list "BABEL")) nil t)
  786. (org-babel-parse-header-arguments
  787. (org-match-string-no-properties 2)))))))))
  788. (defvar org-src-preserve-indentation)
  789. (defun org-babel-parse-src-block-match ()
  790. "Parse the results from a match of the `org-babel-src-block-regexp'."
  791. (let* ((block-indentation (length (match-string 1)))
  792. (lang (org-babel-clean-text-properties (match-string 2)))
  793. (lang-headers (intern (concat "org-babel-default-header-args:" lang)))
  794. (switches (match-string 3))
  795. (body (org-babel-clean-text-properties (match-string 5)))
  796. (preserve-indentation (or org-src-preserve-indentation
  797. (string-match "-i\\>" switches))))
  798. (list lang
  799. ;; get block body less properties, protective commas, and indentation
  800. (with-temp-buffer
  801. (save-match-data
  802. (insert (org-babel-strip-protective-commas body))
  803. (unless preserve-indentation (org-do-remove-indentation))
  804. (buffer-string)))
  805. (org-babel-merge-params
  806. org-babel-default-header-args
  807. (org-babel-params-from-buffer)
  808. (org-babel-params-from-properties lang)
  809. (if (boundp lang-headers) (eval lang-headers) nil)
  810. (org-babel-parse-header-arguments
  811. (org-babel-clean-text-properties (or (match-string 4) ""))))
  812. switches
  813. block-indentation)))
  814. (defun org-babel-parse-inline-src-block-match ()
  815. "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
  816. (let* ((lang (org-babel-clean-text-properties (match-string 2)))
  817. (lang-headers (intern (concat "org-babel-default-header-args:" lang))))
  818. (list lang
  819. (org-babel-strip-protective-commas
  820. (org-babel-clean-text-properties (match-string 5)))
  821. (org-babel-merge-params
  822. org-babel-default-inline-header-args
  823. (org-babel-params-from-buffer)
  824. (org-babel-params-from-properties lang)
  825. (if (boundp lang-headers) (eval lang-headers) nil)
  826. (org-babel-parse-header-arguments
  827. (org-babel-clean-text-properties (or (match-string 4) "")))))))
  828. (defun org-babel-parse-header-arguments (arg-string)
  829. "Parse a string of header arguments returning an alist."
  830. (when (> (length arg-string) 0)
  831. (delq nil
  832. (mapcar
  833. (lambda (arg)
  834. (if (string-match
  835. "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
  836. arg)
  837. (cons (intern (match-string 1 arg))
  838. (org-babel-read (org-babel-chomp (match-string 2 arg))))
  839. (cons (intern (org-babel-chomp arg)) nil)))
  840. (let ((balance 0) (partial nil) (lst nil) (last 0))
  841. (mapc (lambda (ch) ; split on [] balanced instances of [ \t]:
  842. (setq balance (+ balance
  843. (cond ((equal 91 ch) 1)
  844. ((equal 93 ch) -1)
  845. (t 0))))
  846. (setq partial (cons ch partial))
  847. (when (and (= ch 58) (= balance 0)
  848. (or (= last 32) (= last 9)))
  849. (setq lst (cons (apply #'string (nreverse (cddr partial)))
  850. lst))
  851. (setq partial (list ch)))
  852. (setq last ch))
  853. (string-to-list arg-string))
  854. (nreverse (cons (apply #'string (nreverse partial)) lst)))))))
  855. (defun org-babel-process-params (params)
  856. "Expand variables in PARAMS and add summary parameters."
  857. (let* ((vars-and-names (org-babel-disassemble-tables
  858. (mapcar (lambda (el)
  859. (if (consp (cdr el))
  860. (cdr el) (org-babel-ref-parse (cdr el))))
  861. (org-babel-get-header params :var))
  862. (cdr (assoc :hlines params))
  863. (cdr (assoc :colnames params))
  864. (cdr (assoc :rownames params))))
  865. (result-params (append
  866. (split-string (or (cdr (assoc :results params)) ""))
  867. (cdr (assoc :result-params params)))))
  868. (append
  869. (mapcar (lambda (var) (cons :var var)) (car vars-and-names))
  870. (list
  871. (cons :colname-names (cadr vars-and-names))
  872. (cons :rowname-names (caddr vars-and-names))
  873. (cons :result-params result-params)
  874. (cons :result-type (cond ((member "output" result-params) 'output)
  875. ((member "value" result-params) 'value)
  876. (t 'value))))
  877. (org-babel-get-header params :var 'other))))
  878. ;; row and column names
  879. (defun org-babel-del-hlines (table)
  880. "Remove all 'hlines from TABLE."
  881. (remove 'hline table))
  882. (defun org-babel-get-colnames (table)
  883. "Return the column names of TABLE.
  884. Return a cons cell, the `car' of which contains the TABLE less
  885. colnames, and the `cdr' of which contains a list of the column
  886. names."
  887. (if (equal 'hline (nth 1 table))
  888. (cons (cddr table) (car table))
  889. (cons (cdr table) (car table))))
  890. (defun org-babel-get-rownames (table)
  891. "Return the row names of TABLE.
  892. Return a cons cell, the `car' of which contains the TABLE less
  893. colnames, and the `cdr' of which contains a list of the column
  894. names. Note: this function removes any hlines in TABLE."
  895. (flet ((trans (table) (apply #'mapcar* #'list table)))
  896. (let* ((width (apply 'max
  897. (mapcar (lambda (el) (if (listp el) (length el) 0)) table)))
  898. (table (trans (mapcar (lambda (row)
  899. (if (not (equal row 'hline))
  900. row
  901. (setq row '())
  902. (dotimes (n width)
  903. (setq row (cons 'hline row)))
  904. row))
  905. table))))
  906. (cons (mapcar (lambda (row) (if (equal (car row) 'hline) 'hline row))
  907. (trans (cdr table)))
  908. (remove 'hline (car table))))))
  909. (defun org-babel-put-colnames (table colnames)
  910. "Add COLNAMES to TABLE if they exist."
  911. (if colnames (apply 'list colnames 'hline table) table))
  912. (defun org-babel-put-rownames (table rownames)
  913. "Add ROWNAMES to TABLE if they exist."
  914. (if rownames
  915. (mapcar (lambda (row)
  916. (if (listp row)
  917. (cons (or (pop rownames) "") row)
  918. row)) table)
  919. table))
  920. (defun org-babel-pick-name (names selector)
  921. "Select one out of an alist of row or column names.
  922. SELECTOR can be either a list of names in which case those names
  923. will be returned directly, or an index into the list NAMES in
  924. which case the indexed names will be return."
  925. (if (listp selector)
  926. selector
  927. (when names
  928. (if (and selector (symbolp selector) (not (equal t selector)))
  929. (cdr (assoc selector names))
  930. (if (integerp selector)
  931. (nth (- selector 1) names)
  932. (cdr (car (last names))))))))
  933. (defun org-babel-disassemble-tables (vars hlines colnames rownames)
  934. "Parse tables for further processing.
  935. Process the variables in VARS according to the HLINES,
  936. ROWNAMES and COLNAMES header arguments. Return a list consisting
  937. of the vars, cnames and rnames."
  938. (let (cnames rnames)
  939. (list
  940. (mapcar
  941. (lambda (var)
  942. (when (listp (cdr var))
  943. (when (and (not (equal colnames "no"))
  944. (or colnames (and (equal (nth 1 (cdr var)) 'hline)
  945. (not (member 'hline (cddr (cdr var)))))))
  946. (let ((both (org-babel-get-colnames (cdr var))))
  947. (setq cnames (cons (cons (car var) (cdr both))
  948. cnames))
  949. (setq var (cons (car var) (car both)))))
  950. (when (and rownames (not (equal rownames "no")))
  951. (let ((both (org-babel-get-rownames (cdr var))))
  952. (setq rnames (cons (cons (car var) (cdr both))
  953. rnames))
  954. (setq var (cons (car var) (car both)))))
  955. (when (and hlines (not (equal hlines "yes")))
  956. (setq var (cons (car var) (org-babel-del-hlines (cdr var))))))
  957. var)
  958. vars)
  959. cnames rnames)))
  960. (defun org-babel-reassemble-table (table colnames rownames)
  961. "Add column and row names to a table.
  962. Given a TABLE and set of COLNAMES and ROWNAMES add the names
  963. to the table for reinsertion to org-mode."
  964. (if (listp table)
  965. ((lambda (table)
  966. (if (and colnames (listp (car table)) (= (length (car table))
  967. (length colnames)))
  968. (org-babel-put-colnames table colnames) table))
  969. (if (and rownames (= (length table) (length rownames)))
  970. (org-babel-put-rownames table rownames) table))
  971. table))
  972. (defun org-babel-where-is-src-block-head ()
  973. "Find where the current source block begins.
  974. Return the point at the beginning of the current source
  975. block. Specifically at the beginning of the #+BEGIN_SRC line.
  976. If the point is not on a source block then return nil."
  977. (let ((initial (point)) top bottom)
  978. (or
  979. (save-excursion ;; on a source name line
  980. (beginning-of-line 1)
  981. (and (looking-at org-babel-src-name-regexp) (forward-line 1)
  982. (looking-at org-babel-src-block-regexp)
  983. (point)))
  984. (save-excursion ;; on a #+begin_src line
  985. (beginning-of-line 1)
  986. (and (looking-at org-babel-src-block-regexp)
  987. (point)))
  988. (save-excursion ;; inside a src block
  989. (and
  990. (re-search-backward "^[ \t]*#\\+begin_src" nil t) (setq top (point))
  991. (re-search-forward "^[ \t]*#\\+end_src" nil t) (setq bottom (point))
  992. (< top initial) (< initial bottom)
  993. (progn (goto-char top) (beginning-of-line 1)
  994. (looking-at org-babel-src-block-regexp))
  995. (point))))))
  996. ;;;###autoload
  997. (defun org-babel-goto-src-block-head ()
  998. "Go to the beginning of the current code block."
  999. (interactive)
  1000. ((lambda (head)
  1001. (if head (goto-char head) (error "not currently in a code block")))
  1002. (org-babel-where-is-src-block-head)))
  1003. ;;;###autoload
  1004. (defun org-babel-goto-named-src-block (name)
  1005. "Go to a named source-code block."
  1006. (interactive
  1007. (let ((completion-ignore-case t))
  1008. (list (org-icompleting-read "source-block name: "
  1009. (org-babel-src-block-names) nil t))))
  1010. (let ((point (org-babel-find-named-block name)))
  1011. (if point
  1012. ;; taken from `org-open-at-point'
  1013. (progn (goto-char point) (org-show-context))
  1014. (message "source-code block '%s' not found in this buffer" name))))
  1015. (defun org-babel-find-named-block (name)
  1016. "Find a named source-code block.
  1017. Return the location of the source block identified by source
  1018. NAME, or nil if no such block exists. Set match data according to
  1019. org-babel-named-src-block-regexp."
  1020. (save-excursion
  1021. (let ((case-fold-search t)
  1022. (regexp (org-babel-named-src-block-regexp-for-name name)) msg)
  1023. (goto-char (point-min))
  1024. (when (or (re-search-forward regexp nil t)
  1025. (re-search-backward regexp nil t))
  1026. (match-beginning 0)))))
  1027. (defun org-babel-src-block-names (&optional file)
  1028. "Returns the names of source blocks in FILE or the current buffer."
  1029. (save-excursion
  1030. (when file (find-file file)) (goto-char (point-min))
  1031. (let (names)
  1032. (while (re-search-forward org-babel-src-name-w-name-regexp nil t)
  1033. (setq names (cons (org-babel-clean-text-properties (match-string 3))
  1034. names)))
  1035. names)))
  1036. ;;;###autoload
  1037. (defun org-babel-goto-named-result (name)
  1038. "Go to a named result."
  1039. (interactive
  1040. (let ((completion-ignore-case t))
  1041. (list (org-icompleting-read "source-block name: "
  1042. (org-babel-result-names) nil t))))
  1043. (let ((point (org-babel-find-named-result name)))
  1044. (if point
  1045. ;; taken from `org-open-at-point'
  1046. (progn (goto-char point) (org-show-context))
  1047. (message "result '%s' not found in this buffer" name))))
  1048. (defun org-babel-find-named-result (name)
  1049. "Find a named result.
  1050. Return the location of the result named NAME in the current
  1051. buffer or nil if no such result exists."
  1052. (save-excursion
  1053. (goto-char (point-min))
  1054. (when (re-search-forward
  1055. (concat org-babel-result-regexp
  1056. "[ \t]" (regexp-quote name) "[ \t\n\f\v\r]") nil t)
  1057. (beginning-of-line 0) (point))))
  1058. (defun org-babel-result-names (&optional file)
  1059. "Returns the names of results in FILE or the current buffer."
  1060. (save-excursion
  1061. (when file (find-file file)) (goto-char (point-min))
  1062. (let (names)
  1063. (while (re-search-forward org-babel-result-w-name-regexp nil t)
  1064. (setq names (cons (org-babel-clean-text-properties (match-string 4))
  1065. names)))
  1066. names)))
  1067. ;;;###autoload
  1068. (defun org-babel-next-src-block (&optional arg)
  1069. "Jump to the next source block.
  1070. With optional prefix argument ARG, jump forward ARG many source blocks."
  1071. (interactive "P")
  1072. (when (looking-at org-babel-src-block-regexp) (forward-char 1))
  1073. (condition-case nil
  1074. (re-search-forward org-babel-src-block-regexp nil nil (or arg 1))
  1075. (error (error "No further code blocks")))
  1076. (goto-char (match-beginning 0)) (org-show-context))
  1077. ;;;###autoload
  1078. (defun org-babel-previous-src-block (&optional arg)
  1079. "Jump to the previous source block.
  1080. With optional prefix argument ARG, jump backward ARG many source blocks."
  1081. (interactive "P")
  1082. (condition-case nil
  1083. (re-search-backward org-babel-src-block-regexp nil nil (or arg 1))
  1084. (error (error "No previous code blocks")))
  1085. (goto-char (match-beginning 0)) (org-show-context))
  1086. (defvar org-babel-load-languages)
  1087. ;;;###autoload
  1088. (defun org-babel-mark-block ()
  1089. "Mark current src block"
  1090. (interactive)
  1091. ((lambda (head)
  1092. (when head
  1093. (save-excursion
  1094. (goto-char head)
  1095. (looking-at org-babel-src-block-regexp))
  1096. (push-mark (match-end 5) nil t)
  1097. (goto-char (match-beginning 5))))
  1098. (org-babel-where-is-src-block-head)))
  1099. (defun org-babel-demarcate-block (&optional arg)
  1100. "Wrap or split the code in the region or on the point.
  1101. When called from inside of a code block the current block is
  1102. split. When called from outside of a code block a new code block
  1103. is created. In both cases if the region is demarcated and if the
  1104. region is not active then the point is demarcated."
  1105. (interactive "P")
  1106. (let ((info (org-babel-get-src-block-info 'light))
  1107. (stars (concat (make-string (or (org-current-level) 1) ?*) " ")))
  1108. (if info
  1109. (mapc
  1110. (lambda (place)
  1111. (save-excursion
  1112. (goto-char place)
  1113. (let ((lang (nth 0 info))
  1114. (indent (make-string (nth 5 info) ? )))
  1115. (when (string-match "^[[:space:]]*$"
  1116. (buffer-substring (point-at-bol)
  1117. (point-at-eol)))
  1118. (delete-region (point-at-bol) (point-at-eol)))
  1119. (insert (concat (if (looking-at "^") "" "\n")
  1120. indent "#+end_src\n"
  1121. (if arg stars indent) "\n"
  1122. indent "#+begin_src " lang
  1123. (if (looking-at "[\n\r]") "" "\n")))))
  1124. (move-end-of-line 2))
  1125. (sort (if (region-active-p) (list (mark) (point)) (list (point))) #'>))
  1126. (let ((start (point))
  1127. (lang (org-icompleting-read "Lang: "
  1128. (mapcar (lambda (el) (symbol-name (car el)))
  1129. org-babel-load-languages)))
  1130. (body (delete-and-extract-region
  1131. (if (region-active-p) (mark) (point)) (point))))
  1132. (insert (concat (if (looking-at "^") "" "\n")
  1133. (if arg (concat stars "\n") "")
  1134. "#+begin_src " lang "\n"
  1135. body
  1136. (if (or (= (length body) 0)
  1137. (string-match "[\r\n]$" body)) "" "\n")
  1138. "#+end_src\n"))
  1139. (goto-char start) (move-end-of-line 1)))))
  1140. (defvar org-babel-lob-one-liner-regexp)
  1141. (defun org-babel-where-is-src-block-result (&optional insert info hash indent)
  1142. "Find where the current source block results begin.
  1143. Return the point at the beginning of the result of the current
  1144. source block. Specifically at the beginning of the results line.
  1145. If no result exists for this block then create a results line
  1146. following the source block."
  1147. (save-excursion
  1148. (let* ((on-lob-line (progn (beginning-of-line 1)
  1149. (looking-at org-babel-lob-one-liner-regexp)))
  1150. (name (if on-lob-line
  1151. (nth 0 (org-babel-lob-get-info))
  1152. (nth 4 (or info (org-babel-get-src-block-info)))))
  1153. (head (unless on-lob-line (org-babel-where-is-src-block-head)))
  1154. found beg end)
  1155. (when head (goto-char head))
  1156. (setq
  1157. found ;; was there a result (before we potentially insert one)
  1158. (or
  1159. (and
  1160. ;; named results:
  1161. ;; - return t if it is found, else return nil
  1162. ;; - if it does not need to be rebuilt, then don't set end
  1163. ;; - if it does need to be rebuilt then do set end
  1164. name (setq beg (org-babel-find-named-result name))
  1165. (prog1 beg
  1166. (when (and hash (not (string= hash (match-string 3))))
  1167. (goto-char beg) (setq end beg) ;; beginning of result
  1168. (forward-line 1)
  1169. (delete-region end (org-babel-result-end)) nil)))
  1170. (and
  1171. ;; unnamed results:
  1172. ;; - return t if it is found, else return nil
  1173. ;; - if it is found, and the hash doesn't match, delete and set end
  1174. (or on-lob-line (re-search-forward "^[ \t]*#\\+end_src" nil t))
  1175. (progn (end-of-line 1)
  1176. (if (eobp) (insert "\n") (forward-char 1))
  1177. (setq end (point))
  1178. (or (and (not name)
  1179. (progn ;; unnamed results line already exists
  1180. (re-search-forward "[^ \f\t\n\r\v]" nil t)
  1181. (beginning-of-line 1)
  1182. (looking-at
  1183. (concat org-babel-result-regexp "\n")))
  1184. (prog1 (point)
  1185. ;; must remove and rebuild if hash!=old-hash
  1186. (if (and hash (not (string= hash (match-string 3))))
  1187. (prog1 nil
  1188. (forward-line 1)
  1189. (delete-region
  1190. end (org-babel-result-end)))
  1191. (setq end nil)))))))))
  1192. (if (and insert end)
  1193. (progn
  1194. (goto-char end)
  1195. (unless beg
  1196. (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
  1197. (insert (concat
  1198. (if indent
  1199. (mapconcat
  1200. (lambda (el) " ")
  1201. (org-number-sequence 1 indent) "")
  1202. "")
  1203. "#+results"
  1204. (when hash (concat "["hash"]"))
  1205. ":"
  1206. (when name (concat " " name)) "\n"))
  1207. (unless beg (insert "\n") (backward-char))
  1208. (beginning-of-line 0)
  1209. (if hash (org-babel-hide-hash))
  1210. (point))
  1211. found))))
  1212. (defvar org-block-regexp)
  1213. (defun org-babel-read-result ()
  1214. "Read the result at `point' into emacs-lisp."
  1215. (let ((case-fold-search t) result-string)
  1216. (cond
  1217. ((org-at-table-p) (org-babel-read-table))
  1218. ((org-in-item-p) (org-babel-read-list))
  1219. ((looking-at org-bracket-link-regexp) (org-babel-read-link))
  1220. ((looking-at org-block-regexp) (org-babel-trim (match-string 4)))
  1221. ((looking-at "^[ \t]*: ")
  1222. (setq result-string
  1223. (org-babel-trim
  1224. (mapconcat (lambda (line)
  1225. (if (and (> (length line) 1)
  1226. (string-match "^[ \t]*: \\(.+\\)" line))
  1227. (match-string 1 line)
  1228. line))
  1229. (split-string
  1230. (buffer-substring
  1231. (point) (org-babel-result-end)) "[\r\n]+")
  1232. "\n")))
  1233. (or (org-babel-number-p result-string) result-string))
  1234. ((looking-at org-babel-result-regexp)
  1235. (save-excursion (forward-line 1) (org-babel-read-result))))))
  1236. (defun org-babel-read-table ()
  1237. "Read the table at `point' into emacs-lisp."
  1238. (mapcar (lambda (row)
  1239. (if (and (symbolp row) (equal row 'hline)) row
  1240. (mapcar #'org-babel-read row)))
  1241. (org-table-to-lisp)))
  1242. (defun org-babel-read-list ()
  1243. "Read the list at `point' into emacs-lisp."
  1244. (mapcar #'org-babel-read (cdr (org-list-parse-list))))
  1245. (defvar org-link-types-re)
  1246. (defun org-babel-read-link ()
  1247. "Read the link at `point' into emacs-lisp.
  1248. If the path of the link is a file path it is expanded using
  1249. `expand-file-name'."
  1250. (let* ((case-fold-search t)
  1251. (raw (and (looking-at org-bracket-link-regexp)
  1252. (org-babel-clean-text-properties (match-string 1))))
  1253. (type (and (string-match org-link-types-re raw)
  1254. (match-string 1 raw))))
  1255. (cond
  1256. ((not type) (expand-file-name raw))
  1257. ((string= type "file")
  1258. (and (string-match "file\\(.*\\):\\(.+\\)" raw)
  1259. (expand-file-name (match-string 2 raw))))
  1260. (t raw))))
  1261. (defun org-babel-insert-result
  1262. (result &optional result-params info hash indent lang)
  1263. "Insert RESULT into the current buffer.
  1264. By default RESULT is inserted after the end of the
  1265. current source block. With optional argument RESULT-PARAMS
  1266. controls insertion of results in the org-mode file.
  1267. RESULT-PARAMS can take the following values...
  1268. replace - (default option) insert results after the source block
  1269. replacing any previously inserted results
  1270. silent -- no results are inserted
  1271. file ---- the results are interpreted as a file path, and are
  1272. inserted into the buffer using the Org-mode file syntax
  1273. list ---- the results are interpreted as an Org-mode list.
  1274. raw ----- results are added directly to the Org-mode file. This
  1275. is a good option if you code block will output org-mode
  1276. formatted text.
  1277. org ----- similar in effect to raw, only the results are wrapped
  1278. in an org code block. Similar to the raw option, on
  1279. export the results will be interpreted as org-formatted
  1280. text, however by wrapping the results in an org code
  1281. block they can be replaced upon re-execution of the
  1282. code block.
  1283. html ---- results are added inside of a #+BEGIN_HTML block. This
  1284. is a good option if you code block will output html
  1285. formatted text.
  1286. latex --- results are added inside of a #+BEGIN_LATEX block.
  1287. This is a good option if you code block will output
  1288. latex formatted text.
  1289. code ---- the results are extracted in the syntax of the source
  1290. code of the language being evaluated and are added
  1291. inside of a #+BEGIN_SRC block with the source-code
  1292. language set appropriately. Note this relies on the
  1293. optional LANG argument."
  1294. (if (stringp result)
  1295. (progn
  1296. (setq result (org-babel-clean-text-properties result))
  1297. (when (member "file" result-params)
  1298. (setq result (org-babel-result-to-file result))))
  1299. (unless (listp result) (setq result (format "%S" result))))
  1300. (if (and result-params (member "silent" result-params))
  1301. (progn
  1302. (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
  1303. result)
  1304. (when (and (stringp result) ;; ensure results end in a newline
  1305. (> (length result) 0)
  1306. (not (or (string-equal (substring result -1) "\n")
  1307. (string-equal (substring result -1) "\r"))))
  1308. (setq result (concat result "\n")))
  1309. (save-excursion
  1310. (let ((existing-result (org-babel-where-is-src-block-result
  1311. t info hash indent))
  1312. (results-switches
  1313. (cdr (assoc :results_switches (nth 2 info))))
  1314. beg end)
  1315. (if (not existing-result)
  1316. (setq beg (point))
  1317. (goto-char existing-result)
  1318. (save-excursion
  1319. (re-search-forward "#" nil t)
  1320. (setq indent (- (current-column) 1)))
  1321. (forward-line 1)
  1322. (setq beg (point))
  1323. (cond
  1324. ((member "replace" result-params)
  1325. (delete-region (point) (org-babel-result-end)))
  1326. ((member "append" result-params)
  1327. (goto-char (org-babel-result-end)) (setq beg (point-marker)))
  1328. ((member "prepend" result-params)))) ; already there
  1329. (setq results-switches
  1330. (if results-switches (concat " " results-switches) ""))
  1331. ;; insert results based on type
  1332. (cond
  1333. ;; do nothing for an empty result
  1334. ((= (length result) 0))
  1335. ;; insert a list if preferred
  1336. ((member "list" result-params)
  1337. (insert
  1338. (org-babel-trim
  1339. (org-list-to-generic (cons 'unordered
  1340. (if (listp result) result (list result)))
  1341. '(:splicep nil :istart "- " :iend "\n")))))
  1342. ;; assume the result is a table if it's not a string
  1343. ((not (stringp result))
  1344. (goto-char beg)
  1345. (insert (concat (orgtbl-to-orgtbl
  1346. (if (or (eq 'hline (car result))
  1347. (and (listp (car result))
  1348. (listp (cdr (car result)))))
  1349. result (list result))
  1350. '(:fmt (lambda (cell) (format "%s" cell)))) "\n"))
  1351. (goto-char beg) (when (org-at-table-p) (org-table-align)))
  1352. ((member "file" result-params)
  1353. (insert result))
  1354. (t (goto-char beg) (insert result)))
  1355. (when (listp result) (goto-char (org-table-end)))
  1356. (setq end (point-marker))
  1357. ;; possibly wrap result
  1358. (flet ((wrap (start finish)
  1359. (goto-char beg) (insert start)
  1360. (goto-char end) (insert finish)
  1361. (setq end (point-marker))))
  1362. (cond
  1363. ((member "html" result-params)
  1364. (wrap "#+BEGIN_HTML\n" "#+END_HTML"))
  1365. ((member "latex" result-params)
  1366. (wrap "#+BEGIN_LaTeX\n" "#+END_LaTeX"))
  1367. ((member "code" result-params)
  1368. (wrap (format "#+BEGIN_SRC %s%s\n" (or lang "none") results-switches)
  1369. "#+END_SRC"))
  1370. ((member "org" result-params)
  1371. (wrap "#+BEGIN_ORG\n" "#+END_ORG"))
  1372. ((member "raw" result-params)
  1373. (goto-char beg) (if (org-at-table-p) (org-cycle)))
  1374. ((member "wrap" result-params)
  1375. (when (and (stringp result) (not (member "file" result-params)))
  1376. (org-babel-examplize-region beg end results-switches))
  1377. (wrap "#+BEGIN_RESULT\n" "#+END_RESULT"))
  1378. ((and (stringp result) (not (member "file" result-params)))
  1379. (org-babel-examplize-region beg end results-switches)
  1380. (setq end (point)))))
  1381. ;; possibly indent the results to match the #+results line
  1382. (when (and indent (> indent 0)
  1383. ;; in this case `table-align' does the work for us
  1384. (not (and (listp result)
  1385. (member "append" result-params))))
  1386. (indent-rigidly beg end indent))))
  1387. (if (= (length result) 0)
  1388. (if (member "value" result-params)
  1389. (message "Code block returned no value.")
  1390. (message "Code block produced no output."))
  1391. (message "Code block evaluation complete."))))
  1392. (defun org-babel-remove-result (&optional info)
  1393. "Remove the result of the current source block."
  1394. (interactive)
  1395. (let ((location (org-babel-where-is-src-block-result nil info)) start)
  1396. (when location
  1397. (save-excursion
  1398. (goto-char location) (setq start (point)) (forward-line 1)
  1399. (delete-region start (org-babel-result-end))))))
  1400. (defun org-babel-result-end ()
  1401. "Return the point at the end of the current set of results"
  1402. (save-excursion
  1403. (cond
  1404. ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
  1405. ((org-in-item-p) (- (org-list-bottom-point) 1))
  1406. (t
  1407. (let ((case-fold-search t)
  1408. (blocks-re (regexp-opt
  1409. (list "latex" "html" "example" "src" "result"))))
  1410. (if (looking-at (concat "[ \t]*#\\+begin_" blocks-re))
  1411. (re-search-forward (concat "[ \t]*#\\+end_" blocks-re) nil t)
  1412. (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
  1413. (forward-line 1))))
  1414. (point)))))
  1415. (defun org-babel-result-to-file (result)
  1416. "Convert RESULT into an `org-mode' link.
  1417. If the `default-directory' is different from the containing
  1418. file's directory then expand relative links."
  1419. (format
  1420. "[[file:%s]]"
  1421. (if (and default-directory
  1422. buffer-file-name
  1423. (not (string= (expand-file-name default-directory)
  1424. (expand-file-name
  1425. (file-name-directory buffer-file-name)))))
  1426. (expand-file-name result default-directory)
  1427. result)))
  1428. (defun org-babel-examplize-region (beg end &optional results-switches)
  1429. "Comment out region using the ': ' org example quote."
  1430. (interactive "*r")
  1431. (let ((size (count-lines beg end)))
  1432. (save-excursion
  1433. (cond ((= size 0)) ; do nothing for an empty result
  1434. ((< size org-babel-min-lines-for-block-output)
  1435. (goto-char beg)
  1436. (dotimes (n size)
  1437. (beginning-of-line 1) (insert ": ") (forward-line 1)))
  1438. (t
  1439. (goto-char beg)
  1440. (insert (if results-switches
  1441. (format "#+begin_example%s\n" results-switches)
  1442. "#+begin_example\n"))
  1443. (if (markerp end) (goto-char end) (forward-char (- end beg)))
  1444. (insert "#+end_example\n"))))))
  1445. (defun org-babel-update-block-body (new-body)
  1446. "Update the body of the current code block to NEW-BODY."
  1447. (if (not (org-babel-where-is-src-block-head))
  1448. (error "not in source block")
  1449. (save-match-data
  1450. (replace-match (concat (org-babel-trim new-body) "\n") nil nil nil 5))
  1451. (indent-rigidly (match-beginning 5) (match-end 5) 2)))
  1452. (defun org-babel-merge-params (&rest plists)
  1453. "Combine all parameter association lists in PLISTS.
  1454. Later elements of PLISTS override the values of previous element.
  1455. This takes into account some special considerations for certain
  1456. parameters when merging lists."
  1457. (let ((results-exclusive-groups
  1458. '(("file" "list" "vector" "table" "scalar" "raw" "org"
  1459. "html" "latex" "code" "pp" "wrap")
  1460. ("replace" "silent" "append" "prepend")
  1461. ("output" "value")))
  1462. (exports-exclusive-groups
  1463. '(("code" "results" "both" "none")))
  1464. params results exports tangle noweb cache vars shebang comments)
  1465. (flet ((e-merge (exclusive-groups &rest result-params)
  1466. ;; maintain exclusivity of mutually exclusive parameters
  1467. (let (output)
  1468. (mapc (lambda (new-params)
  1469. (mapc (lambda (new-param)
  1470. (mapc (lambda (exclusive-group)
  1471. (when (member new-param exclusive-group)
  1472. (mapcar (lambda (excluded-param)
  1473. (setq output
  1474. (delete
  1475. excluded-param
  1476. output)))
  1477. exclusive-group)))
  1478. exclusive-groups)
  1479. (setq output (org-uniquify
  1480. (cons new-param output))))
  1481. new-params))
  1482. result-params)
  1483. output)))
  1484. (mapc
  1485. (lambda (plist)
  1486. (mapc
  1487. (lambda (pair)
  1488. (case (car pair)
  1489. (:var
  1490. (let ((name (if (listp (cdr pair))
  1491. (cadr pair)
  1492. (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
  1493. (cdr pair))
  1494. (intern (match-string 1 (cdr pair)))))))
  1495. (when name
  1496. (setq vars
  1497. (cons (cons name pair)
  1498. (if (member name (mapcar #'car vars))
  1499. (delq nil
  1500. (mapcar
  1501. (lambda (p) (unless (equal (car p) name) p))
  1502. vars))
  1503. vars))))))
  1504. (:results
  1505. (setq results (e-merge results-exclusive-groups
  1506. results (split-string (cdr pair)))))
  1507. (:file
  1508. (when (cdr pair)
  1509. (setq results (e-merge results-exclusive-groups
  1510. results '("file")))
  1511. (unless (or (member "both" exports)
  1512. (member "none" exports)
  1513. (member "code" exports))
  1514. (setq exports (e-merge exports-exclusive-groups
  1515. exports '("results"))))
  1516. (setq params (cons pair (assq-delete-all (car pair) params)))))
  1517. (:exports
  1518. (setq exports (e-merge exports-exclusive-groups
  1519. exports (split-string (cdr pair)))))
  1520. (:tangle ;; take the latest -- always overwrite
  1521. (setq tangle (or (list (cdr pair)) tangle)))
  1522. (:noweb
  1523. (setq noweb (e-merge '(("yes" "no" "tangle")) noweb
  1524. (split-string (or (cdr pair) "")))))
  1525. (:cache
  1526. (setq cache (e-merge '(("yes" "no")) cache
  1527. (split-string (or (cdr pair) "")))))
  1528. (:shebang ;; take the latest -- always overwrite
  1529. (setq shebang (or (list (cdr pair)) shebang)))
  1530. (:comments
  1531. (setq comments (e-merge '(("yes" "no")) comments
  1532. (split-string (or (cdr pair) "")))))
  1533. (t ;; replace: this covers e.g. :session
  1534. (setq params (cons pair (assq-delete-all (car pair) params))))))
  1535. plist))
  1536. plists))
  1537. (while vars (setq params (cons (cons :var (cddr (pop vars))) params)))
  1538. (cons (cons :comments (mapconcat 'identity comments " "))
  1539. (cons (cons :shebang (mapconcat 'identity shebang " "))
  1540. (cons (cons :cache (mapconcat 'identity cache " "))
  1541. (cons (cons :noweb (mapconcat 'identity noweb " "))
  1542. (cons (cons :tangle (mapconcat 'identity tangle " "))
  1543. (cons (cons :exports
  1544. (mapconcat 'identity exports " "))
  1545. (cons
  1546. (cons :results
  1547. (mapconcat 'identity results " "))
  1548. params)))))))))
  1549. (defun org-babel-expand-noweb-references (&optional info parent-buffer)
  1550. "Expand Noweb references in the body of the current source code block.
  1551. For example the following reference would be replaced with the
  1552. body of the source-code block named 'example-block'.
  1553. <<example-block>>
  1554. Note that any text preceding the <<foo>> construct on a line will
  1555. be interposed between the lines of the replacement text. So for
  1556. example if <<foo>> is placed behind a comment, then the entire
  1557. replacement text will also be commented.
  1558. This function must be called from inside of the buffer containing
  1559. the source-code block which holds BODY.
  1560. In addition the following syntax can be used to insert the
  1561. results of evaluating the source-code block named 'example-block'.
  1562. <<example-block()>>
  1563. Any optional arguments can be passed to example-block by placing
  1564. the arguments inside the parenthesis following the convention
  1565. defined by `org-babel-lob'. For example
  1566. <<example-block(a=9)>>
  1567. would set the value of argument \"a\" equal to \"9\". Note that
  1568. these arguments are not evaluated in the current source-code
  1569. block but are passed literally to the \"example-block\"."
  1570. (let* ((parent-buffer (or parent-buffer (current-buffer)))
  1571. (info (or info (org-babel-get-src-block-info)))
  1572. (lang (nth 0 info))
  1573. (body (nth 1 info))
  1574. (new-body "") index source-name evaluate prefix)
  1575. (flet ((nb-add (text)
  1576. (setq new-body (concat new-body text))))
  1577. (with-temp-buffer
  1578. (insert body) (goto-char (point-min))
  1579. (setq index (point))
  1580. (while (and (re-search-forward "<<\\(.+?\\)>>" nil t))
  1581. (save-match-data (setf source-name (match-string 1)))
  1582. (save-match-data (setq evaluate (string-match "\(.*\)" source-name)))
  1583. (save-match-data
  1584. (setq prefix
  1585. (buffer-substring (match-beginning 0)
  1586. (save-excursion
  1587. (beginning-of-line 1) (point)))))
  1588. ;; add interval to new-body (removing noweb reference)
  1589. (goto-char (match-beginning 0))
  1590. (nb-add (buffer-substring index (point)))
  1591. (goto-char (match-end 0))
  1592. (setq index (point))
  1593. (nb-add (with-current-buffer parent-buffer
  1594. (mapconcat ;; interpose PREFIX between every line
  1595. #'identity
  1596. (split-string
  1597. (if evaluate
  1598. (let ((raw (org-babel-ref-resolve source-name)))
  1599. (if (stringp raw) raw (format "%S" raw)))
  1600. (save-restriction
  1601. (widen)
  1602. (let ((point (org-babel-find-named-block
  1603. source-name)))
  1604. (if point
  1605. (save-excursion
  1606. (goto-char point)
  1607. (org-babel-trim
  1608. (org-babel-expand-noweb-references
  1609. (org-babel-get-src-block-info))))
  1610. ;; optionally raise an error if named
  1611. ;; source-block doesn't exist
  1612. (if (member lang org-babel-noweb-error-langs)
  1613. (error "%s"
  1614. (concat
  1615. "<<" source-name ">> "
  1616. "could not be resolved (see "
  1617. "`org-babel-noweb-error-langs')"))
  1618. "")))))
  1619. "[\n\r]") (concat "\n" prefix)))))
  1620. (nb-add (buffer-substring index (point-max)))))
  1621. new-body))
  1622. (defun org-babel-clean-text-properties (text)
  1623. "Strip all properties from text return."
  1624. (when text
  1625. (set-text-properties 0 (length text) nil text) text))
  1626. (defun org-babel-strip-protective-commas (body)
  1627. "Strip protective commas from bodies of source blocks."
  1628. (replace-regexp-in-string "^,#" "#" body))
  1629. (defun org-babel-script-escape (str)
  1630. "Safely convert tables into elisp lists."
  1631. (let (in-single in-double out)
  1632. (org-babel-read
  1633. (if (and (stringp str) (string-match "^\\[.+\\]$" str))
  1634. (org-babel-read
  1635. (concat
  1636. "'"
  1637. (progn
  1638. (mapc
  1639. (lambda (ch)
  1640. (setq
  1641. out
  1642. (case ch
  1643. (91 (if (or in-double in-single) ; [
  1644. (cons 91 out)
  1645. (cons 40 out)))
  1646. (93 (if (or in-double in-single) ; ]
  1647. (cons 93 out)
  1648. (cons 41 out)))
  1649. (44 (if (or in-double in-single) (cons 44 out) out)) ; ,
  1650. (39 (if in-double ; '
  1651. (cons 39 out)
  1652. (setq in-single (not in-single)) (cons 34 out)))
  1653. (34 (if in-single ; "
  1654. (append (list 34 32) out)
  1655. (setq in-double (not in-double)) (cons 34 out)))
  1656. (t (cons ch out)))))
  1657. (string-to-list str))
  1658. (apply #'string (reverse out)))))
  1659. str))))
  1660. (defun org-babel-read (cell)
  1661. "Convert the string value of CELL to a number if appropriate.
  1662. Otherwise if cell looks like lisp (meaning it starts with a
  1663. \"(\" or a \"'\") then read it as lisp, otherwise return it
  1664. unmodified as a string.
  1665. This is taken almost directly from `org-read-prop'."
  1666. (if (and (stringp cell) (not (equal cell "")))
  1667. (or (org-babel-number-p cell)
  1668. (if (or (equal "(" (substring cell 0 1))
  1669. (equal "'" (substring cell 0 1))
  1670. (equal "`" (substring cell 0 1)))
  1671. (eval (read cell))
  1672. (progn (set-text-properties 0 (length cell) nil cell) cell)))
  1673. cell))
  1674. (defun org-babel-number-p (string)
  1675. "If STRING represents a number return it's value."
  1676. (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string)
  1677. (= (length (substring string (match-beginning 0)
  1678. (match-end 0)))
  1679. (length string)))
  1680. (string-to-number string)))
  1681. (defun org-babel-import-elisp-from-file (file-name &optional separator)
  1682. "Read the results located at FILE-NAME into an elisp table.
  1683. If the table is trivial, then return it as a scalar."
  1684. (let (result)
  1685. (save-window-excursion
  1686. (with-temp-buffer
  1687. (condition-case nil
  1688. (progn
  1689. (org-table-import file-name separator)
  1690. (delete-file file-name)
  1691. (setq result (mapcar (lambda (row)
  1692. (mapcar #'org-babel-string-read row))
  1693. (org-table-to-lisp))))
  1694. (error nil)))
  1695. (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
  1696. (if (consp (car result))
  1697. (if (null (cdr (car result)))
  1698. (caar result)
  1699. result)
  1700. (car result))
  1701. result))))
  1702. (defun org-babel-string-read (cell)
  1703. "Strip nested \"s from around strings."
  1704. (org-babel-read (or (and (stringp cell)
  1705. (string-match "\\\"\\(.+\\)\\\"" cell)
  1706. (match-string 1 cell))
  1707. cell)))
  1708. (defun org-babel-reverse-string (string)
  1709. "Return the reverse of STRING."
  1710. (apply 'string (reverse (string-to-list string))))
  1711. (defun org-babel-chomp (string &optional regexp)
  1712. "Strip trailing spaces and carriage returns from STRING.
  1713. Default regexp used is \"[ \f\t\n\r\v]\" but can be
  1714. overwritten by specifying a regexp as a second argument."
  1715. (let ((regexp (or regexp "[ \f\t\n\r\v]")))
  1716. (while (and (> (length string) 0)
  1717. (string-match regexp (substring string -1)))
  1718. (setq string (substring string 0 -1)))
  1719. string))
  1720. (defun org-babel-trim (string &optional regexp)
  1721. "Strip leading and trailing spaces and carriage returns from STRING.
  1722. Like `org-babel-chomp' only it runs on both the front and back
  1723. of the string."
  1724. (org-babel-chomp (org-babel-reverse-string
  1725. (org-babel-chomp (org-babel-reverse-string string) regexp))
  1726. regexp))
  1727. (defvar org-babel-org-babel-call-process-region-original nil)
  1728. (defun org-babel-tramp-handle-call-process-region
  1729. (start end program &optional delete buffer display &rest args)
  1730. "Use tramp to handle call-process-region.
  1731. Fixes a bug in `tramp-handle-call-process-region'."
  1732. (if (and (featurep 'tramp) (file-remote-p default-directory))
  1733. (let ((tmpfile (tramp-compat-make-temp-file "")))
  1734. (write-region start end tmpfile)
  1735. (when delete (delete-region start end))
  1736. (unwind-protect
  1737. ;; (apply 'call-process program tmpfile buffer display args)
  1738. ;; bug in tramp
  1739. (apply 'process-file program tmpfile buffer display args)
  1740. (delete-file tmpfile)))
  1741. ;; org-babel-call-process-region-original is the original emacs
  1742. ;; definition. It is in scope from the let binding in
  1743. ;; org-babel-execute-src-block
  1744. (apply org-babel-call-process-region-original
  1745. start end program delete buffer display args)))
  1746. (defun org-babel-local-file-name (file)
  1747. "Return the local name component of FILE."
  1748. (if (file-remote-p file)
  1749. (let (localname)
  1750. (with-parsed-tramp-file-name file nil
  1751. localname))
  1752. file))
  1753. (defun org-babel-process-file-name (name &optional no-quote-p)
  1754. "Prepare NAME to be used in an external process.
  1755. If NAME specifies a remote location, the remote portion of the
  1756. name is removed, since in that case the process will be executing
  1757. remotely. The file name is then processed by
  1758. `expand-file-name'. Unless second argument NO-QUOTE-P is non-nil,
  1759. the file name is additionally processed by
  1760. `shell-quote-argument'"
  1761. ((lambda (f) (if no-quote-p f (shell-quote-argument f)))
  1762. (expand-file-name (org-babel-local-file-name name))))
  1763. (defvar org-babel-temporary-directory)
  1764. (unless (or noninteractive (boundp 'org-babel-temporary-directory))
  1765. (defvar org-babel-temporary-directory
  1766. (or (and (boundp 'org-babel-temporary-directory)
  1767. (file-exists-p org-babel-temporary-directory)
  1768. org-babel-temporary-directory)
  1769. (make-temp-file "babel-" t))
  1770. "Directory to hold temporary files created to execute code blocks.
  1771. Used by `org-babel-temp-file'. This directory will be removed on
  1772. Emacs shutdown."))
  1773. (defun org-babel-temp-file (prefix &optional suffix)
  1774. "Create a temporary file in the `org-babel-temporary-directory'.
  1775. Passes PREFIX and SUFFIX directly to `make-temp-file' with the
  1776. value of `temporary-file-directory' temporarily set to the value
  1777. of `org-babel-temporary-directory'."
  1778. (if (file-remote-p default-directory)
  1779. (make-temp-file
  1780. (concat (file-remote-p default-directory)
  1781. (expand-file-name
  1782. prefix temporary-file-directory)
  1783. nil suffix))
  1784. (let ((temporary-file-directory
  1785. (or (and (file-exists-p org-babel-temporary-directory)
  1786. org-babel-temporary-directory)
  1787. temporary-file-directory)))
  1788. (make-temp-file prefix nil suffix))))
  1789. (defun org-babel-remove-temporary-directory ()
  1790. "Remove `org-babel-temporary-directory' on Emacs shutdown."
  1791. (when (and (boundp 'org-babel-temporary-directory)
  1792. (file-exists-p org-babel-temporary-directory))
  1793. ;; taken from `delete-directory' in files.el
  1794. (condition-case nil
  1795. (progn
  1796. (mapc (lambda (file)
  1797. ;; This test is equivalent to
  1798. ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
  1799. ;; but more efficient
  1800. (if (eq t (car (file-attributes file)))
  1801. (delete-directory file)
  1802. (delete-file file)))
  1803. ;; We do not want to delete "." and "..".
  1804. (directory-files org-babel-temporary-directory 'full
  1805. "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
  1806. (delete-directory org-babel-temporary-directory))
  1807. (error
  1808. (message "Failed to remove temporary Org-babel directory %s"
  1809. org-babel-temporary-directory)))))
  1810. (add-hook 'kill-emacs-hook 'org-babel-remove-temporary-directory)
  1811. (provide 'ob)
  1812. ;; arch-tag: 01a7ebee-06c5-4ee4-a709-e660d28c0af1
  1813. ;;; ob.el ends here