ob.el 73 KB

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