ob.el 73 KB

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