ob.el 73 KB

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