ob.el 80 KB

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