ob-core.el 100 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638
  1. ;;; ob-core.el --- working with code blocks in org-mode
  2. ;; Copyright (C) 2009-2012 Free Software Foundation, Inc.
  3. ;; Authors: Eric Schulte
  4. ;; Dan Davison
  5. ;; Keywords: literate programming, reproducible research
  6. ;; Homepage: http://orgmode.org
  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. ;;; Code:
  19. (eval-when-compile
  20. (require 'cl))
  21. (require 'ob-eval)
  22. (require 'org-macs)
  23. (require 'org-compat)
  24. (defconst org-babel-exeext
  25. (if (memq system-type '(windows-nt cygwin))
  26. ".exe"
  27. nil))
  28. (defvar org-babel-call-process-region-original)
  29. (defvar org-src-lang-modes)
  30. (defvar org-babel-library-of-babel)
  31. (declare-function show-all "outline" ())
  32. (declare-function org-reduce "org" (CL-FUNC CL-SEQ &rest CL-KEYS))
  33. (declare-function org-mark-ring-push "org" (&optional pos buffer))
  34. (declare-function tramp-compat-make-temp-file "tramp-compat"
  35. (filename &optional dir-flag))
  36. (declare-function tramp-dissect-file-name "tramp" (name &optional nodefault))
  37. (declare-function tramp-file-name-user "tramp" (vec))
  38. (declare-function tramp-file-name-host "tramp" (vec))
  39. (declare-function with-parsed-tramp-file-name "tramp" (filename var &rest body))
  40. (declare-function org-icompleting-read "org" (&rest args))
  41. (declare-function org-edit-src-code "org-src"
  42. (&optional context code edit-buffer-name quietp))
  43. (declare-function org-edit-src-exit "org-src" (&optional context))
  44. (declare-function org-open-at-point "org" (&optional in-emacs reference-buffer))
  45. (declare-function org-save-outline-visibility "org-macs" (use-markers &rest body))
  46. (declare-function org-outline-overlay-data "org" (&optional use-markers))
  47. (declare-function org-set-outline-overlay-data "org" (data))
  48. (declare-function org-narrow-to-subtree "org" ())
  49. (declare-function org-split-string "org" (string &optional separators))
  50. (declare-function org-entry-get "org"
  51. (pom property &optional inherit literal-nil))
  52. (declare-function org-make-options-regexp "org" (kwds &optional extra))
  53. (declare-function org-do-remove-indentation "org" (&optional n))
  54. (declare-function org-next-block "org" (arg &optional backward block-regexp))
  55. (declare-function org-previous-block "org" (arg &optional block-regexp))
  56. (declare-function org-show-context "org" (&optional key))
  57. (declare-function org-at-table-p "org" (&optional table-type))
  58. (declare-function org-cycle "org" (&optional arg))
  59. (declare-function org-uniquify "org" (list))
  60. (declare-function org-current-level "org" ())
  61. (declare-function org-table-import "org-table" (file arg))
  62. (declare-function org-add-hook "org-compat"
  63. (hook function &optional append local))
  64. (declare-function org-table-align "org-table" ())
  65. (declare-function org-table-end "org-table" (&optional table-type))
  66. (declare-function orgtbl-to-generic "org-table" (table params))
  67. (declare-function orgtbl-to-orgtbl "org-table" (table params))
  68. (declare-function org-babel-tangle-comment-links "ob-tangle" (&optional info))
  69. (declare-function org-babel-lob-get-info "ob-lob" nil)
  70. (declare-function org-babel-ref-split-args "ob-ref" (arg-string))
  71. (declare-function org-babel-ref-parse "ob-ref" (assignment))
  72. (declare-function org-babel-ref-resolve "ob-ref" (ref))
  73. (declare-function org-babel-ref-goto-headline-id "ob-ref" (id))
  74. (declare-function org-babel-ref-headline-body "ob-ref" ())
  75. (declare-function org-babel-lob-execute-maybe "ob-lob" ())
  76. (declare-function org-number-sequence "org-compat" (from &optional to inc))
  77. (declare-function org-at-item-p "org-list" ())
  78. (declare-function org-list-parse-list "org-list" (&optional delete))
  79. (declare-function org-list-to-generic "org-list" (LIST PARAMS))
  80. (declare-function org-list-struct "org-list" ())
  81. (declare-function org-list-prevs-alist "org-list" (struct))
  82. (declare-function org-list-get-list-end "org-list" (item struct prevs))
  83. (declare-function org-remove-if "org" (predicate seq))
  84. (declare-function org-completing-read "org" (&rest args))
  85. (declare-function org-escape-code-in-region "org-src" (beg end))
  86. (declare-function org-unescape-code-in-string "org-src" (s))
  87. (declare-function org-table-to-lisp "org-table" (&optional txt))
  88. (declare-function org-reverse-string "org" (string))
  89. (defgroup org-babel nil
  90. "Code block evaluation and management in `org-mode' documents."
  91. :tag "Babel"
  92. :group 'org)
  93. (defcustom org-confirm-babel-evaluate t
  94. "Confirm before evaluation.
  95. Require confirmation before interactively evaluating code
  96. blocks in Org-mode buffers. The default value of this variable
  97. is t, meaning confirmation is required for any code block
  98. evaluation. This variable can be set to nil to inhibit any
  99. future confirmation requests. This variable can also be set to a
  100. function which takes two arguments the language of the code block
  101. and the body of the code block. Such a function should then
  102. return a non-nil value if the user should be prompted for
  103. execution or nil if no prompt is required.
  104. Warning: Disabling confirmation may result in accidental
  105. evaluation of potentially harmful code. It may be advisable
  106. remove code block execution from C-c C-c as further protection
  107. against accidental code block evaluation. The
  108. `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
  109. remove code block execution from the C-c C-c keybinding."
  110. :group 'org-babel
  111. :version "24.1"
  112. :type '(choice boolean function))
  113. ;; don't allow this variable to be changed through file settings
  114. (put 'org-confirm-babel-evaluate 'safe-local-variable (lambda (x) (eq x t)))
  115. (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
  116. "Remove code block evaluation from the C-c C-c key binding."
  117. :group 'org-babel
  118. :version "24.1"
  119. :type 'boolean)
  120. (defcustom org-babel-results-keyword "RESULTS"
  121. "Keyword used to name results generated by code blocks.
  122. Should be either RESULTS or NAME however any capitalization may
  123. be used."
  124. :group 'org-babel
  125. :type 'string)
  126. (defcustom org-babel-noweb-wrap-start "<<"
  127. "String used to begin a noweb reference in a code block.
  128. See also `org-babel-noweb-wrap-end'."
  129. :group 'org-babel
  130. :type 'string)
  131. (defcustom org-babel-noweb-wrap-end ">>"
  132. "String used to end a noweb reference in a code block.
  133. See also `org-babel-noweb-wrap-start'."
  134. :group 'org-babel
  135. :type 'string)
  136. (defun org-babel-noweb-wrap (&optional regexp)
  137. (concat org-babel-noweb-wrap-start
  138. (or regexp "\\([^ \t\n].+?[^ \t]\\|[^ \t\n]\\)")
  139. org-babel-noweb-wrap-end))
  140. (defvar org-babel-src-name-regexp
  141. "^[ \t]*#\\+name:[ \t]*"
  142. "Regular expression used to match a source name line.")
  143. (defvar org-babel-multi-line-header-regexp
  144. "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
  145. "Regular expression used to match multi-line header arguments.")
  146. (defvar org-babel-src-name-w-name-regexp
  147. (concat org-babel-src-name-regexp
  148. "\\("
  149. org-babel-multi-line-header-regexp
  150. "\\)*"
  151. "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)")
  152. "Regular expression matching source name lines with a name.")
  153. (defvar org-babel-src-block-regexp
  154. (concat
  155. ;; (1) indentation (2) lang
  156. "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
  157. ;; (3) switches
  158. "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
  159. ;; (4) header arguments
  160. "\\([^\n]*\\)\n"
  161. ;; (5) body
  162. "\\([^\000]*?\n\\)?[ \t]*#\\+end_src")
  163. "Regexp used to identify code blocks.")
  164. (defvar org-babel-inline-src-block-regexp
  165. (concat
  166. ;; (1) replacement target (2) lang
  167. "\\(?:^\\|[^-[:alnum:]]\\)\\(src_\\([^ \f\t\n\r\v]+\\)"
  168. ;; (3,4) (unused, headers)
  169. "\\(\\|\\[\\(.*?\\)\\]\\)"
  170. ;; (5) body
  171. "{\\([^\f\n\r\v]+?\\)}\\)")
  172. "Regexp used to identify inline src-blocks.")
  173. (defun org-babel-get-header (params key &optional others)
  174. "Select only header argument of type KEY from a list.
  175. Optional argument OTHERS indicates that only the header that do
  176. not match KEY should be returned."
  177. (delq nil
  178. (mapcar
  179. (lambda (p) (when (funcall (if others #'not #'identity) (eq (car p) key)) p))
  180. params)))
  181. (defun org-babel-get-inline-src-block-matches()
  182. "Set match data if within body of an inline source block.
  183. Returns non-nil if match-data set"
  184. (let ((src-at-0-p (save-excursion
  185. (beginning-of-line 1)
  186. (string= "src" (thing-at-point 'word))))
  187. (first-line-p (= 1 (line-number-at-pos)))
  188. (orig (point)))
  189. (let ((search-for (cond ((and src-at-0-p first-line-p "src_"))
  190. (first-line-p "[[:punct:] \t]src_")
  191. (t "[[:punct:] \f\t\n\r\v]src_")))
  192. (lower-limit (if first-line-p
  193. nil
  194. (- (point-at-bol) 1))))
  195. (save-excursion
  196. (when (or (and src-at-0-p (bobp))
  197. (and (re-search-forward "}" (point-at-eol) t)
  198. (re-search-backward search-for lower-limit t)
  199. (> orig (point))))
  200. (when (looking-at org-babel-inline-src-block-regexp)
  201. t ))))))
  202. (defvar org-babel-inline-lob-one-liner-regexp)
  203. (defun org-babel-get-lob-one-liner-matches()
  204. "Set match data if on line of an lob one liner.
  205. Returns non-nil if match-data set"
  206. (save-excursion
  207. (unless (= (point) (point-at-bol)) ;; move before inline block
  208. (re-search-backward "[ \f\t\n\r\v]" nil t))
  209. (if (looking-at org-babel-inline-lob-one-liner-regexp)
  210. t
  211. nil)))
  212. (defun org-babel-get-src-block-info (&optional light)
  213. "Get information on the current source block.
  214. Optional argument LIGHT does not resolve remote variable
  215. references; a process which could likely result in the execution
  216. of other code blocks.
  217. Returns a list
  218. (language body header-arguments-alist switches name indent)."
  219. (let ((case-fold-search t) head info name indent)
  220. ;; full code block
  221. (if (setq head (org-babel-where-is-src-block-head))
  222. (save-excursion
  223. (goto-char head)
  224. (setq info (org-babel-parse-src-block-match))
  225. (setq indent (car (last info)))
  226. (setq info (butlast info))
  227. (while (and (forward-line -1)
  228. (looking-at org-babel-multi-line-header-regexp))
  229. (setf (nth 2 info)
  230. (org-babel-merge-params
  231. (nth 2 info)
  232. (org-babel-parse-header-arguments (match-string 1)))))
  233. (when (looking-at org-babel-src-name-w-name-regexp)
  234. (setq name (org-no-properties (match-string 3)))
  235. (when (and (match-string 5) (> (length (match-string 5)) 0))
  236. (setf (nth 2 info) ;; merge functional-syntax vars and header-args
  237. (org-babel-merge-params
  238. (mapcar
  239. (lambda (ref) (cons :var ref))
  240. (mapcar
  241. (lambda (var) ;; check that each variable is initialized
  242. (if (string-match ".+=.+" var)
  243. var
  244. (error
  245. "variable \"%s\"%s must be assigned a default value"
  246. var (if name (format " in block \"%s\"" name) ""))))
  247. (org-babel-ref-split-args (match-string 5))))
  248. (nth 2 info))))))
  249. ;; inline source block
  250. (when (org-babel-get-inline-src-block-matches)
  251. (setq info (org-babel-parse-inline-src-block-match))))
  252. ;; resolve variable references and add summary parameters
  253. (when (and info (not light))
  254. (setf (nth 2 info) (org-babel-process-params (nth 2 info))))
  255. (when info (append info (list name indent)))))
  256. (defvar org-current-export-file) ; dynamically bound
  257. (defun org-babel-confirm-evaluate (info)
  258. "Confirm evaluation of the code block INFO.
  259. This behavior can be suppressed by setting the value of
  260. `org-confirm-babel-evaluate' to nil, in which case all future
  261. interactive code block evaluations will proceed without any
  262. confirmation from the user.
  263. Note disabling confirmation may result in accidental evaluation
  264. of potentially harmful code."
  265. (let* ((eval (or (cdr (assoc :eval (nth 2 info)))
  266. (when (assoc :noeval (nth 2 info)) "no")))
  267. (query (cond ((equal eval "query") t)
  268. ((and (boundp 'org-current-export-file)
  269. org-current-export-file
  270. (equal eval "query-export")) t)
  271. ((functionp org-confirm-babel-evaluate)
  272. (funcall org-confirm-babel-evaluate
  273. (nth 0 info) (nth 1 info)))
  274. (t org-confirm-babel-evaluate))))
  275. (if (or (equal eval "never") (equal eval "no")
  276. (and (boundp 'org-current-export-file)
  277. org-current-export-file
  278. (or (equal eval "no-export")
  279. (equal eval "never-export")))
  280. (and query
  281. (not (yes-or-no-p
  282. (format "Evaluate this%scode block%son your system? "
  283. (if info (format " %s " (nth 0 info)) " ")
  284. (if (nth 4 info)
  285. (format " (%s) " (nth 4 info)) " "))))))
  286. (prog1 nil (message "Evaluation %s"
  287. (if (or (equal eval "never") (equal eval "no")
  288. (equal eval "no-export")
  289. (equal eval "never-export"))
  290. "Disabled" "Aborted")))
  291. t)))
  292. ;;;###autoload
  293. (defun org-babel-execute-safely-maybe ()
  294. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  295. (org-babel-execute-maybe)))
  296. (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-execute-safely-maybe)
  297. ;;;###autoload
  298. (defun org-babel-execute-maybe ()
  299. (interactive)
  300. (or (org-babel-execute-src-block-maybe)
  301. (org-babel-lob-execute-maybe)))
  302. (defun org-babel-execute-src-block-maybe ()
  303. "Conditionally execute a source block.
  304. Detect if this is context for a Babel src-block and if so
  305. then run `org-babel-execute-src-block'."
  306. (interactive)
  307. (let ((info (org-babel-get-src-block-info)))
  308. (if info
  309. (progn (org-babel-eval-wipe-error-buffer)
  310. (org-babel-execute-src-block current-prefix-arg info) t) nil)))
  311. ;;;###autoload
  312. (defun org-babel-view-src-block-info ()
  313. "Display information on the current source block.
  314. This includes header arguments, language and name, and is largely
  315. a window into the `org-babel-get-src-block-info' function."
  316. (interactive)
  317. (let ((info (org-babel-get-src-block-info 'light))
  318. (full (lambda (it) (> (length it) 0)))
  319. (printf (lambda (fmt &rest args) (princ (apply #'format fmt args)))))
  320. (when info
  321. (with-help-window (help-buffer)
  322. (let ((name (nth 4 info))
  323. (lang (nth 0 info))
  324. (switches (nth 3 info))
  325. (header-args (nth 2 info)))
  326. (when name (funcall printf "Name: %s\n" name))
  327. (when lang (funcall printf "Lang: %s\n" lang))
  328. (when (funcall full switches) (funcall printf "Switches: %s\n" switches))
  329. (funcall printf "Header Arguments:\n")
  330. (dolist (pair (sort header-args
  331. (lambda (a b) (string< (symbol-name (car a))
  332. (symbol-name (car b))))))
  333. (when (funcall full (cdr pair))
  334. (funcall printf "\t%S%s\t%s\n"
  335. (car pair)
  336. (if (> (length (format "%S" (car pair))) 7) "" "\t")
  337. (cdr pair)))))))))
  338. ;;;###autoload
  339. (defun org-babel-expand-src-block-maybe ()
  340. "Conditionally expand a source block.
  341. Detect if this is context for a org-babel src-block and if so
  342. then run `org-babel-expand-src-block'."
  343. (interactive)
  344. (let ((info (org-babel-get-src-block-info)))
  345. (if info
  346. (progn (org-babel-expand-src-block current-prefix-arg info) t)
  347. nil)))
  348. ;;;###autoload
  349. (defun org-babel-load-in-session-maybe ()
  350. "Conditionally load a source block in a session.
  351. Detect if this is context for a org-babel src-block and if so
  352. then run `org-babel-load-in-session'."
  353. (interactive)
  354. (let ((info (org-babel-get-src-block-info)))
  355. (if info
  356. (progn (org-babel-load-in-session current-prefix-arg info) t)
  357. nil)))
  358. (add-hook 'org-metaup-hook 'org-babel-load-in-session-maybe)
  359. ;;;###autoload
  360. (defun org-babel-pop-to-session-maybe ()
  361. "Conditionally pop to a session.
  362. Detect if this is context for a org-babel src-block and if so
  363. then run `org-babel-pop-to-session'."
  364. (interactive)
  365. (let ((info (org-babel-get-src-block-info)))
  366. (if info (progn (org-babel-pop-to-session current-prefix-arg info) t) nil)))
  367. (add-hook 'org-metadown-hook 'org-babel-pop-to-session-maybe)
  368. (defconst org-babel-common-header-args-w-values
  369. '((cache . ((no yes)))
  370. (cmdline . :any)
  371. (colnames . ((nil no yes)))
  372. (comments . ((no link yes org both noweb)))
  373. (dir . :any)
  374. (eval . ((never query)))
  375. (exports . ((code results both none)))
  376. (file . :any)
  377. (file-desc . :any)
  378. (hlines . ((no yes)))
  379. (mkdirp . ((yes no)))
  380. (no-expand)
  381. (noeval)
  382. (noweb . ((yes no tangle no-export strip-export)))
  383. (noweb-ref . :any)
  384. (noweb-sep . :any)
  385. (padline . ((yes no)))
  386. (results . ((file list vector table scalar verbatim)
  387. (raw html latex org code pp drawer)
  388. (replace silent none append prepend)
  389. (output value)))
  390. (rownames . ((no yes)))
  391. (sep . :any)
  392. (session . :any)
  393. (shebang . :any)
  394. (tangle . ((tangle yes no :any)))
  395. (var . :any)
  396. (wrap . :any)))
  397. (defconst org-babel-header-arg-names
  398. (mapcar #'car org-babel-common-header-args-w-values)
  399. "Common header arguments used by org-babel.
  400. Note that individual languages may define their own language
  401. specific header arguments as well.")
  402. (defvar org-babel-default-header-args
  403. '((:session . "none") (:results . "replace") (:exports . "code")
  404. (:cache . "no") (:noweb . "no") (:hlines . "no") (:tangle . "no")
  405. (:padnewline . "yes"))
  406. "Default arguments to use when evaluating a source block.")
  407. (defvar org-babel-default-inline-header-args
  408. '((:session . "none") (:results . "replace") (:exports . "results"))
  409. "Default arguments to use when evaluating an inline source block.")
  410. (defvar org-babel-data-names '("tblname" "results" "name"))
  411. (defvar org-babel-result-regexp
  412. (concat "^[ \t]*#\\+"
  413. (regexp-opt org-babel-data-names t)
  414. "\\(\\[\\("
  415. ;; FIXME The string below is `org-ts-regexp'
  416. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  417. " \\)?\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*")
  418. "Regular expression used to match result lines.
  419. If the results are associated with a hash key then the hash will
  420. be saved in the second match data.")
  421. (defvar org-babel-result-w-name-regexp
  422. (concat org-babel-result-regexp
  423. "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
  424. (defvar org-babel-min-lines-for-block-output 10
  425. "The minimum number of lines for block output.
  426. If number of lines of output is equal to or exceeds this
  427. value, the output is placed in a #+begin_example...#+end_example
  428. block. Otherwise the output is marked as literal by inserting
  429. colons at the starts of the lines. This variable only takes
  430. effect if the :results output option is in effect.")
  431. (defvar org-babel-noweb-error-langs nil
  432. "Languages for which Babel will raise literate programming errors.
  433. List of languages for which errors should be raised when the
  434. source code block satisfying a noweb reference in this language
  435. can not be resolved.")
  436. (defvar org-babel-hash-show 4
  437. "Number of initial characters to show of a hidden results hash.")
  438. (defvar org-babel-hash-show-time nil
  439. "When not nil show the time the code block was evaluated in the result hash.")
  440. (defvar org-babel-after-execute-hook nil
  441. "Hook for functions to be called after `org-babel-execute-src-block'")
  442. (defun org-babel-named-src-block-regexp-for-name (name)
  443. "This generates a regexp used to match a src block named NAME."
  444. (concat org-babel-src-name-regexp (regexp-quote name)
  445. "[ \t(]*[\r\n]\\(?:^#.*[\r\n]\\)*"
  446. (substring org-babel-src-block-regexp 1)))
  447. (defun org-babel-named-data-regexp-for-name (name)
  448. "This generates a regexp used to match data named NAME."
  449. (concat org-babel-result-regexp (regexp-quote name) "\\([ \t]\\|$\\)"))
  450. ;;; functions
  451. (defvar call-process-region)
  452. ;;;###autoload
  453. (defun org-babel-execute-src-block (&optional arg info params)
  454. "Execute the current source code block.
  455. Insert the results of execution into the buffer. Source code
  456. execution and the collection and formatting of results can be
  457. controlled through a variety of header arguments.
  458. With prefix argument ARG, force re-execution even if an existing
  459. result cached in the buffer would otherwise have been returned.
  460. Optionally supply a value for INFO in the form returned by
  461. `org-babel-get-src-block-info'.
  462. Optionally supply a value for PARAMS which will be merged with
  463. the header arguments specified at the front of the source code
  464. block."
  465. (interactive)
  466. (let* ((info (or info (org-babel-get-src-block-info)))
  467. (merged-params (org-babel-merge-params (nth 2 info) params)))
  468. (when (org-babel-confirm-evaluate
  469. (let ((i info)) (setf (nth 2 i) merged-params) i))
  470. (let* ((lang (nth 0 info))
  471. (params (if params
  472. (org-babel-process-params merged-params)
  473. (nth 2 info)))
  474. (cache-p (and (not arg) (cdr (assoc :cache params))
  475. (string= "yes" (cdr (assoc :cache params)))))
  476. (result-params (cdr (assoc :result-params params)))
  477. (new-hash (when cache-p (org-babel-sha1-hash info)))
  478. (old-hash (when cache-p (org-babel-current-result-hash)))
  479. (cache-current-p (and (not arg) new-hash (equal new-hash old-hash)))
  480. (body (setf (nth 1 info)
  481. (if (org-babel-noweb-p params :eval)
  482. (org-babel-expand-noweb-references info)
  483. (nth 1 info))))
  484. (dir (cdr (assoc :dir params)))
  485. (default-directory
  486. (or (and dir (file-name-as-directory (expand-file-name dir)))
  487. default-directory))
  488. (org-babel-call-process-region-original
  489. (if (boundp 'org-babel-call-process-region-original)
  490. org-babel-call-process-region-original
  491. (symbol-function 'call-process-region)))
  492. (indent (car (last info)))
  493. result cmd)
  494. (unwind-protect
  495. (let ((call-process-region
  496. (lambda (&rest args)
  497. (apply 'org-babel-tramp-handle-call-process-region args))))
  498. (let ((lang-check (lambda (f)
  499. (let ((f (intern (concat "org-babel-execute:" f))))
  500. (when (fboundp f) f)))))
  501. (setq cmd
  502. (or (funcall lang-check lang)
  503. (funcall lang-check (symbol-name
  504. (cdr (assoc lang org-src-lang-modes))))
  505. (error "No org-babel-execute function for %s!" lang))))
  506. (if cache-current-p
  507. (save-excursion ;; return cached result
  508. (goto-char (org-babel-where-is-src-block-result nil info))
  509. (end-of-line 1) (forward-char 1)
  510. (setq result (org-babel-read-result))
  511. (message (replace-regexp-in-string
  512. "%" "%%" (format "%S" result))) result)
  513. (message "executing %s code block%s..."
  514. (capitalize lang)
  515. (if (nth 4 info) (format " (%s)" (nth 4 info)) ""))
  516. (if (member "none" result-params)
  517. (progn
  518. (funcall cmd body params)
  519. (message "result silenced"))
  520. (setq result
  521. ((lambda (result)
  522. (if (and (eq (cdr (assoc :result-type params)) 'value)
  523. (or (member "vector" result-params)
  524. (member "table" result-params))
  525. (not (listp result)))
  526. (list (list result)) result))
  527. (funcall cmd body params)))
  528. ;; if non-empty result and :file then write to :file
  529. (when (cdr (assoc :file params))
  530. (when result
  531. (with-temp-file (cdr (assoc :file params))
  532. (insert
  533. (org-babel-format-result
  534. result (cdr (assoc :sep (nth 2 info)))))))
  535. (setq result (cdr (assoc :file params))))
  536. (org-babel-insert-result
  537. result result-params info new-hash indent lang)
  538. (run-hooks 'org-babel-after-execute-hook)
  539. result
  540. )))
  541. (setq call-process-region 'org-babel-call-process-region-original))))))
  542. (defun org-babel-expand-body:generic (body params &optional var-lines)
  543. "Expand BODY with PARAMS.
  544. Expand a block of code with org-babel according to its header
  545. arguments. This generic implementation of body expansion is
  546. called for languages which have not defined their own specific
  547. org-babel-expand-body:lang function."
  548. (mapconcat #'identity (append var-lines (list body)) "\n"))
  549. ;;;###autoload
  550. (defun org-babel-expand-src-block (&optional arg info params)
  551. "Expand the current source code block.
  552. Expand according to the source code block's header
  553. arguments and pop open the results in a preview buffer."
  554. (interactive)
  555. (let* ((info (or info (org-babel-get-src-block-info)))
  556. (lang (nth 0 info))
  557. (params (setf (nth 2 info)
  558. (sort (org-babel-merge-params (nth 2 info) params)
  559. (lambda (el1 el2) (string< (symbol-name (car el1))
  560. (symbol-name (car el2)))))))
  561. (body (setf (nth 1 info)
  562. (if (org-babel-noweb-p params :eval)
  563. (org-babel-expand-noweb-references info) (nth 1 info))))
  564. (expand-cmd (intern (concat "org-babel-expand-body:" lang)))
  565. (assignments-cmd (intern (concat "org-babel-variable-assignments:"
  566. lang)))
  567. (expanded
  568. (if (fboundp expand-cmd) (funcall expand-cmd body params)
  569. (org-babel-expand-body:generic
  570. body params (and (fboundp assignments-cmd)
  571. (funcall assignments-cmd params))))))
  572. (if (called-interactively-p 'any)
  573. (org-edit-src-code
  574. nil expanded
  575. (concat "*Org-Babel Preview " (buffer-name) "[ " lang " ]*"))
  576. expanded)))
  577. (defun org-babel-edit-distance (s1 s2)
  578. "Return the edit (levenshtein) distance between strings S1 S2."
  579. (let* ((l1 (length s1))
  580. (l2 (length s2))
  581. (dist (vconcat (mapcar (lambda (_) (make-vector (1+ l2) nil))
  582. (number-sequence 1 (1+ l1)))))
  583. (in (lambda (i j) (aref (aref dist i) j))))
  584. (setf (aref (aref dist 0) 0) 0)
  585. (dolist (j (number-sequence 1 l2))
  586. (setf (aref (aref dist 0) j) j))
  587. (dolist (i (number-sequence 1 l1))
  588. (setf (aref (aref dist i) 0) i)
  589. (dolist (j (number-sequence 1 l2))
  590. (setf (aref (aref dist i) j)
  591. (min
  592. (1+ (funcall in (1- i) j))
  593. (1+ (funcall in i (1- j)))
  594. (+ (if (equal (aref s1 (1- i)) (aref s2 (1- j))) 0 1)
  595. (funcall in (1- i) (1- j)))))))
  596. (funcall in l1 l2)))
  597. (defun org-babel-combine-header-arg-lists (original &rest others)
  598. "Combine a number of lists of header argument names and arguments."
  599. (let ((results (copy-sequence original)))
  600. (dolist (new-list others)
  601. (dolist (arg-pair new-list)
  602. (let ((header (car arg-pair))
  603. (args (cdr arg-pair)))
  604. (setq results
  605. (cons arg-pair (org-remove-if
  606. (lambda (pair) (equal header (car pair)))
  607. results))))))
  608. results))
  609. ;;;###autoload
  610. (defun org-babel-check-src-block ()
  611. "Check for misspelled header arguments in the current code block."
  612. (interactive)
  613. ;; TODO: report malformed code block
  614. ;; TODO: report incompatible combinations of header arguments
  615. ;; TODO: report uninitialized variables
  616. (let ((too-close 2) ;; <- control closeness to report potential match
  617. (names (mapcar #'symbol-name org-babel-header-arg-names)))
  618. (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg)) 1))
  619. (and (org-babel-where-is-src-block-head)
  620. (org-babel-parse-header-arguments
  621. (org-no-properties
  622. (match-string 4))))))
  623. (dolist (name names)
  624. (when (and (not (string= header name))
  625. (<= (org-babel-edit-distance header name) too-close)
  626. (not (member header names)))
  627. (error "Supplied header \"%S\" is suspiciously close to \"%S\""
  628. header name))))
  629. (message "No suspicious header arguments found.")))
  630. ;;;###autoload
  631. (defun org-babel-insert-header-arg ()
  632. "Insert a header argument selecting from lists of common args and values."
  633. (interactive)
  634. (let* ((lang (car (org-babel-get-src-block-info 'light)))
  635. (lang-headers (intern (concat "org-babel-header-args:" lang)))
  636. (headers (org-babel-combine-header-arg-lists
  637. org-babel-common-header-args-w-values
  638. (if (boundp lang-headers) (eval lang-headers) nil)))
  639. (arg (org-icompleting-read
  640. "Header Arg: "
  641. (mapcar
  642. (lambda (header-spec) (symbol-name (car header-spec)))
  643. headers))))
  644. (insert ":" arg)
  645. (let ((vals (cdr (assoc (intern arg) headers))))
  646. (when vals
  647. (insert
  648. " "
  649. (cond
  650. ((eq vals :any)
  651. (read-from-minibuffer "value: "))
  652. ((listp vals)
  653. (mapconcat
  654. (lambda (group)
  655. (let ((arg (org-icompleting-read
  656. "value: "
  657. (cons "default" (mapcar #'symbol-name group)))))
  658. (if (and arg (not (string= "default" arg)))
  659. (concat arg " ")
  660. "")))
  661. vals ""))))))))
  662. ;; Add support for completing-read insertion of header arguments after ":"
  663. (defun org-babel-header-arg-expand ()
  664. "Call `org-babel-enter-header-arg-w-completion' in appropriate contexts."
  665. (when (and (equal (char-before) ?\:) (org-babel-where-is-src-block-head))
  666. (org-babel-enter-header-arg-w-completion (match-string 2))))
  667. (defun org-babel-enter-header-arg-w-completion (&optional lang)
  668. "Insert header argument appropriate for LANG with completion."
  669. (let* ((lang-headers-var (intern (concat "org-babel-header-args:" lang)))
  670. (lang-headers (when (boundp lang-headers-var) (eval lang-headers-var)))
  671. (headers-w-values (org-babel-combine-header-arg-lists
  672. org-babel-common-header-args-w-values lang-headers))
  673. (headers (mapcar #'symbol-name (mapcar #'car headers-w-values)))
  674. (header (org-completing-read "Header Arg: " headers))
  675. (args (cdr (assoc (intern header) headers-w-values)))
  676. (arg (when (and args (listp args))
  677. (org-completing-read
  678. (format "%s: " header)
  679. (mapcar #'symbol-name (apply #'append args))))))
  680. (insert (concat header " " (or arg "")))
  681. (cons header arg)))
  682. (add-hook 'org-tab-first-hook 'org-babel-header-arg-expand)
  683. ;;;###autoload
  684. (defun org-babel-load-in-session (&optional arg info)
  685. "Load the body of the current source-code block.
  686. Evaluate the header arguments for the source block before
  687. entering the session. After loading the body this pops open the
  688. session."
  689. (interactive)
  690. (let* ((info (or info (org-babel-get-src-block-info)))
  691. (lang (nth 0 info))
  692. (params (nth 2 info))
  693. (body (if (not info)
  694. (user-error "No src code block at point")
  695. (setf (nth 1 info)
  696. (if (org-babel-noweb-p params :eval)
  697. (org-babel-expand-noweb-references info)
  698. (nth 1 info)))))
  699. (session (cdr (assoc :session params)))
  700. (dir (cdr (assoc :dir params)))
  701. (default-directory
  702. (or (and dir (file-name-as-directory dir)) default-directory))
  703. (cmd (intern (concat "org-babel-load-session:" lang))))
  704. (unless (fboundp cmd)
  705. (error "No org-babel-load-session function for %s!" lang))
  706. (pop-to-buffer (funcall cmd session body params))
  707. (end-of-line 1)))
  708. ;;;###autoload
  709. (defun org-babel-initiate-session (&optional arg info)
  710. "Initiate session for current code block.
  711. If called with a prefix argument then resolve any variable
  712. references in the header arguments and assign these variables in
  713. the session. Copy the body of the code block to the kill ring."
  714. (interactive "P")
  715. (let* ((info (or info (org-babel-get-src-block-info (not arg))))
  716. (lang (nth 0 info))
  717. (body (nth 1 info))
  718. (params (nth 2 info))
  719. (session (cdr (assoc :session params)))
  720. (dir (cdr (assoc :dir params)))
  721. (default-directory
  722. (or (and dir (file-name-as-directory dir)) default-directory))
  723. (init-cmd (intern (format "org-babel-%s-initiate-session" lang)))
  724. (prep-cmd (intern (concat "org-babel-prep-session:" lang))))
  725. (if (and (stringp session) (string= session "none"))
  726. (error "This block is not using a session!"))
  727. (unless (fboundp init-cmd)
  728. (error "No org-babel-initiate-session function for %s!" lang))
  729. (with-temp-buffer (insert (org-babel-trim body))
  730. (copy-region-as-kill (point-min) (point-max)))
  731. (when arg
  732. (unless (fboundp prep-cmd)
  733. (error "No org-babel-prep-session function for %s!" lang))
  734. (funcall prep-cmd session params))
  735. (funcall init-cmd session params)))
  736. ;;;###autoload
  737. (defun org-babel-switch-to-session (&optional arg info)
  738. "Switch to the session of the current code block.
  739. Uses `org-babel-initiate-session' to start the session. If called
  740. with a prefix argument then this is passed on to
  741. `org-babel-initiate-session'."
  742. (interactive "P")
  743. (pop-to-buffer (org-babel-initiate-session arg info))
  744. (end-of-line 1))
  745. (defalias 'org-babel-pop-to-session 'org-babel-switch-to-session)
  746. ;;;###autoload
  747. (defun org-babel-switch-to-session-with-code (&optional arg info)
  748. "Switch to code buffer and display session."
  749. (interactive "P")
  750. (let ((swap-windows
  751. (lambda ()
  752. (let ((other-window-buffer (window-buffer (next-window))))
  753. (set-window-buffer (next-window) (current-buffer))
  754. (set-window-buffer (selected-window) other-window-buffer))
  755. (other-window 1)))
  756. (info (org-babel-get-src-block-info))
  757. (org-src-window-setup 'reorganize-frame))
  758. (save-excursion
  759. (org-babel-switch-to-session arg info))
  760. (org-edit-src-code)
  761. (funcall swap-windows)))
  762. (defmacro org-babel-do-in-edit-buffer (&rest body)
  763. "Evaluate BODY in edit buffer if there is a code block at point.
  764. Return t if a code block was found at point, nil otherwise."
  765. `(let ((org-src-window-setup 'switch-invisibly))
  766. (when (and (org-babel-where-is-src-block-head)
  767. (org-edit-src-code nil nil nil))
  768. (unwind-protect (progn ,@body)
  769. (if (org-bound-and-true-p org-edit-src-from-org-mode)
  770. (org-edit-src-exit)))
  771. t)))
  772. (def-edebug-spec org-babel-do-in-edit-buffer (body))
  773. (defun org-babel-do-key-sequence-in-edit-buffer (key)
  774. "Read key sequence and execute the command in edit buffer.
  775. Enter a key sequence to be executed in the language major-mode
  776. edit buffer. For example, TAB will alter the contents of the
  777. Org-mode code block according to the effect of TAB in the
  778. language major-mode buffer. For languages that support
  779. interactive sessions, this can be used to send code from the Org
  780. buffer to the session for evaluation using the native major-mode
  781. evaluation mechanisms."
  782. (interactive "kEnter key-sequence to execute in edit buffer: ")
  783. (org-babel-do-in-edit-buffer
  784. (call-interactively
  785. (key-binding (or key (read-key-sequence nil))))))
  786. (defvar org-bracket-link-regexp)
  787. ;;;###autoload
  788. (defun org-babel-open-src-block-result (&optional re-run)
  789. "If `point' is on a src block then open the results of the
  790. source code block, otherwise return nil. With optional prefix
  791. argument RE-RUN the source-code block is evaluated even if
  792. results already exist."
  793. (interactive "P")
  794. (let ((info (org-babel-get-src-block-info)))
  795. (when info
  796. (save-excursion
  797. ;; go to the results, if there aren't any then run the block
  798. (goto-char (or (and (not re-run) (org-babel-where-is-src-block-result))
  799. (progn (org-babel-execute-src-block)
  800. (org-babel-where-is-src-block-result))))
  801. (end-of-line 1)
  802. (while (looking-at "[\n\r\t\f ]") (forward-char 1))
  803. ;; open the results
  804. (if (looking-at org-bracket-link-regexp)
  805. ;; file results
  806. (org-open-at-point)
  807. (let ((r (org-babel-format-result
  808. (org-babel-read-result) (cdr (assoc :sep (nth 2 info))))))
  809. (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
  810. (delete-region (point-min) (point-max))
  811. (insert r)))
  812. t))))
  813. ;;;###autoload
  814. (defmacro org-babel-map-src-blocks (file &rest body)
  815. "Evaluate BODY forms on each source-block in FILE.
  816. If FILE is nil evaluate BODY forms on source blocks in current
  817. buffer. During evaluation of BODY the following local variables
  818. are set relative to the currently matched code block.
  819. full-block ------- string holding the entirety of the code block
  820. beg-block -------- point at the beginning of the code block
  821. end-block -------- point at the end of the matched code block
  822. lang ------------- string holding the language of the code block
  823. beg-lang --------- point at the beginning of the lang
  824. end-lang --------- point at the end of the lang
  825. switches --------- string holding the switches
  826. beg-switches ----- point at the beginning of the switches
  827. end-switches ----- point at the end of the switches
  828. header-args ------ string holding the header-args
  829. beg-header-args -- point at the beginning of the header-args
  830. end-header-args -- point at the end of the header-args
  831. body ------------- string holding the body of the code block
  832. beg-body --------- point at the beginning of the body
  833. end-body --------- point at the end of the body"
  834. (declare (indent 1))
  835. (let ((tempvar (make-symbol "file")))
  836. `(let* ((,tempvar ,file)
  837. (visited-p (or (null ,tempvar)
  838. (get-file-buffer (expand-file-name ,tempvar))))
  839. (point (point)) to-be-removed)
  840. (save-window-excursion
  841. (when ,tempvar (find-file ,tempvar))
  842. (setq to-be-removed (current-buffer))
  843. (goto-char (point-min))
  844. (while (re-search-forward org-babel-src-block-regexp nil t)
  845. (goto-char (match-beginning 0))
  846. (let ((full-block (match-string 0))
  847. (beg-block (match-beginning 0))
  848. (end-block (match-end 0))
  849. (lang (match-string 2))
  850. (beg-lang (match-beginning 2))
  851. (end-lang (match-end 2))
  852. (switches (match-string 3))
  853. (beg-switches (match-beginning 3))
  854. (end-switches (match-end 3))
  855. (header-args (match-string 4))
  856. (beg-header-args (match-beginning 4))
  857. (end-header-args (match-end 4))
  858. (body (match-string 5))
  859. (beg-body (match-beginning 5))
  860. (end-body (match-end 5)))
  861. ,@body
  862. (goto-char end-block))))
  863. (unless visited-p (kill-buffer to-be-removed))
  864. (goto-char point))))
  865. (def-edebug-spec org-babel-map-src-blocks (form body))
  866. ;;;###autoload
  867. (defmacro org-babel-map-inline-src-blocks (file &rest body)
  868. "Evaluate BODY forms on each inline source-block in FILE.
  869. If FILE is nil evaluate BODY forms on source blocks in current
  870. buffer."
  871. (declare (indent 1))
  872. (let ((tempvar (make-symbol "file")))
  873. `(let* ((,tempvar ,file)
  874. (visited-p (or (null ,tempvar)
  875. (get-file-buffer (expand-file-name ,tempvar))))
  876. (point (point)) to-be-removed)
  877. (save-window-excursion
  878. (when ,tempvar (find-file ,tempvar))
  879. (setq to-be-removed (current-buffer))
  880. (goto-char (point-min))
  881. (while (re-search-forward org-babel-inline-src-block-regexp nil t)
  882. (goto-char (match-beginning 1))
  883. (save-match-data ,@body)
  884. (goto-char (match-end 0))))
  885. (unless visited-p (kill-buffer to-be-removed))
  886. (goto-char point))))
  887. (def-edebug-spec org-babel-map-inline-src-blocks (form body))
  888. (defvar org-babel-lob-one-liner-regexp)
  889. ;;;###autoload
  890. (defmacro org-babel-map-call-lines (file &rest body)
  891. "Evaluate BODY forms on each call line in FILE.
  892. If FILE is nil evaluate BODY forms on source blocks in current
  893. buffer."
  894. (declare (indent 1))
  895. (let ((tempvar (make-symbol "file")))
  896. `(let* ((,tempvar ,file)
  897. (visited-p (or (null ,tempvar)
  898. (get-file-buffer (expand-file-name ,tempvar))))
  899. (point (point)) to-be-removed)
  900. (save-window-excursion
  901. (when ,tempvar (find-file ,tempvar))
  902. (setq to-be-removed (current-buffer))
  903. (goto-char (point-min))
  904. (while (re-search-forward org-babel-lob-one-liner-regexp nil t)
  905. (goto-char (match-beginning 1))
  906. (save-match-data ,@body)
  907. (goto-char (match-end 0))))
  908. (unless visited-p (kill-buffer to-be-removed))
  909. (goto-char point))))
  910. (def-edebug-spec org-babel-map-call-lines (form body))
  911. ;;;###autoload
  912. (defmacro org-babel-map-executables (file &rest body)
  913. (declare (indent 1))
  914. (let ((tempvar (make-symbol "file"))
  915. (rx (make-symbol "rx")))
  916. `(let* ((,tempvar ,file)
  917. (,rx (concat "\\(" org-babel-src-block-regexp
  918. "\\|" org-babel-inline-src-block-regexp
  919. "\\|" org-babel-lob-one-liner-regexp "\\)"))
  920. (visited-p (or (null ,tempvar)
  921. (get-file-buffer (expand-file-name ,tempvar))))
  922. (point (point)) to-be-removed)
  923. (save-window-excursion
  924. (when ,tempvar (find-file ,tempvar))
  925. (setq to-be-removed (current-buffer))
  926. (goto-char (point-min))
  927. (while (re-search-forward ,rx nil t)
  928. (goto-char (match-beginning 1))
  929. (when (looking-at org-babel-inline-src-block-regexp)(forward-char 1))
  930. (save-match-data ,@body)
  931. (goto-char (match-end 0))))
  932. (unless visited-p (kill-buffer to-be-removed))
  933. (goto-char point))))
  934. (def-edebug-spec org-babel-map-executables (form body))
  935. ;;;###autoload
  936. (defun org-babel-execute-buffer (&optional arg)
  937. "Execute source code blocks in a buffer.
  938. Call `org-babel-execute-src-block' on every source block in
  939. the current buffer."
  940. (interactive "P")
  941. (org-babel-eval-wipe-error-buffer)
  942. (org-save-outline-visibility t
  943. (org-babel-map-executables nil
  944. (if (looking-at org-babel-lob-one-liner-regexp)
  945. (org-babel-lob-execute-maybe)
  946. (org-babel-execute-src-block arg)))))
  947. ;;;###autoload
  948. (defun org-babel-execute-subtree (&optional arg)
  949. "Execute source code blocks in a subtree.
  950. Call `org-babel-execute-src-block' on every source block in
  951. the current subtree."
  952. (interactive "P")
  953. (save-restriction
  954. (save-excursion
  955. (org-narrow-to-subtree)
  956. (org-babel-execute-buffer arg)
  957. (widen))))
  958. ;;;###autoload
  959. (defun org-babel-sha1-hash (&optional info)
  960. "Generate an sha1 hash based on the value of info."
  961. (interactive)
  962. (let ((print-level nil)
  963. (info (or info (org-babel-get-src-block-info))))
  964. (setf (nth 2 info)
  965. (sort (copy-sequence (nth 2 info))
  966. (lambda (a b) (string< (car a) (car b)))))
  967. (let* ((rm (lambda (lst)
  968. (dolist (p '("replace" "silent" "none"
  969. "append" "prepend"))
  970. (setq lst (remove p lst)))
  971. lst))
  972. (norm (lambda (arg)
  973. (let ((v (if (and (listp (cdr arg)) (null (cddr arg)))
  974. (copy-sequence (cdr arg))
  975. (cdr arg))))
  976. (when (and v (not (and (sequencep v)
  977. (not (consp v))
  978. (= (length v) 0))))
  979. (cond
  980. ((and (listp v) ; lists are sorted
  981. (member (car arg) '(:result-params)))
  982. (sort (funcall rm v) #'string<))
  983. ((and (stringp v) ; strings are sorted
  984. (member (car arg) '(:results :exports)))
  985. (mapconcat #'identity (sort (funcall rm (split-string v))
  986. #'string<) " "))
  987. (t v)))))))
  988. ((lambda (hash)
  989. (when (org-called-interactively-p 'interactive) (message hash)) hash)
  990. (let ((it (format "%s-%s"
  991. (mapconcat
  992. #'identity
  993. (delq nil (mapcar (lambda (arg)
  994. (let ((normalized (funcall norm arg)))
  995. (when normalized
  996. (format "%S" normalized))))
  997. (nth 2 info))) ":")
  998. (nth 1 info))))
  999. (sha1 it))))))
  1000. (defun org-babel-current-result-hash ()
  1001. "Return the current in-buffer hash."
  1002. (org-babel-where-is-src-block-result)
  1003. (org-no-properties (match-string 5)))
  1004. (defun org-babel-set-current-result-hash (hash)
  1005. "Set the current in-buffer hash to HASH."
  1006. (org-babel-where-is-src-block-result)
  1007. (save-excursion (goto-char (match-beginning 3))
  1008. ;; (mapc #'delete-overlay (overlays-at (point)))
  1009. (replace-match hash nil nil nil 3)
  1010. (org-babel-hide-hash)))
  1011. (defun org-babel-hide-hash ()
  1012. "Hide the hash in the current results line.
  1013. Only the initial `org-babel-hash-show' characters of the hash
  1014. will remain visible."
  1015. (add-to-invisibility-spec '(org-babel-hide-hash . t))
  1016. (save-excursion
  1017. (when (and (re-search-forward org-babel-result-regexp nil t)
  1018. (match-string 5))
  1019. (let* ((start (match-beginning 5))
  1020. (hide-start (+ org-babel-hash-show start))
  1021. (end (match-end 5))
  1022. (hash (match-string 5))
  1023. ov1 ov2)
  1024. (setq ov1 (make-overlay start hide-start))
  1025. (setq ov2 (make-overlay hide-start end))
  1026. (overlay-put ov2 'invisible 'org-babel-hide-hash)
  1027. (overlay-put ov1 'babel-hash hash)))))
  1028. (defun org-babel-hide-all-hashes ()
  1029. "Hide the hash in the current buffer.
  1030. Only the initial `org-babel-hash-show' characters of each hash
  1031. will remain visible. This function should be called as part of
  1032. the `org-mode-hook'."
  1033. (save-excursion
  1034. (while (and (not org-babel-hash-show-time)
  1035. (re-search-forward org-babel-result-regexp nil t))
  1036. (goto-char (match-beginning 0))
  1037. (org-babel-hide-hash)
  1038. (goto-char (match-end 0)))))
  1039. (add-hook 'org-mode-hook 'org-babel-hide-all-hashes)
  1040. (defun org-babel-hash-at-point (&optional point)
  1041. "Return the value of the hash at POINT.
  1042. The hash is also added as the last element of the kill ring.
  1043. This can be called with C-c C-c."
  1044. (interactive)
  1045. (let ((hash (car (delq nil (mapcar
  1046. (lambda (ol) (overlay-get ol 'babel-hash))
  1047. (overlays-at (or point (point))))))))
  1048. (when hash (kill-new hash) (message hash))))
  1049. (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-hash-at-point)
  1050. (defun org-babel-result-hide-spec ()
  1051. "Hide portions of results lines.
  1052. Add `org-babel-hide-result' as an invisibility spec for hiding
  1053. portions of results lines."
  1054. (add-to-invisibility-spec '(org-babel-hide-result . t)))
  1055. (add-hook 'org-mode-hook 'org-babel-result-hide-spec)
  1056. (defvar org-babel-hide-result-overlays nil
  1057. "Overlays hiding results.")
  1058. (defun org-babel-result-hide-all ()
  1059. "Fold all results in the current buffer."
  1060. (interactive)
  1061. (org-babel-show-result-all)
  1062. (save-excursion
  1063. (while (re-search-forward org-babel-result-regexp nil t)
  1064. (save-excursion (goto-char (match-beginning 0))
  1065. (org-babel-hide-result-toggle-maybe)))))
  1066. (defun org-babel-show-result-all ()
  1067. "Unfold all results in the current buffer."
  1068. (mapc 'delete-overlay org-babel-hide-result-overlays)
  1069. (setq org-babel-hide-result-overlays nil))
  1070. ;;;###autoload
  1071. (defun org-babel-hide-result-toggle-maybe ()
  1072. "Toggle visibility of result at point."
  1073. (interactive)
  1074. (let ((case-fold-search t))
  1075. (if (save-excursion
  1076. (beginning-of-line 1)
  1077. (looking-at org-babel-result-regexp))
  1078. (progn (org-babel-hide-result-toggle)
  1079. t) ;; to signal that we took action
  1080. nil))) ;; to signal that we did not
  1081. (defun org-babel-hide-result-toggle (&optional force)
  1082. "Toggle the visibility of the current result."
  1083. (interactive)
  1084. (save-excursion
  1085. (beginning-of-line)
  1086. (if (re-search-forward org-babel-result-regexp nil t)
  1087. (let ((start (progn (beginning-of-line 2) (- (point) 1)))
  1088. (end (progn
  1089. (while (looking-at org-babel-multi-line-header-regexp)
  1090. (forward-line 1))
  1091. (goto-char (- (org-babel-result-end) 1)) (point)))
  1092. ov)
  1093. (if (memq t (mapcar (lambda (overlay)
  1094. (eq (overlay-get overlay 'invisible)
  1095. 'org-babel-hide-result))
  1096. (overlays-at start)))
  1097. (if (or (not force) (eq force 'off))
  1098. (mapc (lambda (ov)
  1099. (when (member ov org-babel-hide-result-overlays)
  1100. (setq org-babel-hide-result-overlays
  1101. (delq ov org-babel-hide-result-overlays)))
  1102. (when (eq (overlay-get ov 'invisible)
  1103. 'org-babel-hide-result)
  1104. (delete-overlay ov)))
  1105. (overlays-at start)))
  1106. (setq ov (make-overlay start end))
  1107. (overlay-put ov 'invisible 'org-babel-hide-result)
  1108. ;; make the block accessible to isearch
  1109. (overlay-put
  1110. ov 'isearch-open-invisible
  1111. (lambda (ov)
  1112. (when (member ov org-babel-hide-result-overlays)
  1113. (setq org-babel-hide-result-overlays
  1114. (delq ov org-babel-hide-result-overlays)))
  1115. (when (eq (overlay-get ov 'invisible)
  1116. 'org-babel-hide-result)
  1117. (delete-overlay ov))))
  1118. (push ov org-babel-hide-result-overlays)))
  1119. (error "Not looking at a result line"))))
  1120. ;; org-tab-after-check-for-cycling-hook
  1121. (add-hook 'org-tab-first-hook 'org-babel-hide-result-toggle-maybe)
  1122. ;; Remove overlays when changing major mode
  1123. (add-hook 'org-mode-hook
  1124. (lambda () (org-add-hook 'change-major-mode-hook
  1125. 'org-babel-show-result-all 'append 'local)))
  1126. (defvar org-file-properties)
  1127. (defun org-babel-params-from-properties (&optional lang)
  1128. "Retrieve parameters specified as properties.
  1129. Return an association list of any source block params which
  1130. may be specified in the properties of the current outline entry."
  1131. (save-match-data
  1132. (let (val sym)
  1133. (org-babel-parse-multiple-vars
  1134. (delq nil
  1135. (mapcar
  1136. (lambda (header-arg)
  1137. (and (setq val (org-entry-get (point) header-arg t))
  1138. (cons (intern (concat ":" header-arg))
  1139. (org-babel-read val))))
  1140. (mapcar
  1141. #'symbol-name
  1142. (mapcar
  1143. #'car
  1144. (org-babel-combine-header-arg-lists
  1145. org-babel-common-header-args-w-values
  1146. (progn
  1147. (setq sym (intern (concat "org-babel-header-args:" lang)))
  1148. (and (boundp sym) (eval sym))))))))))))
  1149. (defvar org-src-preserve-indentation)
  1150. (defun org-babel-parse-src-block-match ()
  1151. "Parse the results from a match of the `org-babel-src-block-regexp'."
  1152. (let* ((block-indentation (length (match-string 1)))
  1153. (lang (org-no-properties (match-string 2)))
  1154. (lang-headers (intern (concat "org-babel-default-header-args:" lang)))
  1155. (switches (match-string 3))
  1156. (body (org-no-properties
  1157. (let* ((body (match-string 5))
  1158. (sub-length (- (length body) 1)))
  1159. (if (and (> sub-length 0)
  1160. (string= "\n" (substring body sub-length)))
  1161. (substring body 0 sub-length)
  1162. (or body "")))))
  1163. (preserve-indentation (or org-src-preserve-indentation
  1164. (save-match-data
  1165. (string-match "-i\\>" switches)))))
  1166. (list lang
  1167. ;; get block body less properties, protective commas, and indentation
  1168. (with-temp-buffer
  1169. (save-match-data
  1170. (insert (org-unescape-code-in-string body))
  1171. (unless preserve-indentation (org-do-remove-indentation))
  1172. (buffer-string)))
  1173. (org-babel-merge-params
  1174. org-babel-default-header-args
  1175. (org-babel-params-from-properties lang)
  1176. (if (boundp lang-headers) (eval lang-headers) nil)
  1177. (org-babel-parse-header-arguments
  1178. (org-no-properties (or (match-string 4) ""))))
  1179. switches
  1180. block-indentation)))
  1181. (defun org-babel-parse-inline-src-block-match ()
  1182. "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
  1183. (let* ((lang (org-no-properties (match-string 2)))
  1184. (lang-headers (intern (concat "org-babel-default-header-args:" lang))))
  1185. (list lang
  1186. (org-unescape-code-in-string (org-no-properties (match-string 5)))
  1187. (org-babel-merge-params
  1188. org-babel-default-inline-header-args
  1189. (org-babel-params-from-properties lang)
  1190. (if (boundp lang-headers) (eval lang-headers) nil)
  1191. (org-babel-parse-header-arguments
  1192. (org-no-properties (or (match-string 4) "")))))))
  1193. (defun org-babel-balanced-split (string alts)
  1194. "Split STRING on instances of ALTS.
  1195. ALTS is a cons of two character options where each option may be
  1196. either the numeric code of a single character or a list of
  1197. character alternatives. For example to split on balanced
  1198. instances of \"[ \t]:\" set ALTS to '((32 9) . 58)."
  1199. (let* ((matches (lambda (ch spec) (if (listp spec) (member ch spec) (equal spec ch))))
  1200. (matched (lambda (ch last)
  1201. (if (consp alts)
  1202. (and (funcall matches ch (cdr alts))
  1203. (funcall matches last (car alts)))
  1204. (funcall matches ch alts))))
  1205. (balance 0) (last 0)
  1206. quote partial lst)
  1207. (mapc (lambda (ch) ; split on [], (), "" balanced instances of [ \t]:
  1208. (setq balance (+ balance
  1209. (cond ((or (equal 91 ch) (equal 40 ch)) 1)
  1210. ((or (equal 93 ch) (equal 41 ch)) -1)
  1211. (t 0))))
  1212. (when (and (equal 34 ch) (not (equal 92 last)))
  1213. (setq quote (not quote)))
  1214. (setq partial (cons ch partial))
  1215. (when (and (= balance 0) (not quote) (funcall matched ch last))
  1216. (setq lst (cons (apply #'string (nreverse
  1217. (if (consp alts)
  1218. (cddr partial)
  1219. (cdr partial))))
  1220. lst))
  1221. (setq partial nil))
  1222. (setq last ch))
  1223. (string-to-list string))
  1224. (nreverse (cons (apply #'string (nreverse partial)) lst))))
  1225. (defun org-babel-join-splits-near-ch (ch list)
  1226. "Join splits where \"=\" is on either end of the split."
  1227. (let ((last= (lambda (str) (= ch (aref str (1- (length str))))))
  1228. (first= (lambda (str) (= ch (aref str 0)))))
  1229. (reverse
  1230. (org-reduce (lambda (acc el)
  1231. (let ((head (car acc)))
  1232. (if (and head (or (funcall last= head) (funcall first= el)))
  1233. (cons (concat head el) (cdr acc))
  1234. (cons el acc))))
  1235. list :initial-value nil))))
  1236. (defun org-babel-parse-header-arguments (arg-string)
  1237. "Parse a string of header arguments returning an alist."
  1238. (when (> (length arg-string) 0)
  1239. (org-babel-parse-multiple-vars
  1240. (delq nil
  1241. (mapcar
  1242. (lambda (arg)
  1243. (if (string-match
  1244. "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
  1245. arg)
  1246. (cons (intern (match-string 1 arg))
  1247. (org-babel-read (org-babel-chomp (match-string 2 arg))))
  1248. (cons (intern (org-babel-chomp arg)) nil)))
  1249. ((lambda (raw)
  1250. (cons (car raw) (mapcar (lambda (r) (concat ":" r)) (cdr raw))))
  1251. (org-babel-balanced-split arg-string '((32 9) . 58))))))))
  1252. (defun org-babel-parse-multiple-vars (header-arguments)
  1253. "Expand multiple variable assignments behind a single :var keyword.
  1254. This allows expression of multiple variables with one :var as
  1255. shown below.
  1256. #+PROPERTY: var foo=1, bar=2"
  1257. (let (results)
  1258. (mapc (lambda (pair)
  1259. (if (eq (car pair) :var)
  1260. (mapcar (lambda (v) (push (cons :var (org-babel-trim v)) results))
  1261. (org-babel-join-splits-near-ch
  1262. 61 (org-babel-balanced-split (cdr pair) 32)))
  1263. (push pair results)))
  1264. header-arguments)
  1265. (nreverse results)))
  1266. (defun org-babel-process-params (params)
  1267. "Expand variables in PARAMS and add summary parameters."
  1268. (let* ((processed-vars (mapcar (lambda (el)
  1269. (if (consp (cdr el))
  1270. (cdr el)
  1271. (org-babel-ref-parse (cdr el))))
  1272. (org-babel-get-header params :var)))
  1273. (vars-and-names (if (and (assoc :colname-names params)
  1274. (assoc :rowname-names params))
  1275. (list processed-vars)
  1276. (org-babel-disassemble-tables
  1277. processed-vars
  1278. (cdr (assoc :hlines params))
  1279. (cdr (assoc :colnames params))
  1280. (cdr (assoc :rownames params)))))
  1281. (raw-result (or (cdr (assoc :results params)) ""))
  1282. (result-params (append
  1283. (split-string (if (stringp raw-result)
  1284. raw-result
  1285. (eval raw-result)))
  1286. (cdr (assoc :result-params params)))))
  1287. (append
  1288. (mapcar (lambda (var) (cons :var var)) (car vars-and-names))
  1289. (list
  1290. (cons :colname-names (or (cdr (assoc :colname-names params))
  1291. (cadr vars-and-names)))
  1292. (cons :rowname-names (or (cdr (assoc :rowname-names params))
  1293. (caddr vars-and-names)))
  1294. (cons :result-params result-params)
  1295. (cons :result-type (cond ((member "output" result-params) 'output)
  1296. ((member "value" result-params) 'value)
  1297. (t 'value))))
  1298. (org-babel-get-header params :var 'other))))
  1299. ;; row and column names
  1300. (defun org-babel-del-hlines (table)
  1301. "Remove all 'hlines from TABLE."
  1302. (remove 'hline table))
  1303. (defun org-babel-get-colnames (table)
  1304. "Return the column names of TABLE.
  1305. Return a cons cell, the `car' of which contains the TABLE less
  1306. colnames, and the `cdr' of which contains a list of the column
  1307. names."
  1308. (if (equal 'hline (nth 1 table))
  1309. (cons (cddr table) (car table))
  1310. (cons (cdr table) (car table))))
  1311. (defun org-babel-get-rownames (table)
  1312. "Return the row names of TABLE.
  1313. Return a cons cell, the `car' of which contains the TABLE less
  1314. colnames, and the `cdr' of which contains a list of the column
  1315. names. Note: this function removes any hlines in TABLE."
  1316. (let* ((trans (lambda (table) (apply #'mapcar* #'list table)))
  1317. (width (apply 'max
  1318. (mapcar (lambda (el) (if (listp el) (length el) 0)) table)))
  1319. (table (funcall trans (mapcar (lambda (row)
  1320. (if (not (equal row 'hline))
  1321. row
  1322. (setq row '())
  1323. (dotimes (n width)
  1324. (setq row (cons 'hline row)))
  1325. row))
  1326. table))))
  1327. (cons (mapcar (lambda (row) (if (equal (car row) 'hline) 'hline row))
  1328. (funcall trans (cdr table)))
  1329. (remove 'hline (car table)))))
  1330. (defun org-babel-put-colnames (table colnames)
  1331. "Add COLNAMES to TABLE if they exist."
  1332. (if colnames (apply 'list colnames 'hline table) table))
  1333. (defun org-babel-put-rownames (table rownames)
  1334. "Add ROWNAMES to TABLE if they exist."
  1335. (if rownames
  1336. (mapcar (lambda (row)
  1337. (if (listp row)
  1338. (cons (or (pop rownames) "") row)
  1339. row)) table)
  1340. table))
  1341. (defun org-babel-pick-name (names selector)
  1342. "Select one out of an alist of row or column names.
  1343. SELECTOR can be either a list of names in which case those names
  1344. will be returned directly, or an index into the list NAMES in
  1345. which case the indexed names will be return."
  1346. (if (listp selector)
  1347. selector
  1348. (when names
  1349. (if (and selector (symbolp selector) (not (equal t selector)))
  1350. (cdr (assoc selector names))
  1351. (if (integerp selector)
  1352. (nth (- selector 1) names)
  1353. (cdr (car (last names))))))))
  1354. (defun org-babel-disassemble-tables (vars hlines colnames rownames)
  1355. "Parse tables for further processing.
  1356. Process the variables in VARS according to the HLINES,
  1357. ROWNAMES and COLNAMES header arguments. Return a list consisting
  1358. of the vars, cnames and rnames."
  1359. (let (cnames rnames)
  1360. (list
  1361. (mapcar
  1362. (lambda (var)
  1363. (when (listp (cdr var))
  1364. (when (and (not (equal colnames "no"))
  1365. (or colnames (and (equal (nth 1 (cdr var)) 'hline)
  1366. (not (member 'hline (cddr (cdr var)))))))
  1367. (let ((both (org-babel-get-colnames (cdr var))))
  1368. (setq cnames (cons (cons (car var) (cdr both))
  1369. cnames))
  1370. (setq var (cons (car var) (car both)))))
  1371. (when (and rownames (not (equal rownames "no")))
  1372. (let ((both (org-babel-get-rownames (cdr var))))
  1373. (setq rnames (cons (cons (car var) (cdr both))
  1374. rnames))
  1375. (setq var (cons (car var) (car both)))))
  1376. (when (and hlines (not (equal hlines "yes")))
  1377. (setq var (cons (car var) (org-babel-del-hlines (cdr var))))))
  1378. var)
  1379. vars)
  1380. (reverse cnames) (reverse rnames))))
  1381. (defun org-babel-reassemble-table (table colnames rownames)
  1382. "Add column and row names to a table.
  1383. Given a TABLE and set of COLNAMES and ROWNAMES add the names
  1384. to the table for reinsertion to org-mode."
  1385. (if (listp table)
  1386. ((lambda (table)
  1387. (if (and colnames (listp (car table)) (= (length (car table))
  1388. (length colnames)))
  1389. (org-babel-put-colnames table colnames) table))
  1390. (if (and rownames (= (length table) (length rownames)))
  1391. (org-babel-put-rownames table rownames) table))
  1392. table))
  1393. (defun org-babel-where-is-src-block-head ()
  1394. "Find where the current source block begins.
  1395. Return the point at the beginning of the current source
  1396. block. Specifically at the beginning of the #+BEGIN_SRC line.
  1397. If the point is not on a source block then return nil."
  1398. (let ((initial (point)) (case-fold-search t) top bottom)
  1399. (or
  1400. (save-excursion ;; on a source name line or a #+header line
  1401. (beginning-of-line 1)
  1402. (and (or (looking-at org-babel-src-name-regexp)
  1403. (looking-at org-babel-multi-line-header-regexp))
  1404. (progn
  1405. (while (and (forward-line 1)
  1406. (or (looking-at org-babel-src-name-regexp)
  1407. (looking-at org-babel-multi-line-header-regexp))))
  1408. (looking-at org-babel-src-block-regexp))
  1409. (point)))
  1410. (save-excursion ;; on a #+begin_src line
  1411. (beginning-of-line 1)
  1412. (and (looking-at org-babel-src-block-regexp)
  1413. (point)))
  1414. (save-excursion ;; inside a src block
  1415. (and
  1416. (re-search-backward "^[ \t]*#\\+begin_src" nil t) (setq top (point))
  1417. (re-search-forward "^[ \t]*#\\+end_src" nil t) (setq bottom (point))
  1418. (< top initial) (< initial bottom)
  1419. (progn (goto-char top) (beginning-of-line 1)
  1420. (looking-at org-babel-src-block-regexp))
  1421. (point))))))
  1422. ;;;###autoload
  1423. (defun org-babel-goto-src-block-head ()
  1424. "Go to the beginning of the current code block."
  1425. (interactive)
  1426. ((lambda (head)
  1427. (if head (goto-char head) (error "Not currently in a code block")))
  1428. (org-babel-where-is-src-block-head)))
  1429. ;;;###autoload
  1430. (defun org-babel-goto-named-src-block (name)
  1431. "Go to a named source-code block."
  1432. (interactive
  1433. (let ((completion-ignore-case t)
  1434. (case-fold-search t)
  1435. (under-point (thing-at-point 'line)))
  1436. (list (org-icompleting-read
  1437. "source-block name: " (org-babel-src-block-names) nil t
  1438. (cond
  1439. ;; noweb
  1440. ((string-match (org-babel-noweb-wrap) under-point)
  1441. (let ((block-name (match-string 1 under-point)))
  1442. (string-match "[^(]*" block-name)
  1443. (match-string 0 block-name)))
  1444. ;; #+call:
  1445. ((string-match org-babel-lob-one-liner-regexp under-point)
  1446. (let ((source-info (car (org-babel-lob-get-info))))
  1447. (if (string-match "^\\([^\\[]+?\\)\\(\\[.*\\]\\)?(" source-info)
  1448. (let ((source-name (match-string 1 source-info)))
  1449. source-name))))
  1450. ;; #+results:
  1451. ((string-match (concat "#\\+" org-babel-results-keyword
  1452. "\\:\s+\\([^\\(]*\\)") under-point)
  1453. (match-string 1 under-point))
  1454. ;; symbol-at-point
  1455. ((and (thing-at-point 'symbol))
  1456. (org-babel-find-named-block (thing-at-point 'symbol))
  1457. (thing-at-point 'symbol))
  1458. (""))))))
  1459. (let ((point (org-babel-find-named-block name)))
  1460. (if point
  1461. ;; taken from `org-open-at-point'
  1462. (progn (org-mark-ring-push) (goto-char point) (org-show-context))
  1463. (message "source-code block '%s' not found in this buffer" name))))
  1464. (defun org-babel-find-named-block (name)
  1465. "Find a named source-code block.
  1466. Return the location of the source block identified by source
  1467. NAME, or nil if no such block exists. Set match data according to
  1468. org-babel-named-src-block-regexp."
  1469. (save-excursion
  1470. (let ((case-fold-search t)
  1471. (regexp (org-babel-named-src-block-regexp-for-name name)) msg)
  1472. (goto-char (point-min))
  1473. (when (or (re-search-forward regexp nil t)
  1474. (re-search-backward regexp nil t))
  1475. (match-beginning 0)))))
  1476. (defun org-babel-src-block-names (&optional file)
  1477. "Returns the names of source blocks in FILE or the current buffer."
  1478. (save-excursion
  1479. (when file (find-file file)) (goto-char (point-min))
  1480. (let ((case-fold-search t) names)
  1481. (while (re-search-forward org-babel-src-name-w-name-regexp nil t)
  1482. (setq names (cons (match-string 3) names)))
  1483. names)))
  1484. ;;;###autoload
  1485. (defun org-babel-goto-named-result (name)
  1486. "Go to a named result."
  1487. (interactive
  1488. (let ((completion-ignore-case t))
  1489. (list (org-icompleting-read "source-block name: "
  1490. (org-babel-result-names) nil t))))
  1491. (let ((point (org-babel-find-named-result name)))
  1492. (if point
  1493. ;; taken from `org-open-at-point'
  1494. (progn (goto-char point) (org-show-context))
  1495. (message "result '%s' not found in this buffer" name))))
  1496. (defun org-babel-find-named-result (name &optional point)
  1497. "Find a named result.
  1498. Return the location of the result named NAME in the current
  1499. buffer or nil if no such result exists."
  1500. (save-excursion
  1501. (let ((case-fold-search t))
  1502. (goto-char (or point (point-min)))
  1503. (catch 'is-a-code-block
  1504. (when (re-search-forward
  1505. (concat org-babel-result-regexp
  1506. "[ \t]" (regexp-quote name) "[ \t]*[\n\f\v\r]") nil t)
  1507. (when (and (string= "name" (downcase (match-string 1)))
  1508. (or (beginning-of-line 1)
  1509. (looking-at org-babel-src-block-regexp)
  1510. (looking-at org-babel-multi-line-header-regexp)))
  1511. (throw 'is-a-code-block (org-babel-find-named-result name (point))))
  1512. (beginning-of-line 0) (point))))))
  1513. (defun org-babel-result-names (&optional file)
  1514. "Returns the names of results in FILE or the current buffer."
  1515. (save-excursion
  1516. (when file (find-file file)) (goto-char (point-min))
  1517. (let ((case-fold-search t) names)
  1518. (while (re-search-forward org-babel-result-w-name-regexp nil t)
  1519. (setq names (cons (match-string 4) names)))
  1520. names)))
  1521. ;;;###autoload
  1522. (defun org-babel-next-src-block (&optional arg)
  1523. "Jump to the next source block.
  1524. With optional prefix argument ARG, jump forward ARG many source blocks."
  1525. (interactive "p")
  1526. (org-next-block arg nil org-babel-src-block-regexp))
  1527. ;;;###autoload
  1528. (defun org-babel-previous-src-block (&optional arg)
  1529. "Jump to the previous source block.
  1530. With optional prefix argument ARG, jump backward ARG many source blocks."
  1531. (interactive "p")
  1532. (org-previous-block arg org-babel-src-block-regexp))
  1533. (defvar org-babel-load-languages)
  1534. ;;;###autoload
  1535. (defun org-babel-mark-block ()
  1536. "Mark current src block."
  1537. (interactive)
  1538. ((lambda (head)
  1539. (when head
  1540. (save-excursion
  1541. (goto-char head)
  1542. (looking-at org-babel-src-block-regexp))
  1543. (push-mark (match-end 5) nil t)
  1544. (goto-char (match-beginning 5))))
  1545. (org-babel-where-is-src-block-head)))
  1546. (defun org-babel-demarcate-block (&optional arg)
  1547. "Wrap or split the code in the region or on the point.
  1548. When called from inside of a code block the current block is
  1549. split. When called from outside of a code block a new code block
  1550. is created. In both cases if the region is demarcated and if the
  1551. region is not active then the point is demarcated."
  1552. (interactive "P")
  1553. (let ((info (org-babel-get-src-block-info 'light))
  1554. (headers (progn (org-babel-where-is-src-block-head)
  1555. (match-string 4)))
  1556. (stars (concat (make-string (or (org-current-level) 1) ?*) " ")))
  1557. (if info
  1558. (mapc
  1559. (lambda (place)
  1560. (save-excursion
  1561. (goto-char place)
  1562. (let ((lang (nth 0 info))
  1563. (indent (make-string (nth 5 info) ? )))
  1564. (when (string-match "^[[:space:]]*$"
  1565. (buffer-substring (point-at-bol)
  1566. (point-at-eol)))
  1567. (delete-region (point-at-bol) (point-at-eol)))
  1568. (insert (concat
  1569. (if (looking-at "^") "" "\n")
  1570. indent "#+end_src\n"
  1571. (if arg stars indent) "\n"
  1572. indent "#+begin_src " lang
  1573. (if (> (length headers) 1)
  1574. (concat " " headers) headers)
  1575. (if (looking-at "[\n\r]")
  1576. ""
  1577. (concat "\n" (make-string (current-column) ? )))))))
  1578. (move-end-of-line 2))
  1579. (sort (if (org-region-active-p) (list (mark) (point)) (list (point))) #'>))
  1580. (let ((start (point))
  1581. (lang (org-icompleting-read "Lang: "
  1582. (mapcar (lambda (el) (symbol-name (car el)))
  1583. org-babel-load-languages)))
  1584. (body (delete-and-extract-region
  1585. (if (org-region-active-p) (mark) (point)) (point))))
  1586. (insert (concat (if (looking-at "^") "" "\n")
  1587. (if arg (concat stars "\n") "")
  1588. "#+begin_src " lang "\n"
  1589. body
  1590. (if (or (= (length body) 0)
  1591. (string-match "[\r\n]$" body)) "" "\n")
  1592. "#+end_src\n"))
  1593. (goto-char start) (move-end-of-line 1)))))
  1594. (defvar org-babel-lob-one-liner-regexp)
  1595. (defun org-babel-where-is-src-block-result (&optional insert info hash indent)
  1596. "Find where the current source block results begin.
  1597. Return the point at the beginning of the result of the current
  1598. source block. Specifically at the beginning of the results line.
  1599. If no result exists for this block then create a results line
  1600. following the source block."
  1601. (save-excursion
  1602. (let* ((case-fold-search t)
  1603. (on-lob-line (save-excursion
  1604. (beginning-of-line 1)
  1605. (looking-at org-babel-lob-one-liner-regexp)))
  1606. (inlinep (when (org-babel-get-inline-src-block-matches)
  1607. (match-end 0)))
  1608. (name (if on-lob-line
  1609. (mapconcat #'identity (butlast (org-babel-lob-get-info)) "")
  1610. (nth 4 (or info (org-babel-get-src-block-info 'light)))))
  1611. (head (unless on-lob-line (org-babel-where-is-src-block-head)))
  1612. found beg end)
  1613. (when head (goto-char head))
  1614. (org-with-wide-buffer
  1615. (setq
  1616. found ;; was there a result (before we potentially insert one)
  1617. (or
  1618. inlinep
  1619. (and
  1620. ;; named results:
  1621. ;; - return t if it is found, else return nil
  1622. ;; - if it does not need to be rebuilt, then don't set end
  1623. ;; - if it does need to be rebuilt then do set end
  1624. name (setq beg (org-babel-find-named-result name))
  1625. (prog1 beg
  1626. (when (and hash (not (string= hash (match-string 5))))
  1627. (goto-char beg) (setq end beg) ;; beginning of result
  1628. (forward-line 1)
  1629. (delete-region end (org-babel-result-end)) nil)))
  1630. (and
  1631. ;; unnamed results:
  1632. ;; - return t if it is found, else return nil
  1633. ;; - if it is found, and the hash doesn't match, delete and set end
  1634. (or on-lob-line (re-search-forward "^[ \t]*#\\+end_src" nil t))
  1635. (progn (end-of-line 1)
  1636. (if (eobp) (insert "\n") (forward-char 1))
  1637. (setq end (point))
  1638. (or (and (not name)
  1639. (progn ;; unnamed results line already exists
  1640. (re-search-forward "[^ \f\t\n\r\v]" nil t)
  1641. (beginning-of-line 1)
  1642. (looking-at
  1643. (concat org-babel-result-regexp "\n")))
  1644. (let ((this-hash (match-string 5)))
  1645. (prog1 (point)
  1646. ;; must remove and rebuild if hash!=old-hash
  1647. (if (and hash (not (string= hash this-hash)))
  1648. (prog1 nil
  1649. (forward-line 1)
  1650. (delete-region
  1651. end (org-babel-result-end)))
  1652. (setq end nil)))))))))))
  1653. (if (not (and insert end)) found
  1654. (goto-char end)
  1655. (unless beg
  1656. (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
  1657. (insert (concat
  1658. (when (wholenump indent) (make-string indent ? ))
  1659. "#+" org-babel-results-keyword
  1660. (when hash
  1661. (if org-babel-hash-show-time
  1662. (concat
  1663. "["(format-time-string "<%Y-%m-%d %H:%M:%S>")" "hash"]")
  1664. (concat "["hash"]")))
  1665. ":"
  1666. (when name (concat " " name)) "\n"))
  1667. (unless beg (insert "\n") (backward-char))
  1668. (beginning-of-line 0)
  1669. (if hash (org-babel-hide-hash))
  1670. (point)))))
  1671. (defvar org-block-regexp)
  1672. (defun org-babel-read-result ()
  1673. "Read the result at `point' into emacs-lisp."
  1674. (let ((case-fold-search t) result-string)
  1675. (cond
  1676. ((org-at-table-p) (org-babel-read-table))
  1677. ((org-at-item-p) (org-babel-read-list))
  1678. ((looking-at org-bracket-link-regexp) (org-babel-read-link))
  1679. ((looking-at org-block-regexp) (org-babel-trim (match-string 4)))
  1680. ((looking-at "^[ \t]*: ")
  1681. (setq result-string
  1682. (org-babel-trim
  1683. (mapconcat (lambda (line)
  1684. (if (and (> (length line) 1)
  1685. (string-match "^[ \t]*: \\(.+\\)" line))
  1686. (match-string 1 line)
  1687. line))
  1688. (split-string
  1689. (buffer-substring
  1690. (point) (org-babel-result-end)) "[\r\n]+")
  1691. "\n")))
  1692. (or (org-babel-number-p result-string) result-string))
  1693. ((looking-at org-babel-result-regexp)
  1694. (save-excursion (forward-line 1) (org-babel-read-result))))))
  1695. (defun org-babel-read-table ()
  1696. "Read the table at `point' into emacs-lisp."
  1697. (mapcar (lambda (row)
  1698. (if (and (symbolp row) (equal row 'hline)) row
  1699. (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval)) row)))
  1700. (org-table-to-lisp)))
  1701. (defun org-babel-read-list ()
  1702. "Read the list at `point' into emacs-lisp."
  1703. (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval))
  1704. (mapcar #'cadr (cdr (org-list-parse-list)))))
  1705. (defvar org-link-types-re)
  1706. (defun org-babel-read-link ()
  1707. "Read the link at `point' into emacs-lisp.
  1708. If the path of the link is a file path it is expanded using
  1709. `expand-file-name'."
  1710. (let* ((case-fold-search t)
  1711. (raw (and (looking-at org-bracket-link-regexp)
  1712. (org-no-properties (match-string 1))))
  1713. (type (and (string-match org-link-types-re raw)
  1714. (match-string 1 raw))))
  1715. (cond
  1716. ((not type) (expand-file-name raw))
  1717. ((string= type "file")
  1718. (and (string-match "file\\(.*\\):\\(.+\\)" raw)
  1719. (expand-file-name (match-string 2 raw))))
  1720. (t raw))))
  1721. (defun org-babel-format-result (result &optional sep)
  1722. "Format RESULT for writing to file."
  1723. (let ((echo-res (lambda (r) (if (stringp r) r (format "%S" r)))))
  1724. (if (listp result)
  1725. ;; table result
  1726. (orgtbl-to-generic
  1727. result (list :sep (or sep "\t") :fmt echo-res))
  1728. ;; scalar result
  1729. (funcall echo-res result))))
  1730. (defun org-babel-insert-result
  1731. (result &optional result-params info hash indent lang)
  1732. "Insert RESULT into the current buffer.
  1733. By default RESULT is inserted after the end of the
  1734. current source block. With optional argument RESULT-PARAMS
  1735. controls insertion of results in the org-mode file.
  1736. RESULT-PARAMS can take the following values:
  1737. replace - (default option) insert results after the source block
  1738. replacing any previously inserted results
  1739. silent -- no results are inserted into the Org-mode buffer but
  1740. the results are echoed to the minibuffer and are
  1741. ingested by Emacs (a potentially time consuming
  1742. process)
  1743. file ---- the results are interpreted as a file path, and are
  1744. inserted into the buffer using the Org-mode file syntax
  1745. list ---- the results are interpreted as an Org-mode list.
  1746. raw ----- results are added directly to the Org-mode file. This
  1747. is a good option if you code block will output org-mode
  1748. formatted text.
  1749. drawer -- results are added directly to the Org-mode file as with
  1750. \"raw\", but are wrapped in a RESULTS drawer, allowing
  1751. them to later be replaced or removed automatically.
  1752. org ----- results are added inside of a \"#+BEGIN_SRC org\" block.
  1753. They are not comma-escaped when inserted, but Org syntax
  1754. here will be discarded when exporting the file.
  1755. html ---- results are added inside of a #+BEGIN_HTML block. This
  1756. is a good option if you code block will output html
  1757. formatted text.
  1758. latex --- results are added inside of a #+BEGIN_LATEX block.
  1759. This is a good option if you code block will output
  1760. latex formatted text.
  1761. code ---- the results are extracted in the syntax of the source
  1762. code of the language being evaluated and are added
  1763. inside of a #+BEGIN_SRC block with the source-code
  1764. language set appropriately. Note this relies on the
  1765. optional LANG argument."
  1766. (if (stringp result)
  1767. (progn
  1768. (setq result (org-no-properties result))
  1769. (when (member "file" result-params)
  1770. (setq result (org-babel-result-to-file
  1771. result (when (assoc :file-desc (nth 2 info))
  1772. (or (cdr (assoc :file-desc (nth 2 info)))
  1773. result))))))
  1774. (unless (listp result) (setq result (format "%S" result))))
  1775. (if (and result-params (member "silent" result-params))
  1776. (progn
  1777. (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
  1778. result)
  1779. (save-excursion
  1780. (let* ((inlinep
  1781. (save-excursion
  1782. (when (or (org-babel-get-inline-src-block-matches)
  1783. (org-babel-get-lob-one-liner-matches))
  1784. (goto-char (match-end 0))
  1785. (insert (if (listp result) "\n" " "))
  1786. (point))))
  1787. (existing-result (unless inlinep
  1788. (org-babel-where-is-src-block-result
  1789. t info hash indent)))
  1790. (results-switches
  1791. (cdr (assoc :results_switches (nth 2 info))))
  1792. (visible-beg (copy-marker (point-min)))
  1793. (visible-end (copy-marker (point-max)))
  1794. ;; When results exist outside of the current visible
  1795. ;; region of the buffer, be sure to widen buffer to
  1796. ;; update them.
  1797. (outside-scope-p (and existing-result
  1798. (or (> visible-beg existing-result)
  1799. (<= visible-end existing-result))))
  1800. beg end)
  1801. (when (and (stringp result) ; ensure results end in a newline
  1802. (not inlinep)
  1803. (> (length result) 0)
  1804. (not (or (string-equal (substring result -1) "\n")
  1805. (string-equal (substring result -1) "\r"))))
  1806. (setq result (concat result "\n")))
  1807. (unwind-protect
  1808. (progn
  1809. (when outside-scope-p (widen))
  1810. (if (not existing-result)
  1811. (setq beg (or inlinep (point)))
  1812. (goto-char existing-result)
  1813. (save-excursion
  1814. (re-search-forward "#" nil t)
  1815. (setq indent (- (current-column) 1)))
  1816. (forward-line 1)
  1817. (setq beg (point))
  1818. (cond
  1819. ((member "replace" result-params)
  1820. (delete-region (point) (org-babel-result-end)))
  1821. ((member "append" result-params)
  1822. (goto-char (org-babel-result-end)) (setq beg (point-marker)))
  1823. ((member "prepend" result-params)))) ; already there
  1824. (setq results-switches
  1825. (if results-switches (concat " " results-switches) ""))
  1826. (let ((wrap (lambda (start finish &optional no-escape)
  1827. (goto-char end) (insert (concat finish "\n"))
  1828. (goto-char beg) (insert (concat start "\n"))
  1829. (unless no-escape
  1830. (org-escape-code-in-region (min (point) end) end))
  1831. (goto-char end) (goto-char (point-at-eol))
  1832. (setq end (point-marker))))
  1833. (proper-list-p (lambda (it) (and (listp it) (null (cdr (last it)))))))
  1834. ;; insert results based on type
  1835. (cond
  1836. ;; do nothing for an empty result
  1837. ((null result))
  1838. ;; insert a list if preferred
  1839. ((member "list" result-params)
  1840. (insert
  1841. (org-babel-trim
  1842. (org-list-to-generic
  1843. (cons 'unordered
  1844. (mapcar
  1845. (lambda (el) (list nil (if (stringp el) el (format "%S" el))))
  1846. (if (listp result) result (list result))))
  1847. '(:splicep nil :istart "- " :iend "\n")))
  1848. "\n"))
  1849. ;; assume the result is a table if it's not a string
  1850. ((funcall proper-list-p result)
  1851. (goto-char beg)
  1852. (insert (concat (orgtbl-to-orgtbl
  1853. (if (or (eq 'hline (car result))
  1854. (and (listp (car result))
  1855. (listp (cdr (car result)))))
  1856. result (list result))
  1857. '(:fmt (lambda (cell) (format "%s" cell)))) "\n"))
  1858. (goto-char beg) (when (org-at-table-p) (org-table-align)))
  1859. ((and (listp result) (not (funcall proper-list-p result)))
  1860. (insert (format "%s\n" result)))
  1861. ((member "file" result-params)
  1862. (when inlinep (goto-char inlinep))
  1863. (insert result))
  1864. (t (goto-char beg) (insert result)))
  1865. (when (funcall proper-list-p result) (goto-char (org-table-end)))
  1866. (setq end (point-marker))
  1867. ;; possibly wrap result
  1868. (cond
  1869. ((assoc :wrap (nth 2 info))
  1870. (let ((name (or (cdr (assoc :wrap (nth 2 info))) "RESULTS")))
  1871. (funcall wrap (concat "#+BEGIN_" name)
  1872. (concat "#+END_" (car (org-split-string name))))))
  1873. ((member "html" result-params)
  1874. (funcall wrap "#+BEGIN_HTML" "#+END_HTML"))
  1875. ((member "latex" result-params)
  1876. (funcall wrap "#+BEGIN_LaTeX" "#+END_LaTeX"))
  1877. ((member "org" result-params)
  1878. (funcall wrap "#+BEGIN_SRC org" "#+END_SRC"))
  1879. ((member "code" result-params)
  1880. (funcall wrap (format "#+BEGIN_SRC %s%s" (or lang "none") results-switches)
  1881. "#+END_SRC"))
  1882. ((member "raw" result-params)
  1883. (goto-char beg) (if (org-at-table-p) (org-cycle)))
  1884. ((or (member "drawer" result-params)
  1885. ;; Stay backward compatible with <7.9.2
  1886. (member "wrap" result-params))
  1887. (funcall wrap ":RESULTS:" ":END:" 'no-escape))
  1888. ((and (not (funcall proper-list-p result))
  1889. (not (member "file" result-params)))
  1890. (org-babel-examplize-region beg end results-switches)
  1891. (setq end (point)))))
  1892. ;; possibly indent the results to match the #+results line
  1893. (when (and (not inlinep) (numberp indent) indent (> indent 0)
  1894. ;; in this case `table-align' does the work for us
  1895. (not (and (listp result)
  1896. (member "append" result-params))))
  1897. (indent-rigidly beg end indent))
  1898. (if (null result)
  1899. (if (member "value" result-params)
  1900. (message "Code block returned no value.")
  1901. (message "Code block produced no output."))
  1902. (message "Code block evaluation complete.")))
  1903. (when outside-scope-p (narrow-to-region visible-beg visible-end))
  1904. (set-marker visible-beg nil)
  1905. (set-marker visible-end nil))))))
  1906. (defun org-babel-remove-result (&optional info)
  1907. "Remove the result of the current source block."
  1908. (interactive)
  1909. (let ((location (org-babel-where-is-src-block-result nil info)) start)
  1910. (when location
  1911. (setq start (- location 1))
  1912. (save-excursion
  1913. (goto-char location) (forward-line 1)
  1914. (delete-region start (org-babel-result-end))))))
  1915. (defun org-babel-result-end ()
  1916. "Return the point at the end of the current set of results."
  1917. (save-excursion
  1918. (cond
  1919. ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
  1920. ((org-at-item-p) (let* ((struct (org-list-struct))
  1921. (prvs (org-list-prevs-alist struct)))
  1922. (org-list-get-list-end (point-at-bol) struct prvs)))
  1923. ((let ((case-fold-search t)) (looking-at "^\\([ \t]*\\):results:"))
  1924. (progn (re-search-forward (concat "^" (match-string 1) ":END:"))
  1925. (forward-char 1) (point)))
  1926. (t
  1927. (let ((case-fold-search t))
  1928. (if (looking-at (concat "[ \t]*#\\+begin_\\([^ \t\n\r]+\\)"))
  1929. (progn (re-search-forward (concat "[ \t]*#\\+end_" (match-string 1))
  1930. nil t)
  1931. (forward-char 1))
  1932. (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
  1933. (forward-line 1))))
  1934. (point)))))
  1935. (defun org-babel-result-to-file (result &optional description)
  1936. "Convert RESULT into an `org-mode' link with optional DESCRIPTION.
  1937. If the `default-directory' is different from the containing
  1938. file's directory then expand relative links."
  1939. (when (stringp result)
  1940. (format "[[file:%s]%s]"
  1941. (if (and default-directory
  1942. buffer-file-name
  1943. (not (string= (expand-file-name default-directory)
  1944. (expand-file-name
  1945. (file-name-directory buffer-file-name)))))
  1946. (expand-file-name result default-directory)
  1947. result)
  1948. (if description (concat "[" description "]") ""))))
  1949. (defvar org-babel-capitalize-examplize-region-markers nil
  1950. "Make true to capitalize begin/end example markers inserted by code blocks.")
  1951. (defun org-babel-examplize-region (beg end &optional results-switches)
  1952. "Comment out region using the inline '==' or ': ' org example quote."
  1953. (interactive "*r")
  1954. (let ((chars-between (lambda (b e)
  1955. (not (string-match "^[\\s]*$" (buffer-substring b e)))))
  1956. (maybe-cap (lambda (str) (if org-babel-capitalize-examplize-region-markers
  1957. (upcase str) str))))
  1958. (if (or (funcall chars-between (save-excursion (goto-char beg) (point-at-bol)) beg)
  1959. (funcall chars-between end (save-excursion (goto-char end) (point-at-eol))))
  1960. (save-excursion
  1961. (goto-char beg)
  1962. (insert (format "=%s=" (prog1 (buffer-substring beg end)
  1963. (delete-region beg end)))))
  1964. (let ((size (count-lines beg end)))
  1965. (save-excursion
  1966. (cond ((= size 0)) ; do nothing for an empty result
  1967. ((< size org-babel-min-lines-for-block-output)
  1968. (goto-char beg)
  1969. (dotimes (n size)
  1970. (beginning-of-line 1) (insert ": ") (forward-line 1)))
  1971. (t
  1972. (goto-char beg)
  1973. (insert (if results-switches
  1974. (format "%s%s\n"
  1975. (funcall maybe-cap "#+begin_example")
  1976. results-switches)
  1977. (funcall maybe-cap "#+begin_example\n")))
  1978. (if (markerp end) (goto-char end) (forward-char (- end beg)))
  1979. (insert (funcall maybe-cap "#+end_example\n")))))))))
  1980. (defun org-babel-update-block-body (new-body)
  1981. "Update the body of the current code block to NEW-BODY."
  1982. (if (not (org-babel-where-is-src-block-head))
  1983. (error "Not in a source block")
  1984. (save-match-data
  1985. (replace-match (concat (org-babel-trim new-body) "\n") nil t nil 5))
  1986. (indent-rigidly (match-beginning 5) (match-end 5) 2)))
  1987. (defun org-babel-merge-params (&rest plists)
  1988. "Combine all parameter association lists in PLISTS.
  1989. Later elements of PLISTS override the values of previous elements.
  1990. This takes into account some special considerations for certain
  1991. parameters when merging lists."
  1992. (let* ((results-exclusive-groups
  1993. (mapcar (lambda (group) (mapcar #'symbol-name group))
  1994. (cdr (assoc 'results org-babel-common-header-args-w-values))))
  1995. (exports-exclusive-groups
  1996. (mapcar (lambda (group) (mapcar #'symbol-name group))
  1997. (cdr (assoc 'exports org-babel-common-header-args-w-values))))
  1998. (variable-index 0)
  1999. (e-merge (lambda (exclusive-groups &rest result-params)
  2000. ;; maintain exclusivity of mutually exclusive parameters
  2001. (let (output)
  2002. (mapc (lambda (new-params)
  2003. (mapc (lambda (new-param)
  2004. (mapc (lambda (exclusive-group)
  2005. (when (member new-param exclusive-group)
  2006. (mapcar (lambda (excluded-param)
  2007. (setq output
  2008. (delete
  2009. excluded-param
  2010. output)))
  2011. exclusive-group)))
  2012. exclusive-groups)
  2013. (setq output (org-uniquify
  2014. (cons new-param output))))
  2015. new-params))
  2016. result-params)
  2017. output)))
  2018. params results exports tangle noweb cache vars shebang comments padline)
  2019. (mapc
  2020. (lambda (plist)
  2021. (mapc
  2022. (lambda (pair)
  2023. (case (car pair)
  2024. (:var
  2025. (let ((name (if (listp (cdr pair))
  2026. (cadr pair)
  2027. (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
  2028. (cdr pair))
  2029. (intern (match-string 1 (cdr pair)))))))
  2030. (if name
  2031. (setq vars
  2032. (append
  2033. (if (member name (mapcar #'car vars))
  2034. (delq nil
  2035. (mapcar
  2036. (lambda (p)
  2037. (unless (equal (car p) name) p))
  2038. vars))
  2039. vars)
  2040. (list (cons name pair))))
  2041. ;; if no name is given and we already have named variables
  2042. ;; then assign to named variables in order
  2043. (if (and vars (nth variable-index vars))
  2044. (prog1 (setf (cddr (nth variable-index vars))
  2045. (concat (symbol-name
  2046. (car (nth variable-index vars)))
  2047. "=" (cdr pair)))
  2048. (incf variable-index))
  2049. (error "Variable \"%s\" must be assigned a default value"
  2050. (cdr pair))))))
  2051. (:results
  2052. (setq results (funcall e-merge results-exclusive-groups
  2053. results
  2054. (split-string
  2055. (let ((r (cdr pair)))
  2056. (if (stringp r) r (eval r)))))))
  2057. (:file
  2058. (when (cdr pair)
  2059. (setq results (funcall e-merge results-exclusive-groups
  2060. results '("file")))
  2061. (unless (or (member "both" exports)
  2062. (member "none" exports)
  2063. (member "code" exports))
  2064. (setq exports (funcall e-merge exports-exclusive-groups
  2065. exports '("results"))))
  2066. (setq params (cons pair (assq-delete-all (car pair) params)))))
  2067. (:exports
  2068. (setq exports (funcall e-merge exports-exclusive-groups
  2069. exports (split-string (cdr pair)))))
  2070. (:tangle ;; take the latest -- always overwrite
  2071. (setq tangle (or (list (cdr pair)) tangle)))
  2072. (:noweb
  2073. (setq noweb (funcall e-merge
  2074. '(("yes" "no" "tangle" "no-export"
  2075. "strip-export" "eval"))
  2076. noweb
  2077. (split-string (or (cdr pair) "")))))
  2078. (:cache
  2079. (setq cache (funcall e-merge '(("yes" "no")) cache
  2080. (split-string (or (cdr pair) "")))))
  2081. (:padline
  2082. (setq padline (funcall e-merge '(("yes" "no")) padline
  2083. (split-string (or (cdr pair) "")))))
  2084. (:shebang ;; take the latest -- always overwrite
  2085. (setq shebang (or (list (cdr pair)) shebang)))
  2086. (:comments
  2087. (setq comments (funcall e-merge '(("yes" "no")) comments
  2088. (split-string (or (cdr pair) "")))))
  2089. (t ;; replace: this covers e.g. :session
  2090. (setq params (cons pair (assq-delete-all (car pair) params))))))
  2091. plist))
  2092. plists)
  2093. (setq vars (reverse vars))
  2094. (while vars (setq params (cons (cons :var (cddr (pop vars))) params)))
  2095. (mapc
  2096. (lambda (hd)
  2097. (let ((key (intern (concat ":" (symbol-name hd))))
  2098. (val (eval hd)))
  2099. (setf params (cons (cons key (mapconcat 'identity val " ")) params))))
  2100. '(results exports tangle noweb padline cache shebang comments))
  2101. params))
  2102. (defvar org-babel-use-quick-and-dirty-noweb-expansion nil
  2103. "Set to true to use regular expressions to expand noweb references.
  2104. This results in much faster noweb reference expansion but does
  2105. not properly allow code blocks to inherit the \":noweb-ref\"
  2106. header argument from buffer or subtree wide properties.")
  2107. (defun org-babel-noweb-p (params context)
  2108. "Check if PARAMS require expansion in CONTEXT.
  2109. CONTEXT may be one of :tangle, :export or :eval."
  2110. (let* (intersect
  2111. (intersect (lambda (as bs)
  2112. (when as
  2113. (if (member (car as) bs)
  2114. (car as)
  2115. (funcall intersect (cdr as) bs))))))
  2116. (funcall intersect (case context
  2117. (:tangle '("yes" "tangle" "no-export" "strip-export"))
  2118. (:eval '("yes" "no-export" "strip-export" "eval"))
  2119. (:export '("yes")))
  2120. (split-string (or (cdr (assoc :noweb params)) "")))))
  2121. (defun org-babel-expand-noweb-references (&optional info parent-buffer)
  2122. "Expand Noweb references in the body of the current source code block.
  2123. For example the following reference would be replaced with the
  2124. body of the source-code block named 'example-block'.
  2125. <<example-block>>
  2126. Note that any text preceding the <<foo>> construct on a line will
  2127. be interposed between the lines of the replacement text. So for
  2128. example if <<foo>> is placed behind a comment, then the entire
  2129. replacement text will also be commented.
  2130. This function must be called from inside of the buffer containing
  2131. the source-code block which holds BODY.
  2132. In addition the following syntax can be used to insert the
  2133. results of evaluating the source-code block named 'example-block'.
  2134. <<example-block()>>
  2135. Any optional arguments can be passed to example-block by placing
  2136. the arguments inside the parenthesis following the convention
  2137. defined by `org-babel-lob'. For example
  2138. <<example-block(a=9)>>
  2139. would set the value of argument \"a\" equal to \"9\". Note that
  2140. these arguments are not evaluated in the current source-code
  2141. block but are passed literally to the \"example-block\"."
  2142. (let* ((parent-buffer (or parent-buffer (current-buffer)))
  2143. (info (or info (org-babel-get-src-block-info)))
  2144. (lang (nth 0 info))
  2145. (body (nth 1 info))
  2146. (ob-nww-start org-babel-noweb-wrap-start)
  2147. (ob-nww-end org-babel-noweb-wrap-end)
  2148. (comment (string= "noweb" (cdr (assoc :comments (nth 2 info)))))
  2149. (rx-prefix (concat "\\(" org-babel-src-name-regexp "\\|"
  2150. ":noweb-ref[ \t]+" "\\)"))
  2151. (new-body "")
  2152. (nb-add (lambda (text) (setq new-body (concat new-body text))))
  2153. (c-wrap (lambda (text)
  2154. (with-temp-buffer
  2155. (funcall (intern (concat lang "-mode")))
  2156. (comment-region (point) (progn (insert text) (point)))
  2157. (org-babel-trim (buffer-string)))))
  2158. index source-name evaluate prefix blocks-in-buffer)
  2159. (with-temp-buffer
  2160. (org-set-local 'org-babel-noweb-wrap-start ob-nww-start)
  2161. (org-set-local 'org-babel-noweb-wrap-end ob-nww-end)
  2162. (insert body) (goto-char (point-min))
  2163. (setq index (point))
  2164. (while (and (re-search-forward (org-babel-noweb-wrap) nil t))
  2165. (save-match-data (setf source-name (match-string 1)))
  2166. (save-match-data (setq evaluate (string-match "\(.*\)" source-name)))
  2167. (save-match-data
  2168. (setq prefix
  2169. (buffer-substring (match-beginning 0)
  2170. (save-excursion
  2171. (beginning-of-line 1) (point)))))
  2172. ;; add interval to new-body (removing noweb reference)
  2173. (goto-char (match-beginning 0))
  2174. (funcall nb-add (buffer-substring index (point)))
  2175. (goto-char (match-end 0))
  2176. (setq index (point))
  2177. (funcall nb-add
  2178. (with-current-buffer parent-buffer
  2179. (save-restriction
  2180. (widen)
  2181. (mapconcat ;; interpose PREFIX between every line
  2182. #'identity
  2183. (split-string
  2184. (if evaluate
  2185. (let ((raw (org-babel-ref-resolve source-name)))
  2186. (if (stringp raw) raw (format "%S" raw)))
  2187. (or
  2188. ;; retrieve from the library of babel
  2189. (nth 2 (assoc (intern source-name)
  2190. org-babel-library-of-babel))
  2191. ;; return the contents of headlines literally
  2192. (save-excursion
  2193. (when (org-babel-ref-goto-headline-id source-name)
  2194. (org-babel-ref-headline-body)))
  2195. ;; find the expansion of reference in this buffer
  2196. (let ((rx (concat rx-prefix source-name "[ \t\n]"))
  2197. expansion)
  2198. (save-excursion
  2199. (goto-char (point-min))
  2200. (if org-babel-use-quick-and-dirty-noweb-expansion
  2201. (while (re-search-forward rx nil t)
  2202. (let* ((i (org-babel-get-src-block-info 'light))
  2203. (body (org-babel-expand-noweb-references i))
  2204. (sep (or (cdr (assoc :noweb-sep (nth 2 i)))
  2205. "\n"))
  2206. (full (if comment
  2207. ((lambda (cs)
  2208. (concat (funcall c-wrap (car cs)) "\n"
  2209. body "\n"
  2210. (funcall c-wrap (cadr cs))))
  2211. (org-babel-tangle-comment-links i))
  2212. body)))
  2213. (setq expansion (cons sep (cons full expansion)))))
  2214. (org-babel-map-src-blocks nil
  2215. (let ((i (org-babel-get-src-block-info 'light)))
  2216. (when (equal (or (cdr (assoc :noweb-ref (nth 2 i)))
  2217. (nth 4 i))
  2218. source-name)
  2219. (let* ((body (org-babel-expand-noweb-references i))
  2220. (sep (or (cdr (assoc :noweb-sep (nth 2 i)))
  2221. "\n"))
  2222. (full (if comment
  2223. ((lambda (cs)
  2224. (concat (funcall c-wrap (car cs)) "\n"
  2225. body "\n"
  2226. (funcall c-wrap (cadr cs))))
  2227. (org-babel-tangle-comment-links i))
  2228. body)))
  2229. (setq expansion
  2230. (cons sep (cons full expansion)))))))))
  2231. (and expansion
  2232. (mapconcat #'identity (nreverse (cdr expansion)) "")))
  2233. ;; possibly raise an error if named block doesn't exist
  2234. (if (member lang org-babel-noweb-error-langs)
  2235. (error "%s" (concat
  2236. (org-babel-noweb-wrap source-name)
  2237. "could not be resolved (see "
  2238. "`org-babel-noweb-error-langs')"))
  2239. "")))
  2240. "[\n\r]") (concat "\n" prefix))))))
  2241. (funcall nb-add (buffer-substring index (point-max))))
  2242. new-body))
  2243. (defun org-babel-script-escape (str &optional force)
  2244. "Safely convert tables into elisp lists."
  2245. (let (in-single in-double out)
  2246. ((lambda (escaped) (condition-case nil (org-babel-read escaped) (error escaped)))
  2247. (if (or force
  2248. (and (stringp str)
  2249. (> (length str) 2)
  2250. (or (and (string-equal "[" (substring str 0 1))
  2251. (string-equal "]" (substring str -1)))
  2252. (and (string-equal "{" (substring str 0 1))
  2253. (string-equal "}" (substring str -1)))
  2254. (and (string-equal "(" (substring str 0 1))
  2255. (string-equal ")" (substring str -1))))))
  2256. (org-babel-read
  2257. (concat
  2258. "'"
  2259. (progn
  2260. (mapc
  2261. (lambda (ch)
  2262. (setq
  2263. out
  2264. (case ch
  2265. (91 (if (or in-double in-single) ; [
  2266. (cons 91 out)
  2267. (cons 40 out)))
  2268. (93 (if (or in-double in-single) ; ]
  2269. (cons 93 out)
  2270. (cons 41 out)))
  2271. (123 (if (or in-double in-single) ; {
  2272. (cons 123 out)
  2273. (cons 40 out)))
  2274. (125 (if (or in-double in-single) ; }
  2275. (cons 125 out)
  2276. (cons 41 out)))
  2277. (44 (if (or in-double in-single) ; ,
  2278. (cons 44 out) (cons 32 out)))
  2279. (39 (if in-double ; '
  2280. (cons 39 out)
  2281. (setq in-single (not in-single)) (cons 34 out)))
  2282. (34 (if in-single ; "
  2283. (append (list 34 32) out)
  2284. (setq in-double (not in-double)) (cons 34 out)))
  2285. (t (cons ch out)))))
  2286. (string-to-list str))
  2287. (apply #'string (reverse out)))))
  2288. str))))
  2289. (defun org-babel-read (cell &optional inhibit-lisp-eval)
  2290. "Convert the string value of CELL to a number if appropriate.
  2291. Otherwise if cell looks like lisp (meaning it starts with a
  2292. \"(\", \"'\", \"`\" or a \"[\") then read it as lisp, otherwise
  2293. return it unmodified as a string. Optional argument NO-LISP-EVAL
  2294. inhibits lisp evaluation for situations in which is it not
  2295. appropriate."
  2296. (if (and (stringp cell) (not (equal cell "")))
  2297. (or (org-babel-number-p cell)
  2298. (if (and (not inhibit-lisp-eval)
  2299. (member (substring cell 0 1) '("(" "'" "`" "[")))
  2300. (eval (read cell))
  2301. (if (string= (substring cell 0 1) "\"")
  2302. (read cell)
  2303. (progn (set-text-properties 0 (length cell) nil cell) cell))))
  2304. cell))
  2305. (defun org-babel-number-p (string)
  2306. "If STRING represents a number return its value."
  2307. (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string)
  2308. (= (length (substring string (match-beginning 0)
  2309. (match-end 0)))
  2310. (length string)))
  2311. (string-to-number string)))
  2312. (defun org-babel-import-elisp-from-file (file-name &optional separator)
  2313. "Read the results located at FILE-NAME into an elisp table.
  2314. If the table is trivial, then return it as a scalar."
  2315. (let (result)
  2316. (save-window-excursion
  2317. (with-temp-buffer
  2318. (condition-case err
  2319. (progn
  2320. (org-table-import file-name separator)
  2321. (delete-file file-name)
  2322. (setq result (mapcar (lambda (row)
  2323. (mapcar #'org-babel-string-read row))
  2324. (org-table-to-lisp))))
  2325. (error (message "Error reading results: %s" err) nil)))
  2326. (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
  2327. (if (consp (car result))
  2328. (if (null (cdr (car result)))
  2329. (caar result)
  2330. result)
  2331. (car result))
  2332. result))))
  2333. (defun org-babel-string-read (cell)
  2334. "Strip nested \"s from around strings."
  2335. (org-babel-read (or (and (stringp cell)
  2336. (string-match "\\\"\\(.+\\)\\\"" cell)
  2337. (match-string 1 cell))
  2338. cell) t))
  2339. (defun org-babel-chomp (string &optional regexp)
  2340. "Strip trailing spaces and carriage returns from STRING.
  2341. Default regexp used is \"[ \f\t\n\r\v]\" but can be
  2342. overwritten by specifying a regexp as a second argument."
  2343. (let ((regexp (or regexp "[ \f\t\n\r\v]")))
  2344. (while (and (> (length string) 0)
  2345. (string-match regexp (substring string -1)))
  2346. (setq string (substring string 0 -1)))
  2347. string))
  2348. (defun org-babel-trim (string &optional regexp)
  2349. "Strip leading and trailing spaces and carriage returns from STRING.
  2350. Like `org-babel-chomp' only it runs on both the front and back
  2351. of the string."
  2352. (org-babel-chomp (org-reverse-string
  2353. (org-babel-chomp (org-reverse-string string) regexp))
  2354. regexp))
  2355. (defvar org-babel-org-babel-call-process-region-original nil)
  2356. (defun org-babel-tramp-handle-call-process-region
  2357. (start end program &optional delete buffer display &rest args)
  2358. "Use Tramp to handle `call-process-region'.
  2359. Fixes a bug in `tramp-handle-call-process-region'."
  2360. (if (and (featurep 'tramp) (file-remote-p default-directory))
  2361. (let ((tmpfile (tramp-compat-make-temp-file "")))
  2362. (write-region start end tmpfile)
  2363. (when delete (delete-region start end))
  2364. (unwind-protect
  2365. ;; (apply 'call-process program tmpfile buffer display args)
  2366. ;; bug in tramp
  2367. (apply 'process-file program tmpfile buffer display args)
  2368. (delete-file tmpfile)))
  2369. ;; org-babel-call-process-region-original is the original emacs
  2370. ;; definition. It is in scope from the let binding in
  2371. ;; org-babel-execute-src-block
  2372. (apply org-babel-call-process-region-original
  2373. start end program delete buffer display args)))
  2374. (defun org-babel-local-file-name (file)
  2375. "Return the local name component of FILE."
  2376. (if (file-remote-p file)
  2377. (let (localname)
  2378. (with-parsed-tramp-file-name file nil
  2379. localname))
  2380. file))
  2381. (defun org-babel-process-file-name (name &optional no-quote-p)
  2382. "Prepare NAME to be used in an external process.
  2383. If NAME specifies a remote location, the remote portion of the
  2384. name is removed, since in that case the process will be executing
  2385. remotely. The file name is then processed by `expand-file-name'.
  2386. Unless second argument NO-QUOTE-P is non-nil, the file name is
  2387. additionally processed by `shell-quote-argument'"
  2388. ((lambda (f) (if no-quote-p f (shell-quote-argument f)))
  2389. (expand-file-name (org-babel-local-file-name name))))
  2390. (defvar org-babel-temporary-directory)
  2391. (unless (or noninteractive (boundp 'org-babel-temporary-directory))
  2392. (defvar org-babel-temporary-directory
  2393. (or (and (boundp 'org-babel-temporary-directory)
  2394. (file-exists-p org-babel-temporary-directory)
  2395. org-babel-temporary-directory)
  2396. (make-temp-file "babel-" t))
  2397. "Directory to hold temporary files created to execute code blocks.
  2398. Used by `org-babel-temp-file'. This directory will be removed on
  2399. Emacs shutdown."))
  2400. (defmacro org-babel-result-cond (result-params scalar-form &rest table-forms)
  2401. "Call the code to parse raw string results according to RESULT-PARAMS."
  2402. (declare (indent 1)
  2403. (debug (form form &rest form)))
  2404. `(unless (member "none" ,result-params)
  2405. (if (or (member "scalar" ,result-params)
  2406. (member "verbatim" ,result-params)
  2407. (member "html" ,result-params)
  2408. (member "code" ,result-params)
  2409. (member "pp" ,result-params)
  2410. (and (member "output" ,result-params)
  2411. (not (member "table" ,result-params))))
  2412. ,scalar-form
  2413. ,@table-forms)))
  2414. (defun org-babel-temp-file (prefix &optional suffix)
  2415. "Create a temporary file in the `org-babel-temporary-directory'.
  2416. Passes PREFIX and SUFFIX directly to `make-temp-file' with the
  2417. value of `temporary-file-directory' temporarily set to the value
  2418. of `org-babel-temporary-directory'."
  2419. (let ((temporary-file-directory
  2420. (if (file-remote-p default-directory)
  2421. (concat (file-remote-p default-directory) "/tmp")
  2422. (or (and (boundp 'org-babel-temporary-directory)
  2423. (file-exists-p org-babel-temporary-directory)
  2424. org-babel-temporary-directory)
  2425. temporary-file-directory))))
  2426. (make-temp-file prefix nil suffix)))
  2427. (defun org-babel-remove-temporary-directory ()
  2428. "Remove `org-babel-temporary-directory' on Emacs shutdown."
  2429. (when (and (boundp 'org-babel-temporary-directory)
  2430. (file-exists-p org-babel-temporary-directory))
  2431. ;; taken from `delete-directory' in files.el
  2432. (condition-case nil
  2433. (progn
  2434. (mapc (lambda (file)
  2435. ;; This test is equivalent to
  2436. ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
  2437. ;; but more efficient
  2438. (if (eq t (car (file-attributes file)))
  2439. (delete-directory file)
  2440. (delete-file file)))
  2441. ;; We do not want to delete "." and "..".
  2442. (directory-files org-babel-temporary-directory 'full
  2443. "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
  2444. (delete-directory org-babel-temporary-directory))
  2445. (error
  2446. (message "Failed to remove temporary Org-babel directory %s"
  2447. (if (boundp 'org-babel-temporary-directory)
  2448. org-babel-temporary-directory
  2449. "[directory not defined]"))))))
  2450. (add-hook 'kill-emacs-hook 'org-babel-remove-temporary-directory)
  2451. (provide 'ob-core)
  2452. ;; Local variables:
  2453. ;; generated-autoload-file: "org-loaddefs.el"
  2454. ;; End:
  2455. ;;; ob-core.el ends here