ob.el 74 KB

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