ob.el 77 KB

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