ob.el 72 KB

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