ob.el 74 KB

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