ob-core.el 120 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220
  1. ;;; ob-core.el --- Working with Code Blocks -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2009-2020 Free Software Foundation, Inc.
  3. ;; Authors: Eric Schulte
  4. ;; Dan Davison
  5. ;; Keywords: literate programming, reproducible research
  6. ;; Homepage: https://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 <https://www.gnu.org/licenses/>.
  18. ;;; Code:
  19. (require 'cl-lib)
  20. (require 'ob-eval)
  21. (require 'org-macs)
  22. (require 'org-compat)
  23. (defconst org-babel-exeext
  24. (if (memq system-type '(windows-nt cygwin))
  25. ".exe"
  26. nil))
  27. (defvar org-babel-library-of-babel)
  28. (defvar org-edit-src-content-indentation)
  29. (defvar org-link-file-path-type)
  30. (defvar org-src-lang-modes)
  31. (defvar org-src-preserve-indentation)
  32. (defvar org-babel-tangle-uncomment-comments)
  33. (declare-function org-at-item-p "org-list" ())
  34. (declare-function org-at-table-p "org" (&optional table-type))
  35. (declare-function org-babel-lob-execute-maybe "ob-lob" ())
  36. (declare-function org-babel-ref-goto-headline-id "ob-ref" (id))
  37. (declare-function org-babel-ref-headline-body "ob-ref" ())
  38. (declare-function org-babel-ref-parse "ob-ref" (assignment))
  39. (declare-function org-babel-ref-resolve "ob-ref" (ref))
  40. (declare-function org-babel-ref-split-args "ob-ref" (arg-string))
  41. (declare-function org-babel-tangle-comment-links "ob-tangle" (&optional info))
  42. (declare-function org-current-level "org" ())
  43. (declare-function org-cycle "org" (&optional arg))
  44. (declare-function org-edit-src-code "org-src" (&optional code edit-buffer-name))
  45. (declare-function org-edit-src-exit "org-src" ())
  46. (declare-function org-element-at-point "org-element" ())
  47. (declare-function org-element-context "org-element" (&optional element))
  48. (declare-function org-element-normalize-string "org-element" (s))
  49. (declare-function org-element-property "org-element" (property element))
  50. (declare-function org-element-type "org-element" (element))
  51. (declare-function org-entry-get "org" (pom property &optional inherit literal-nil))
  52. (declare-function org-escape-code-in-region "org-src" (beg end))
  53. (declare-function org-forward-heading-same-level "org" (arg &optional invisible-ok))
  54. (declare-function org-in-commented-heading-p "org" (&optional no-inheritance))
  55. (declare-function org-indent-line "org" ())
  56. (declare-function org-list-get-list-end "org-list" (item struct prevs))
  57. (declare-function org-list-prevs-alist "org-list" (struct))
  58. (declare-function org-list-struct "org-list" ())
  59. (declare-function org-list-to-generic "org-list" (LIST PARAMS))
  60. (declare-function org-list-to-lisp "org-list" (&optional delete))
  61. (declare-function org-macro-escape-arguments "org-macro" (&rest args))
  62. (declare-function org-mark-ring-push "org" (&optional pos buffer))
  63. (declare-function org-narrow-to-subtree "org" ())
  64. (declare-function org-next-block "org" (arg &optional backward block-regexp))
  65. (declare-function org-open-at-point "org" (&optional in-emacs reference-buffer))
  66. (declare-function org-previous-block "org" (arg &optional block-regexp))
  67. (declare-function org-show-context "org" (&optional key))
  68. (declare-function org-src-coderef-format "org-src" (&optional element))
  69. (declare-function org-src-coderef-regexp "org-src" (fmt &optional label))
  70. (declare-function org-src-get-lang-mode "org-src" (lang))
  71. (declare-function org-table-align "org-table" ())
  72. (declare-function org-table-end "org-table" (&optional table-type))
  73. (declare-function org-table-import "org-table" (file arg))
  74. (declare-function org-table-to-lisp "org-table" (&optional txt))
  75. (declare-function org-unescape-code-in-string "org-src" (s))
  76. (declare-function orgtbl-to-generic "org-table" (table params))
  77. (declare-function orgtbl-to-orgtbl "org-table" (table params))
  78. (declare-function tramp-compat-make-temp-file "tramp-compat" (filename &optional dir-flag))
  79. (defgroup org-babel nil
  80. "Code block evaluation and management in `org-mode' documents."
  81. :tag "Babel"
  82. :group 'org)
  83. (defcustom org-confirm-babel-evaluate t
  84. "Confirm before evaluation.
  85. \\<org-mode-map>\
  86. Require confirmation before interactively evaluating code
  87. blocks in Org buffers. The default value of this variable is t,
  88. meaning confirmation is required for any code block evaluation.
  89. This variable can be set to nil to inhibit any future
  90. confirmation requests. This variable can also be set to a
  91. function which takes two arguments the language of the code block
  92. and the body of the code block. Such a function should then
  93. return a non-nil value if the user should be prompted for
  94. execution or nil if no prompt is required.
  95. Warning: Disabling confirmation may result in accidental
  96. evaluation of potentially harmful code. It may be advisable
  97. remove code block execution from `\\[org-ctrl-c-ctrl-c]' \
  98. as further protection
  99. against accidental code block evaluation. The
  100. `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
  101. remove code block execution from the `\\[org-ctrl-c-ctrl-c]' keybinding."
  102. :group 'org-babel
  103. :version "24.1"
  104. :type '(choice boolean function))
  105. ;; don't allow this variable to be changed through file settings
  106. (put 'org-confirm-babel-evaluate 'safe-local-variable (lambda (x) (eq x t)))
  107. (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
  108. "\\<org-mode-map>\
  109. Remove code block evaluation from the `\\[org-ctrl-c-ctrl-c]' key binding."
  110. :group 'org-babel
  111. :version "24.1"
  112. :type 'boolean)
  113. (defcustom org-babel-results-keyword "RESULTS"
  114. "Keyword used to name results generated by code blocks.
  115. It should be \"RESULTS\". However any capitalization may be
  116. used."
  117. :group 'org-babel
  118. :version "24.4"
  119. :package-version '(Org . "8.0")
  120. :type 'string
  121. :safe (lambda (v)
  122. (and (stringp v)
  123. (eq (compare-strings "RESULTS" nil nil v nil nil t)
  124. t))))
  125. (defcustom org-babel-noweb-wrap-start "<<"
  126. "String used to begin a noweb reference in a code block.
  127. See also `org-babel-noweb-wrap-end'."
  128. :group 'org-babel
  129. :type 'string)
  130. (defcustom org-babel-noweb-wrap-end ">>"
  131. "String used to end a noweb reference in a code block.
  132. See also `org-babel-noweb-wrap-start'."
  133. :group 'org-babel
  134. :type 'string)
  135. (defcustom org-babel-inline-result-wrap "=%s="
  136. "Format string used to wrap inline results.
  137. This string must include a \"%s\" which will be replaced by the results."
  138. :group 'org-babel
  139. :type 'string)
  140. (put 'org-babel-inline-result-wrap
  141. 'safe-local-variable
  142. (lambda (value)
  143. (and (stringp value)
  144. (string-match-p "%s" value))))
  145. (defcustom org-babel-hash-show-time nil
  146. "Non-nil means show the time the code block was evaluated in the result hash."
  147. :group 'org-babel
  148. :type 'boolean
  149. :package-version '(Org . "9.0")
  150. :safe #'booleanp)
  151. (defcustom org-babel-uppercase-example-markers nil
  152. "When non-nil, begin/end example markers will be inserted in upper case."
  153. :group 'org-babel
  154. :type 'boolean
  155. :version "26.1"
  156. :package-version '(Org . "9.1")
  157. :safe #'booleanp)
  158. (defun org-babel-noweb-wrap (&optional regexp)
  159. "Return regexp matching a Noweb reference.
  160. Match any reference, or only those matching REGEXP, if non-nil.
  161. When matching, reference is stored in match group 1."
  162. (concat (regexp-quote org-babel-noweb-wrap-start)
  163. (or regexp "\\([^ \t\n]\\(?:.*?[^ \t\n]\\)?\\)")
  164. (regexp-quote org-babel-noweb-wrap-end)))
  165. (defvar org-babel-src-name-regexp
  166. "^[ \t]*#\\+name:[ \t]*"
  167. "Regular expression used to match a source name line.")
  168. (defvar org-babel-multi-line-header-regexp
  169. "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
  170. "Regular expression used to match multi-line header arguments.")
  171. (defvar org-babel-src-block-regexp
  172. (concat
  173. ;; (1) indentation (2) lang
  174. "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
  175. ;; (3) switches
  176. "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
  177. ;; (4) header arguments
  178. "\\([^\n]*\\)\n"
  179. ;; (5) body
  180. "\\([^\000]*?\n\\)??[ \t]*#\\+end_src")
  181. "Regexp used to identify code blocks.")
  182. (defun org-babel--get-vars (params)
  183. "Return the babel variable assignments in PARAMS.
  184. PARAMS is a quasi-alist of header args, which may contain
  185. multiple entries for the key `:var'. This function returns a
  186. list of the cdr of all the `:var' entries."
  187. (mapcar #'cdr
  188. (cl-remove-if-not (lambda (x) (eq (car x) :var)) params)))
  189. (defvar org-babel-exp-reference-buffer nil
  190. "Buffer containing original contents of the exported buffer.
  191. This is used by Babel to resolve references in source blocks.
  192. Its value is dynamically bound during export.")
  193. (defun org-babel-check-confirm-evaluate (info)
  194. "Check whether INFO allows code block evaluation.
  195. Returns nil if evaluation is disallowed, t if it is
  196. unconditionally allowed, and the symbol `query' if the user
  197. should be asked whether to allow evaluation."
  198. (let* ((headers (nth 2 info))
  199. (eval (or (cdr (assq :eval headers))
  200. (when (assq :noeval headers) "no")))
  201. (eval-no (member eval '("no" "never")))
  202. (export org-babel-exp-reference-buffer)
  203. (eval-no-export (and export (member eval '("no-export" "never-export"))))
  204. (noeval (or eval-no eval-no-export))
  205. (query (or (equal eval "query")
  206. (and export (equal eval "query-export"))
  207. (if (functionp org-confirm-babel-evaluate)
  208. (funcall org-confirm-babel-evaluate
  209. ;; Language, code block body.
  210. (nth 0 info)
  211. (if (org-babel-noweb-p headers :eval)
  212. (org-babel-expand-noweb-references info)
  213. (nth 1 info)))
  214. org-confirm-babel-evaluate))))
  215. (cond
  216. (noeval nil)
  217. (query 'query)
  218. (t t))))
  219. (defun org-babel-check-evaluate (info)
  220. "Check if code block INFO should be evaluated.
  221. Do not query the user, but do display an informative message if
  222. evaluation is blocked. Returns non-nil if evaluation is not blocked."
  223. (let ((confirmed (org-babel-check-confirm-evaluate info)))
  224. (unless confirmed
  225. (message "Evaluation of this %s code block%sis disabled."
  226. (nth 0 info)
  227. (let ((name (nth 4 info)))
  228. (if name (format " (%s) " name) " "))))
  229. confirmed))
  230. ;; Dynamically scoped for asynchronous export.
  231. (defvar org-babel-confirm-evaluate-answer-no)
  232. (defun org-babel-confirm-evaluate (info)
  233. "Confirm evaluation of the code block INFO.
  234. This query can also be suppressed by setting the value of
  235. `org-confirm-babel-evaluate' to nil, in which case all future
  236. interactive code block evaluations will proceed without any
  237. confirmation from the user.
  238. Note disabling confirmation may result in accidental evaluation
  239. of potentially harmful code.
  240. The variable `org-babel-confirm-evaluate-answer-no' is used by
  241. the async export process, which requires a non-interactive
  242. environment, to override this check."
  243. (let* ((evalp (org-babel-check-confirm-evaluate info))
  244. (lang (nth 0 info))
  245. (name (nth 4 info))
  246. (name-string (if name (format " (%s) " name) " ")))
  247. (pcase evalp
  248. (`nil nil)
  249. (`t t)
  250. (`query (or
  251. (and (not (bound-and-true-p
  252. org-babel-confirm-evaluate-answer-no))
  253. (yes-or-no-p
  254. (format "Evaluate this %s code block%son your system? "
  255. lang name-string)))
  256. (progn
  257. (message "Evaluation of this %s code block%sis aborted."
  258. lang name-string)
  259. nil)))
  260. (x (error "Unexpected value `%s' from `org-babel-check-confirm-evaluate'" x)))))
  261. ;;;###autoload
  262. (defun org-babel-execute-safely-maybe ()
  263. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  264. (org-babel-execute-maybe)))
  265. ;;;###autoload
  266. (defun org-babel-execute-maybe ()
  267. (interactive)
  268. (or (org-babel-execute-src-block-maybe)
  269. (org-babel-lob-execute-maybe)))
  270. (defmacro org-babel-when-in-src-block (&rest body)
  271. "Execute BODY if point is in a source block and return t.
  272. Otherwise do nothing and return nil."
  273. `(if (memq (org-element-type (org-element-context))
  274. '(inline-src-block src-block))
  275. (progn
  276. ,@body
  277. t)
  278. nil))
  279. (defun org-babel-execute-src-block-maybe ()
  280. "Conditionally execute a source block.
  281. Detect if this is context for a Babel src-block and if so
  282. then run `org-babel-execute-src-block'."
  283. (interactive)
  284. (org-babel-when-in-src-block
  285. (org-babel-eval-wipe-error-buffer)
  286. (org-babel-execute-src-block current-prefix-arg)))
  287. ;;;###autoload
  288. (defun org-babel-view-src-block-info ()
  289. "Display information on the current source block.
  290. This includes header arguments, language and name, and is largely
  291. a window into the `org-babel-get-src-block-info' function."
  292. (interactive)
  293. (let ((info (org-babel-get-src-block-info 'light))
  294. (full (lambda (it) (> (length it) 0)))
  295. (printf (lambda (fmt &rest args) (princ (apply #'format fmt args)))))
  296. (when info
  297. (with-help-window (help-buffer)
  298. (let ((name (nth 4 info))
  299. (lang (nth 0 info))
  300. (switches (nth 3 info))
  301. (header-args (nth 2 info)))
  302. (when name (funcall printf "Name: %s\n" name))
  303. (when lang (funcall printf "Lang: %s\n" lang))
  304. (funcall printf "Properties:\n")
  305. (funcall printf "\t:header-args \t%s\n" (org-entry-get (point) "header-args" t))
  306. (funcall printf "\t:header-args:%s \t%s\n" lang (org-entry-get (point) (concat "header-args:" lang) t))
  307. (when (funcall full switches) (funcall printf "Switches: %s\n" switches))
  308. (funcall printf "Header Arguments:\n")
  309. (dolist (pair (sort header-args
  310. (lambda (a b) (string< (symbol-name (car a))
  311. (symbol-name (car b))))))
  312. (when (funcall full (format "%s" (cdr pair)))
  313. (funcall printf "\t%S%s\t%s\n"
  314. (car pair)
  315. (if (> (length (format "%S" (car pair))) 7) "" "\t")
  316. (cdr pair)))))))))
  317. ;;;###autoload
  318. (defun org-babel-expand-src-block-maybe ()
  319. "Conditionally expand a source block.
  320. Detect if this is context for an org-babel src-block and if so
  321. then run `org-babel-expand-src-block'."
  322. (interactive)
  323. (org-babel-when-in-src-block
  324. (org-babel-expand-src-block current-prefix-arg)))
  325. ;;;###autoload
  326. (defun org-babel-load-in-session-maybe ()
  327. "Conditionally load a source block in a session.
  328. Detect if this is context for an org-babel src-block and if so
  329. then run `org-babel-load-in-session'."
  330. (interactive)
  331. (org-babel-when-in-src-block
  332. (org-babel-load-in-session current-prefix-arg)))
  333. (add-hook 'org-metaup-hook 'org-babel-load-in-session-maybe)
  334. ;;;###autoload
  335. (defun org-babel-pop-to-session-maybe ()
  336. "Conditionally pop to a session.
  337. Detect if this is context for an org-babel src-block and if so
  338. then run `org-babel-switch-to-session'."
  339. (interactive)
  340. (org-babel-when-in-src-block
  341. (org-babel-switch-to-session current-prefix-arg)))
  342. (add-hook 'org-metadown-hook 'org-babel-pop-to-session-maybe)
  343. (defconst org-babel-common-header-args-w-values
  344. '((cache . ((no yes)))
  345. (cmdline . :any)
  346. (colnames . ((nil no yes)))
  347. (comments . ((no link yes org both noweb)))
  348. (dir . :any)
  349. (eval . ((yes no no-export strip-export never-export eval never
  350. query)))
  351. (exports . ((code results both none)))
  352. (epilogue . :any)
  353. (file . :any)
  354. (file-desc . :any)
  355. (file-ext . :any)
  356. (hlines . ((no yes)))
  357. (mkdirp . ((yes no)))
  358. (no-expand)
  359. (noeval)
  360. (noweb . ((yes no tangle no-export strip-export)))
  361. (noweb-ref . :any)
  362. (noweb-sep . :any)
  363. (output-dir . :any)
  364. (padline . ((yes no)))
  365. (post . :any)
  366. (prologue . :any)
  367. (results . ((file list vector table scalar verbatim)
  368. (raw html latex org code pp drawer link graphics)
  369. (replace silent none append prepend)
  370. (output value)))
  371. (rownames . ((no yes)))
  372. (sep . :any)
  373. (session . :any)
  374. (shebang . :any)
  375. (tangle . ((tangle yes no :any)))
  376. (tangle-mode . ((#o755 #o555 #o444 :any)))
  377. (var . :any)
  378. (wrap . :any)))
  379. (defconst org-babel-header-arg-names
  380. (mapcar #'car org-babel-common-header-args-w-values)
  381. "Common header arguments used by org-babel.
  382. Note that individual languages may define their own language
  383. specific header arguments as well.")
  384. (defconst org-babel-safe-header-args
  385. '(:cache :colnames :comments :exports :epilogue :hlines :noeval
  386. :noweb :noweb-ref :noweb-sep :padline :prologue :rownames
  387. :sep :session :tangle :wrap
  388. (:eval . ("never" "query"))
  389. (:results . (lambda (str) (not (string-match "file" str)))))
  390. "A list of safe header arguments for babel source blocks.
  391. The list can have entries of the following forms:
  392. - :ARG -> :ARG is always a safe header arg
  393. - (:ARG . (VAL1 VAL2 ...)) -> :ARG is safe as a header arg if it is
  394. `equal' to one of the VALs.
  395. - (:ARG . FN) -> :ARG is safe as a header arg if the function FN
  396. returns non-nil. FN is passed one
  397. argument, the value of the header arg
  398. (as a string).")
  399. (defmacro org-babel-header-args-safe-fn (safe-list)
  400. "Return a function that determines whether a list of header args are safe.
  401. Intended usage is:
  402. \(put \\='org-babel-default-header-args \\='safe-local-variable
  403. (org-babel-header-args-safe-p org-babel-safe-header-args)
  404. This allows org-babel languages to extend the list of safe values for
  405. their `org-babel-default-header-args:foo' variable.
  406. For the format of SAFE-LIST, see `org-babel-safe-header-args'."
  407. `(lambda (value)
  408. (and (listp value)
  409. (cl-every
  410. (lambda (pair)
  411. (and (consp pair)
  412. (org-babel-one-header-arg-safe-p pair ,safe-list)))
  413. value))))
  414. (defvar org-babel-default-header-args
  415. '((:session . "none") (:results . "replace") (:exports . "code")
  416. (:cache . "no") (:noweb . "no") (:hlines . "no") (:tangle . "no"))
  417. "Default arguments to use when evaluating a source block.")
  418. (put 'org-babel-default-header-args 'safe-local-variable
  419. (org-babel-header-args-safe-fn org-babel-safe-header-args))
  420. (defvar org-babel-default-inline-header-args
  421. '((:session . "none") (:results . "replace")
  422. (:exports . "results") (:hlines . "yes"))
  423. "Default arguments to use when evaluating an inline source block.")
  424. (put 'org-babel-default-inline-header-args 'safe-local-variable
  425. (org-babel-header-args-safe-fn org-babel-safe-header-args))
  426. (defconst org-babel-name-regexp
  427. (format "^[ \t]*#\\+%s:[ \t]*"
  428. ;; FIXME: TBLNAME is for backward compatibility.
  429. (regexp-opt '("NAME" "TBLNAME")))
  430. "Regexp matching a NAME keyword.")
  431. (defconst org-babel-result-regexp
  432. (rx (seq bol
  433. (zero-or-more (any "\t "))
  434. "#+results"
  435. (opt "["
  436. ;; Time stamp part.
  437. (opt "("
  438. (= 4 digit) (= 2 "-" (= 2 digit))
  439. " "
  440. (= 2 digit) (= 2 ":" (= 2 digit))
  441. ") ")
  442. ;; SHA1 hash.
  443. (group (one-or-more hex-digit))
  444. "]")
  445. ":"
  446. (zero-or-more (any "\t "))))
  447. "Regular expression used to match result lines.
  448. If the results are associated with a hash key then the hash will
  449. be saved in match group 1.")
  450. (defconst org-babel-result-w-name-regexp
  451. (concat org-babel-result-regexp "\\(?9:[^ \t\n\r\v\f]+\\)")
  452. "Regexp matching a RESULTS keyword with a name.
  453. Name is saved in match group 9.")
  454. (defvar org-babel-min-lines-for-block-output 10
  455. "The minimum number of lines for block output.
  456. If number of lines of output is equal to or exceeds this
  457. value, the output is placed in a #+begin_example...#+end_example
  458. block. Otherwise the output is marked as literal by inserting
  459. colons at the starts of the lines. This variable only takes
  460. effect if the :results output option is in effect.")
  461. (defvar org-babel-noweb-error-all-langs nil
  462. "Raise errors when noweb references don't resolve.
  463. Also see `org-babel-noweb-error-langs' to control noweb errors on
  464. a language by language bases.")
  465. (defvar org-babel-noweb-error-langs nil
  466. "Languages for which Babel will raise literate programming errors.
  467. List of languages for which errors should be raised when the
  468. source code block satisfying a noweb reference in this language
  469. can not be resolved. Also see `org-babel-noweb-error-all-langs'
  470. to raise errors for all languages.")
  471. (defvar org-babel-hash-show 4
  472. "Number of initial characters to show of a hidden results hash.")
  473. (defvar org-babel-after-execute-hook nil
  474. "Hook for functions to be called after `org-babel-execute-src-block'")
  475. (defun org-babel-named-src-block-regexp-for-name (&optional name)
  476. "Generate a regexp used to match a source block named NAME.
  477. If NAME is nil, match any name. Matched name is then put in
  478. match group 9. Other match groups are defined in
  479. `org-babel-src-block-regexp'."
  480. (concat org-babel-src-name-regexp
  481. (concat (if name (regexp-quote name) "\\(?9:.*?\\)") "[ \t]*" )
  482. "\\(?:\n[ \t]*#\\+\\S-+:.*\\)*?"
  483. "\n"
  484. (substring org-babel-src-block-regexp 1)))
  485. (defun org-babel-named-data-regexp-for-name (name)
  486. "Generate a regexp used to match data named NAME."
  487. (concat org-babel-name-regexp (regexp-quote name) "[ \t]*$"))
  488. (defun org-babel--normalize-body (datum)
  489. "Normalize body for element or object DATUM.
  490. DATUM is a source block element or an inline source block object.
  491. Remove final newline character and spurious indentation."
  492. (let* ((value (org-element-property :value datum))
  493. (body (if (string-suffix-p "\n" value)
  494. (substring value 0 -1)
  495. value)))
  496. (cond ((eq (org-element-type datum) 'inline-src-block)
  497. ;; Newline characters and indentation in an inline
  498. ;; src-block are not meaningful, since they could come from
  499. ;; some paragraph filling. Treat them as a white space.
  500. (replace-regexp-in-string "\n[ \t]*" " " body))
  501. ((or org-src-preserve-indentation
  502. (org-element-property :preserve-indent datum))
  503. body)
  504. (t (org-remove-indentation body)))))
  505. ;;; functions
  506. (defvar org-babel-current-src-block-location nil
  507. "Marker pointing to the source block currently being executed.
  508. This may also point to a call line or an inline code block. If
  509. multiple blocks are being executed (e.g., in chained execution
  510. through use of the :var header argument) this marker points to
  511. the outer-most code block.")
  512. (defvar *this*)
  513. (defun org-babel-get-src-block-info (&optional light datum)
  514. "Extract information from a source block or inline source block.
  515. When optional argument LIGHT is non-nil, Babel does not resolve
  516. remote variable references; a process which could likely result
  517. in the execution of other code blocks, and do not evaluate Lisp
  518. values in parameters.
  519. By default, consider the block at point. However, when optional
  520. argument DATUM is provided, extract information from that parsed
  521. object instead.
  522. Return nil if point is not on a source block. Otherwise, return
  523. a list with the following pattern:
  524. (language body arguments switches name start coderef)"
  525. (let* ((datum (or datum (org-element-context)))
  526. (type (org-element-type datum))
  527. (inline (eq type 'inline-src-block)))
  528. (when (memq type '(inline-src-block src-block))
  529. (let* ((lang (org-element-property :language datum))
  530. (lang-headers (intern
  531. (concat "org-babel-default-header-args:" lang)))
  532. (name (org-element-property :name datum))
  533. (info
  534. (list
  535. lang
  536. (org-babel--normalize-body datum)
  537. (apply #'org-babel-merge-params
  538. (if inline org-babel-default-inline-header-args
  539. org-babel-default-header-args)
  540. (and (boundp lang-headers) (eval lang-headers t))
  541. (append
  542. ;; If DATUM is provided, make sure we get node
  543. ;; properties applicable to its location within
  544. ;; the document.
  545. (org-with-point-at (org-element-property :begin datum)
  546. (org-babel-params-from-properties lang light))
  547. (mapcar (lambda (h)
  548. (org-babel-parse-header-arguments h light))
  549. (cons (org-element-property :parameters datum)
  550. (org-element-property :header datum)))))
  551. (or (org-element-property :switches datum) "")
  552. name
  553. (org-element-property (if inline :begin :post-affiliated)
  554. datum)
  555. (and (not inline) (org-src-coderef-format datum)))))
  556. (unless light
  557. (setf (nth 2 info) (org-babel-process-params (nth 2 info))))
  558. (setf (nth 2 info) (org-babel-generate-file-param name (nth 2 info)))
  559. info))))
  560. ;;;###autoload
  561. (defun org-babel-execute-src-block (&optional arg info params)
  562. "Execute the current source code block.
  563. Insert the results of execution into the buffer. Source code
  564. execution and the collection and formatting of results can be
  565. controlled through a variety of header arguments.
  566. With prefix argument ARG, force re-execution even if an existing
  567. result cached in the buffer would otherwise have been returned.
  568. Optionally supply a value for INFO in the form returned by
  569. `org-babel-get-src-block-info'.
  570. Optionally supply a value for PARAMS which will be merged with
  571. the header arguments specified at the front of the source code
  572. block."
  573. (interactive)
  574. (let* ((org-babel-current-src-block-location
  575. (or org-babel-current-src-block-location
  576. (nth 5 info)
  577. (org-babel-where-is-src-block-head)))
  578. (info (if info (copy-tree info) (org-babel-get-src-block-info))))
  579. ;; Merge PARAMS with INFO before considering source block
  580. ;; evaluation since both could disagree.
  581. (cl-callf org-babel-merge-params (nth 2 info) params)
  582. (when (org-babel-check-evaluate info)
  583. (cl-callf org-babel-process-params (nth 2 info))
  584. (let* ((params (nth 2 info))
  585. (cache (let ((c (cdr (assq :cache params))))
  586. (and (not arg) c (string= "yes" c))))
  587. (new-hash (and cache (org-babel-sha1-hash info :eval)))
  588. (old-hash (and cache (org-babel-current-result-hash)))
  589. (current-cache (and new-hash (equal new-hash old-hash))))
  590. (cond
  591. (current-cache
  592. (save-excursion ;Return cached result.
  593. (goto-char (org-babel-where-is-src-block-result nil info))
  594. (forward-line)
  595. (skip-chars-forward " \t")
  596. (let ((result (org-babel-read-result)))
  597. (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
  598. result)))
  599. ((org-babel-confirm-evaluate info)
  600. (let* ((lang (nth 0 info))
  601. (result-params (cdr (assq :result-params params)))
  602. ;; Expand noweb references in BODY and remove any
  603. ;; coderef.
  604. (body
  605. (let ((coderef (nth 6 info))
  606. (expand
  607. (if (org-babel-noweb-p params :eval)
  608. (org-babel-expand-noweb-references info)
  609. (nth 1 info))))
  610. (if (not coderef) expand
  611. (replace-regexp-in-string
  612. (org-src-coderef-regexp coderef) "" expand nil nil 1))))
  613. (dir (cdr (assq :dir params)))
  614. (mkdirp (cdr (assq :mkdirp params)))
  615. (default-directory
  616. (cond
  617. ((not dir) default-directory)
  618. ((member mkdirp '("no" "nil" nil))
  619. (file-name-as-directory (expand-file-name dir)))
  620. (t
  621. (let ((d (file-name-as-directory (expand-file-name dir))))
  622. (make-directory d 'parents)
  623. d))))
  624. (cmd (intern (concat "org-babel-execute:" lang)))
  625. result)
  626. (unless (fboundp cmd)
  627. (error "No org-babel-execute function for %s!" lang))
  628. (message "executing %s code block%s..."
  629. (capitalize lang)
  630. (let ((name (nth 4 info)))
  631. (if name (format " (%s)" name) "")))
  632. (if (member "none" result-params)
  633. (progn (funcall cmd body params)
  634. (message "result silenced"))
  635. (setq result
  636. (let ((r (funcall cmd body params)))
  637. (if (and (eq (cdr (assq :result-type params)) 'value)
  638. (or (member "vector" result-params)
  639. (member "table" result-params))
  640. (not (listp r)))
  641. (list (list r))
  642. r)))
  643. (let ((file (and (member "file" result-params)
  644. (cdr (assq :file params)))))
  645. ;; If non-empty result and :file then write to :file.
  646. (when file
  647. ;; If `:results' are special types like `link' or
  648. ;; `graphics', don't write result to `:file'. Only
  649. ;; insert a link to `:file'.
  650. (when (and result
  651. (not (or (member "link" result-params)
  652. (member "graphics" result-params))))
  653. (with-temp-file file
  654. (insert (org-babel-format-result
  655. result
  656. (cdr (assq :sep params))))))
  657. (setq result file))
  658. ;; Possibly perform post process provided its
  659. ;; appropriate. Dynamically bind "*this*" to the
  660. ;; actual results of the block.
  661. (let ((post (cdr (assq :post params))))
  662. (when post
  663. (let ((*this* (if (not file) result
  664. (org-babel-result-to-file
  665. file
  666. (let ((desc (assq :file-desc params)))
  667. (and desc (or (cdr desc) result)))))))
  668. (setq result (org-babel-ref-resolve post))
  669. (when file
  670. (setq result-params (remove "file" result-params))))))
  671. (org-babel-insert-result
  672. result result-params info new-hash lang)))
  673. (run-hooks 'org-babel-after-execute-hook)
  674. result)))))))
  675. (defun org-babel-expand-body:generic (body params &optional var-lines)
  676. "Expand BODY with PARAMS.
  677. Expand a block of code with org-babel according to its header
  678. arguments. This generic implementation of body expansion is
  679. called for languages which have not defined their own specific
  680. org-babel-expand-body:lang function."
  681. (let ((pro (cdr (assq :prologue params)))
  682. (epi (cdr (assq :epilogue params))))
  683. (mapconcat #'identity
  684. (append (when pro (list pro))
  685. var-lines
  686. (list body)
  687. (when epi (list epi)))
  688. "\n")))
  689. ;;;###autoload
  690. (defun org-babel-expand-src-block (&optional _arg info params)
  691. "Expand the current source code block.
  692. Expand according to the source code block's header
  693. arguments and pop open the results in a preview buffer."
  694. (interactive)
  695. (let* ((info (or info (org-babel-get-src-block-info)))
  696. (lang (nth 0 info))
  697. (params (setf (nth 2 info)
  698. (sort (org-babel-merge-params (nth 2 info) params)
  699. (lambda (el1 el2) (string< (symbol-name (car el1))
  700. (symbol-name (car el2)))))))
  701. (body (setf (nth 1 info)
  702. (if (org-babel-noweb-p params :eval)
  703. (org-babel-expand-noweb-references info) (nth 1 info))))
  704. (expand-cmd (intern (concat "org-babel-expand-body:" lang)))
  705. (assignments-cmd (intern (concat "org-babel-variable-assignments:"
  706. lang)))
  707. (expanded
  708. (if (fboundp expand-cmd) (funcall expand-cmd body params)
  709. (org-babel-expand-body:generic
  710. body params (and (fboundp assignments-cmd)
  711. (funcall assignments-cmd params))))))
  712. (if (called-interactively-p 'any)
  713. (org-edit-src-code
  714. expanded (concat "*Org-Babel Preview " (buffer-name) "[ " lang " ]*"))
  715. expanded)))
  716. (defun org-babel-edit-distance (s1 s2)
  717. "Return the edit (levenshtein) distance between strings S1 S2."
  718. (let* ((l1 (length s1))
  719. (l2 (length s2))
  720. (dist (vconcat (mapcar (lambda (_) (make-vector (1+ l2) nil))
  721. (number-sequence 1 (1+ l1)))))
  722. (in (lambda (i j) (aref (aref dist i) j))))
  723. (setf (aref (aref dist 0) 0) 0)
  724. (dolist (j (number-sequence 1 l2))
  725. (setf (aref (aref dist 0) j) j))
  726. (dolist (i (number-sequence 1 l1))
  727. (setf (aref (aref dist i) 0) i)
  728. (dolist (j (number-sequence 1 l2))
  729. (setf (aref (aref dist i) j)
  730. (min
  731. (1+ (funcall in (1- i) j))
  732. (1+ (funcall in i (1- j)))
  733. (+ (if (equal (aref s1 (1- i)) (aref s2 (1- j))) 0 1)
  734. (funcall in (1- i) (1- j)))))))
  735. (funcall in l1 l2)))
  736. (defun org-babel-combine-header-arg-lists (original &rest others)
  737. "Combine a number of lists of header argument names and arguments."
  738. (let ((results (copy-sequence original)))
  739. (dolist (new-list others)
  740. (dolist (arg-pair new-list)
  741. (let ((header (car arg-pair)))
  742. (setq results
  743. (cons arg-pair (cl-remove-if
  744. (lambda (pair) (equal header (car pair)))
  745. results))))))
  746. results))
  747. ;;;###autoload
  748. (defun org-babel-check-src-block ()
  749. "Check for misspelled header arguments in the current code block."
  750. (interactive)
  751. ;; TODO: report malformed code block
  752. ;; TODO: report incompatible combinations of header arguments
  753. ;; TODO: report uninitialized variables
  754. (let ((too-close 2) ;; <- control closeness to report potential match
  755. (names (mapcar #'symbol-name org-babel-header-arg-names)))
  756. (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg)) 1))
  757. (and (org-babel-where-is-src-block-head)
  758. (org-babel-parse-header-arguments
  759. (org-no-properties
  760. (match-string 4))))))
  761. (dolist (name names)
  762. (when (and (not (string= header name))
  763. (<= (org-babel-edit-distance header name) too-close)
  764. (not (member header names)))
  765. (error "Supplied header \"%S\" is suspiciously close to \"%S\""
  766. header name))))
  767. (message "No suspicious header arguments found.")))
  768. ;;;###autoload
  769. (defun org-babel-insert-header-arg (&optional header-arg value)
  770. "Insert a header argument selecting from lists of common args and values."
  771. (interactive)
  772. (let* ((info (org-babel-get-src-block-info 'light))
  773. (lang (car info))
  774. (begin (nth 5 info))
  775. (lang-headers (intern (concat "org-babel-header-args:" lang)))
  776. (headers (org-babel-combine-header-arg-lists
  777. org-babel-common-header-args-w-values
  778. (when (boundp lang-headers) (eval lang-headers t))))
  779. (header-arg (or header-arg
  780. (completing-read
  781. "Header Arg: "
  782. (mapcar
  783. (lambda (header-spec) (symbol-name (car header-spec)))
  784. headers))))
  785. (vals (cdr (assoc (intern header-arg) headers)))
  786. (value (or value
  787. (cond
  788. ((eq vals :any)
  789. (read-from-minibuffer "value: "))
  790. ((listp vals)
  791. (mapconcat
  792. (lambda (group)
  793. (let ((arg (completing-read
  794. "Value: "
  795. (cons "default"
  796. (mapcar #'symbol-name group)))))
  797. (if (and arg (not (string= "default" arg)))
  798. (concat arg " ")
  799. "")))
  800. vals ""))))))
  801. (save-excursion
  802. (goto-char begin)
  803. (goto-char (point-at-eol))
  804. (unless (= (char-before (point)) ?\ ) (insert " "))
  805. (insert ":" header-arg) (when value (insert " " value)))))
  806. ;; Add support for completing-read insertion of header arguments after ":"
  807. (defun org-babel-header-arg-expand ()
  808. "Call `org-babel-enter-header-arg-w-completion' in appropriate contexts."
  809. (when (and (equal (char-before) ?\:) (org-babel-where-is-src-block-head))
  810. (org-babel-enter-header-arg-w-completion (match-string 2))))
  811. (defun org-babel-enter-header-arg-w-completion (&optional lang)
  812. "Insert header argument appropriate for LANG with completion."
  813. (let* ((lang-headers-var (intern (concat "org-babel-header-args:" lang)))
  814. (lang-headers (when (boundp lang-headers-var) (eval lang-headers-var t)))
  815. (headers-w-values (org-babel-combine-header-arg-lists
  816. org-babel-common-header-args-w-values lang-headers))
  817. (headers (mapcar #'symbol-name (mapcar #'car headers-w-values)))
  818. (header (org-completing-read "Header Arg: " headers))
  819. (args (cdr (assoc (intern header) headers-w-values)))
  820. (arg (when (and args (listp args))
  821. (org-completing-read
  822. (format "%s: " header)
  823. (mapcar #'symbol-name (apply #'append args))))))
  824. (insert (concat header " " (or arg "")))
  825. (cons header arg)))
  826. (add-hook 'org-tab-first-hook 'org-babel-header-arg-expand)
  827. ;;;###autoload
  828. (defun org-babel-load-in-session (&optional _arg info)
  829. "Load the body of the current source-code block.
  830. Evaluate the header arguments for the source block before
  831. entering the session. After loading the body this pops open the
  832. session."
  833. (interactive)
  834. (let* ((info (or info (org-babel-get-src-block-info)))
  835. (lang (nth 0 info))
  836. (params (nth 2 info))
  837. (body (if (not info)
  838. (user-error "No src code block at point")
  839. (setf (nth 1 info)
  840. (if (org-babel-noweb-p params :eval)
  841. (org-babel-expand-noweb-references info)
  842. (nth 1 info)))))
  843. (session (cdr (assq :session params)))
  844. (dir (cdr (assq :dir params)))
  845. (default-directory
  846. (or (and dir (file-name-as-directory dir)) default-directory))
  847. (cmd (intern (concat "org-babel-load-session:" lang))))
  848. (unless (fboundp cmd)
  849. (error "No org-babel-load-session function for %s!" lang))
  850. (pop-to-buffer (funcall cmd session body params))
  851. (end-of-line 1)))
  852. ;;;###autoload
  853. (defun org-babel-initiate-session (&optional arg info)
  854. "Initiate session for current code block.
  855. If called with a prefix argument then resolve any variable
  856. references in the header arguments and assign these variables in
  857. the session. Copy the body of the code block to the kill ring."
  858. (interactive "P")
  859. (let* ((info (or info (org-babel-get-src-block-info (not arg))))
  860. (lang (nth 0 info))
  861. (body (nth 1 info))
  862. (params (nth 2 info))
  863. (session (cdr (assq :session params)))
  864. (dir (cdr (assq :dir params)))
  865. (default-directory
  866. (or (and dir (file-name-as-directory dir)) default-directory))
  867. (init-cmd (intern (format "org-babel-%s-initiate-session" lang)))
  868. (prep-cmd (intern (concat "org-babel-prep-session:" lang))))
  869. (when (and (stringp session) (string= session "none"))
  870. (error "This block is not using a session!"))
  871. (unless (fboundp init-cmd)
  872. (error "No org-babel-initiate-session function for %s!" lang))
  873. (with-temp-buffer (insert (org-trim body))
  874. (copy-region-as-kill (point-min) (point-max)))
  875. (when arg
  876. (unless (fboundp prep-cmd)
  877. (error "No org-babel-prep-session function for %s!" lang))
  878. (funcall prep-cmd session params))
  879. (funcall init-cmd session params)))
  880. ;;;###autoload
  881. (defun org-babel-switch-to-session (&optional arg info)
  882. "Switch to the session of the current code block.
  883. Uses `org-babel-initiate-session' to start the session. If called
  884. with a prefix argument then this is passed on to
  885. `org-babel-initiate-session'."
  886. (interactive "P")
  887. (pop-to-buffer (org-babel-initiate-session arg info))
  888. (end-of-line 1))
  889. (defalias 'org-babel-pop-to-session 'org-babel-switch-to-session)
  890. (defvar org-src-window-setup)
  891. ;;;###autoload
  892. (defun org-babel-switch-to-session-with-code (&optional arg _info)
  893. "Switch to code buffer and display session."
  894. (interactive "P")
  895. (let ((swap-windows
  896. (lambda ()
  897. (let ((other-window-buffer (window-buffer (next-window))))
  898. (set-window-buffer (next-window) (current-buffer))
  899. (set-window-buffer (selected-window) other-window-buffer))
  900. (other-window 1)))
  901. (info (org-babel-get-src-block-info))
  902. (org-src-window-setup 'reorganize-frame))
  903. (save-excursion
  904. (org-babel-switch-to-session arg info))
  905. (org-edit-src-code)
  906. (funcall swap-windows)))
  907. ;;;###autoload
  908. (defmacro org-babel-do-in-edit-buffer (&rest body)
  909. "Evaluate BODY in edit buffer if there is a code block at point.
  910. Return t if a code block was found at point, nil otherwise."
  911. (declare (debug (body)))
  912. `(let* ((element (org-element-at-point))
  913. ;; This function is not supposed to move point. However,
  914. ;; `org-edit-src-code' always moves point back into the
  915. ;; source block. It is problematic if the point was before
  916. ;; the code, e.g., on block's opening line. In this case,
  917. ;; we want to restore this location after executing BODY.
  918. (outside-position
  919. (and (<= (line-beginning-position)
  920. (org-element-property :post-affiliated element))
  921. (point-marker)))
  922. (org-src-window-setup 'switch-invisibly))
  923. (when (and (org-babel-where-is-src-block-head element)
  924. (org-edit-src-code))
  925. (unwind-protect (progn ,@body)
  926. (org-edit-src-exit)
  927. (when outside-position (goto-char outside-position)))
  928. t)))
  929. (defun org-babel-do-key-sequence-in-edit-buffer (key)
  930. "Read key sequence and execute the command in edit buffer.
  931. Enter a key sequence to be executed in the language major-mode
  932. edit buffer. For example, TAB will alter the contents of the
  933. Org code block according to the effect of TAB in the language
  934. major mode buffer. For languages that support interactive
  935. sessions, this can be used to send code from the Org buffer
  936. to the session for evaluation using the native major mode
  937. evaluation mechanisms."
  938. (interactive "kEnter key-sequence to execute in edit buffer: ")
  939. (org-babel-do-in-edit-buffer
  940. (call-interactively
  941. (key-binding (or key (read-key-sequence nil))))))
  942. (defvar org-link-bracket-re)
  943. (defun org-babel-active-location-p ()
  944. (memq (org-element-type (save-match-data (org-element-context)))
  945. '(babel-call inline-babel-call inline-src-block src-block)))
  946. ;;;###autoload
  947. (defun org-babel-open-src-block-result (&optional re-run)
  948. "Open results of source block at point.
  949. If `point' is on a source block then open the results of the source
  950. code block, otherwise return nil. With optional prefix argument
  951. RE-RUN the source-code block is evaluated even if results already
  952. exist."
  953. (interactive "P")
  954. (pcase (org-babel-get-src-block-info 'light)
  955. (`(,_ ,_ ,arguments ,_ ,_ ,start ,_)
  956. (save-excursion
  957. ;; Go to the results, if there aren't any then run the block.
  958. (goto-char start)
  959. (goto-char (or (and (not re-run) (org-babel-where-is-src-block-result))
  960. (progn (org-babel-execute-src-block)
  961. (org-babel-where-is-src-block-result))))
  962. (end-of-line)
  963. (skip-chars-forward " \r\t\n")
  964. ;; Open the results.
  965. (if (looking-at org-link-bracket-re) (org-open-at-point)
  966. (let ((r (org-babel-format-result (org-babel-read-result)
  967. (cdr (assq :sep arguments)))))
  968. (pop-to-buffer (get-buffer-create "*Org Babel Results*"))
  969. (erase-buffer)
  970. (insert r)))
  971. t))
  972. (_ nil)))
  973. ;;;###autoload
  974. (defmacro org-babel-map-src-blocks (file &rest body)
  975. "Evaluate BODY forms on each source-block in FILE.
  976. If FILE is nil evaluate BODY forms on source blocks in current
  977. buffer. During evaluation of BODY the following local variables
  978. are set relative to the currently matched code block.
  979. full-block ------- string holding the entirety of the code block
  980. beg-block -------- point at the beginning of the code block
  981. end-block -------- point at the end of the matched code block
  982. lang ------------- string holding the language of the code block
  983. beg-lang --------- point at the beginning of the lang
  984. end-lang --------- point at the end of the lang
  985. switches --------- string holding the switches
  986. beg-switches ----- point at the beginning of the switches
  987. end-switches ----- point at the end of the switches
  988. header-args ------ string holding the header-args
  989. beg-header-args -- point at the beginning of the header-args
  990. end-header-args -- point at the end of the header-args
  991. body ------------- string holding the body of the code block
  992. beg-body --------- point at the beginning of the body
  993. end-body --------- point at the end of the body"
  994. (declare (indent 1))
  995. (let ((tempvar (make-symbol "file")))
  996. `(let* ((case-fold-search t)
  997. (,tempvar ,file)
  998. (visited-p (or (null ,tempvar)
  999. (get-file-buffer (expand-file-name ,tempvar))))
  1000. (point (point)) to-be-removed)
  1001. (save-window-excursion
  1002. (when ,tempvar (find-file ,tempvar))
  1003. (setq to-be-removed (current-buffer))
  1004. (goto-char (point-min))
  1005. (while (re-search-forward org-babel-src-block-regexp nil t)
  1006. (when (org-babel-active-location-p)
  1007. (goto-char (match-beginning 0))
  1008. (let ((full-block (match-string 0))
  1009. (beg-block (match-beginning 0))
  1010. (end-block (match-end 0))
  1011. (lang (match-string 2))
  1012. (beg-lang (match-beginning 2))
  1013. (end-lang (match-end 2))
  1014. (switches (match-string 3))
  1015. (beg-switches (match-beginning 3))
  1016. (end-switches (match-end 3))
  1017. (header-args (match-string 4))
  1018. (beg-header-args (match-beginning 4))
  1019. (end-header-args (match-end 4))
  1020. (body (match-string 5))
  1021. (beg-body (match-beginning 5))
  1022. (end-body (match-end 5)))
  1023. ;; Silence byte-compiler in case `body' doesn't use all
  1024. ;; those variables.
  1025. (ignore full-block beg-block end-block lang
  1026. beg-lang end-lang switches beg-switches
  1027. end-switches header-args beg-header-args
  1028. end-header-args body beg-body end-body)
  1029. ,@body
  1030. (goto-char end-block)))))
  1031. (unless visited-p (kill-buffer to-be-removed))
  1032. (goto-char point))))
  1033. (def-edebug-spec org-babel-map-src-blocks (form body))
  1034. ;;;###autoload
  1035. (defmacro org-babel-map-inline-src-blocks (file &rest body)
  1036. "Evaluate BODY forms on each inline source block in FILE.
  1037. If FILE is nil evaluate BODY forms on source blocks in current
  1038. buffer."
  1039. (declare (indent 1) (debug (form body)))
  1040. (org-with-gensyms (datum end point tempvar to-be-removed visitedp)
  1041. `(let* ((case-fold-search t)
  1042. (,tempvar ,file)
  1043. (,visitedp (or (null ,tempvar)
  1044. (get-file-buffer (expand-file-name ,tempvar))))
  1045. (,point (point))
  1046. ,to-be-removed)
  1047. (save-window-excursion
  1048. (when ,tempvar (find-file ,tempvar))
  1049. (setq ,to-be-removed (current-buffer))
  1050. (goto-char (point-min))
  1051. (while (re-search-forward "src_\\S-" nil t)
  1052. (let ((,datum (save-match-data (org-element-context))))
  1053. (when (eq (org-element-type ,datum) 'inline-src-block)
  1054. (goto-char (match-beginning 0))
  1055. (let ((,end (copy-marker (org-element-property :end ,datum))))
  1056. ,@body
  1057. (goto-char ,end)
  1058. (set-marker ,end nil))))))
  1059. (unless ,visitedp (kill-buffer ,to-be-removed))
  1060. (goto-char ,point))))
  1061. ;;;###autoload
  1062. (defmacro org-babel-map-call-lines (file &rest body)
  1063. "Evaluate BODY forms on each call line in FILE.
  1064. If FILE is nil evaluate BODY forms on source blocks in current
  1065. buffer."
  1066. (declare (indent 1) (debug (form body)))
  1067. (org-with-gensyms (datum end point tempvar to-be-removed visitedp)
  1068. `(let* ((case-fold-search t)
  1069. (,tempvar ,file)
  1070. (,visitedp (or (null ,tempvar)
  1071. (get-file-buffer (expand-file-name ,tempvar))))
  1072. (,point (point))
  1073. ,to-be-removed)
  1074. (save-window-excursion
  1075. (when ,tempvar (find-file ,tempvar))
  1076. (setq ,to-be-removed (current-buffer))
  1077. (goto-char (point-min))
  1078. (while (re-search-forward "call_\\S-\\|^[ \t]*#\\+CALL:" nil t)
  1079. (let ((,datum (save-match-data (org-element-context))))
  1080. (when (memq (org-element-type ,datum)
  1081. '(babel-call inline-babel-call))
  1082. (goto-char (match-beginning 0))
  1083. (let ((,end (copy-marker (org-element-property :end ,datum))))
  1084. ,@body
  1085. (goto-char ,end)
  1086. (set-marker ,end nil))))))
  1087. (unless ,visitedp (kill-buffer ,to-be-removed))
  1088. (goto-char ,point))))
  1089. ;;;###autoload
  1090. (defmacro org-babel-map-executables (file &rest body)
  1091. "Evaluate BODY forms on each active Babel code in FILE.
  1092. If FILE is nil evaluate BODY forms on source blocks in current
  1093. buffer."
  1094. (declare (indent 1) (debug (form body)))
  1095. (org-with-gensyms (datum end point tempvar to-be-removed visitedp)
  1096. `(let* ((case-fold-search t)
  1097. (,tempvar ,file)
  1098. (,visitedp (or (null ,tempvar)
  1099. (get-file-buffer (expand-file-name ,tempvar))))
  1100. (,point (point))
  1101. ,to-be-removed)
  1102. (save-window-excursion
  1103. (when ,tempvar (find-file ,tempvar))
  1104. (setq ,to-be-removed (current-buffer))
  1105. (goto-char (point-min))
  1106. (while (re-search-forward
  1107. "\\(call\\|src\\)_\\|^[ \t]*#\\+\\(BEGIN_SRC\\|CALL:\\)" nil t)
  1108. (let ((,datum (save-match-data (org-element-context))))
  1109. (when (memq (org-element-type ,datum)
  1110. '(babel-call inline-babel-call inline-src-block
  1111. src-block))
  1112. (goto-char (match-beginning 0))
  1113. (let ((,end (copy-marker (org-element-property :end ,datum))))
  1114. ,@body
  1115. (goto-char ,end)
  1116. (set-marker ,end nil))))))
  1117. (unless ,visitedp (kill-buffer ,to-be-removed))
  1118. (goto-char ,point))))
  1119. ;;;###autoload
  1120. (defun org-babel-execute-buffer (&optional arg)
  1121. "Execute source code blocks in a buffer.
  1122. Call `org-babel-execute-src-block' on every source block in
  1123. the current buffer."
  1124. (interactive "P")
  1125. (org-babel-eval-wipe-error-buffer)
  1126. (org-save-outline-visibility t
  1127. (org-babel-map-executables nil
  1128. (if (memq (org-element-type (org-element-context))
  1129. '(babel-call inline-babel-call))
  1130. (org-babel-lob-execute-maybe)
  1131. (org-babel-execute-src-block arg)))))
  1132. ;;;###autoload
  1133. (defun org-babel-execute-subtree (&optional arg)
  1134. "Execute source code blocks in a subtree.
  1135. Call `org-babel-execute-src-block' on every source block in
  1136. the current subtree."
  1137. (interactive "P")
  1138. (save-restriction
  1139. (save-excursion
  1140. (org-narrow-to-subtree)
  1141. (org-babel-execute-buffer arg)
  1142. (widen))))
  1143. ;;;###autoload
  1144. (defun org-babel-sha1-hash (&optional info context)
  1145. "Generate a sha1 hash based on the value of INFO.
  1146. CONTEXT specifies the context of evaluation. It can be `:eval',
  1147. `:export', `:tangle'. A nil value means `:eval'."
  1148. (interactive)
  1149. (let ((print-level nil)
  1150. (info (or info (org-babel-get-src-block-info)))
  1151. (context (or context :eval)))
  1152. (setf (nth 2 info)
  1153. (sort (copy-sequence (nth 2 info))
  1154. (lambda (a b) (string< (car a) (car b)))))
  1155. (let* ((rm (lambda (lst)
  1156. (dolist (p '("replace" "silent" "none"
  1157. "append" "prepend"))
  1158. (setq lst (remove p lst)))
  1159. lst))
  1160. (norm (lambda (arg)
  1161. (let ((v (if (and (listp (cdr arg)) (null (cddr arg)))
  1162. (copy-sequence (cdr arg))
  1163. (cdr arg))))
  1164. (when (and v (not (and (sequencep v)
  1165. (not (consp v))
  1166. (= (length v) 0))))
  1167. (cond
  1168. ((and (listp v) ; lists are sorted
  1169. (member (car arg) '(:result-params)))
  1170. (sort (funcall rm v) #'string<))
  1171. ((and (stringp v) ; strings are sorted
  1172. (member (car arg) '(:results :exports)))
  1173. (mapconcat #'identity (sort (funcall rm (split-string v))
  1174. #'string<) " "))
  1175. (t v))))))
  1176. ;; expanded body
  1177. (lang (nth 0 info))
  1178. (params (nth 2 info))
  1179. (body (if (org-babel-noweb-p params context)
  1180. (org-babel-expand-noweb-references info)
  1181. (nth 1 info)))
  1182. (expand-cmd (intern (concat "org-babel-expand-body:" lang)))
  1183. (assignments-cmd (intern (concat "org-babel-variable-assignments:"
  1184. lang)))
  1185. (expanded
  1186. (if (fboundp expand-cmd) (funcall expand-cmd body params)
  1187. (org-babel-expand-body:generic
  1188. body params (and (fboundp assignments-cmd)
  1189. (funcall assignments-cmd params))))))
  1190. (let* ((it (format "%s-%s"
  1191. (mapconcat
  1192. #'identity
  1193. (delq nil (mapcar (lambda (arg)
  1194. (let ((normalized (funcall norm arg)))
  1195. (when normalized
  1196. (format "%S" normalized))))
  1197. (nth 2 info))) ":")
  1198. expanded))
  1199. (hash (sha1 it)))
  1200. (when (called-interactively-p 'interactive) (message hash))
  1201. hash))))
  1202. (defun org-babel-current-result-hash (&optional info)
  1203. "Return the current in-buffer hash."
  1204. (let ((result (org-babel-where-is-src-block-result nil info)))
  1205. (when result
  1206. (org-with-point-at result
  1207. (let ((case-fold-search t)) (looking-at org-babel-result-regexp))
  1208. (match-string-no-properties 1)))))
  1209. (defun org-babel-hide-hash ()
  1210. "Hide the hash in the current results line.
  1211. Only the initial `org-babel-hash-show' characters of the hash
  1212. will remain visible."
  1213. (add-to-invisibility-spec '(org-babel-hide-hash . t))
  1214. (save-excursion
  1215. (when (and (let ((case-fold-search t))
  1216. (re-search-forward org-babel-result-regexp nil t))
  1217. (match-string 1))
  1218. (let* ((start (match-beginning 1))
  1219. (hide-start (+ org-babel-hash-show start))
  1220. (end (match-end 1))
  1221. (hash (match-string 1))
  1222. ov1 ov2)
  1223. (setq ov1 (make-overlay start hide-start))
  1224. (setq ov2 (make-overlay hide-start end))
  1225. (overlay-put ov2 'invisible 'org-babel-hide-hash)
  1226. (overlay-put ov1 'babel-hash hash)))))
  1227. (defun org-babel-hide-all-hashes ()
  1228. "Hide the hash in the current buffer.
  1229. Only the initial `org-babel-hash-show' characters of each hash
  1230. will remain visible. This function should be called as part of
  1231. the `org-mode-hook'."
  1232. (save-excursion
  1233. (let ((case-fold-search t))
  1234. (while (and (not org-babel-hash-show-time)
  1235. (re-search-forward org-babel-result-regexp nil t))
  1236. (goto-char (match-beginning 0))
  1237. (org-babel-hide-hash)
  1238. (goto-char (match-end 0))))))
  1239. (add-hook 'org-mode-hook 'org-babel-hide-all-hashes)
  1240. (defun org-babel-hash-at-point (&optional point)
  1241. "Return the value of the hash at POINT.
  1242. \\<org-mode-map>\
  1243. The hash is also added as the last element of the kill ring.
  1244. This can be called with `\\[org-ctrl-c-ctrl-c]'."
  1245. (interactive)
  1246. (let ((hash (car (delq nil (mapcar
  1247. (lambda (ol) (overlay-get ol 'babel-hash))
  1248. (overlays-at (or point (point))))))))
  1249. (when hash (kill-new hash) (message hash))))
  1250. (defun org-babel-result-hide-spec ()
  1251. "Hide portions of results lines.
  1252. Add `org-babel-hide-result' as an invisibility spec for hiding
  1253. portions of results lines."
  1254. (add-to-invisibility-spec '(org-babel-hide-result . t)))
  1255. (add-hook 'org-mode-hook 'org-babel-result-hide-spec)
  1256. (defvar org-babel-hide-result-overlays nil
  1257. "Overlays hiding results.")
  1258. (defun org-babel-result-hide-all ()
  1259. "Fold all results in the current buffer."
  1260. (interactive)
  1261. (org-babel-show-result-all)
  1262. (save-excursion
  1263. (let ((case-fold-search t))
  1264. (while (re-search-forward org-babel-result-regexp nil t)
  1265. (save-excursion (goto-char (match-beginning 0))
  1266. (org-babel-hide-result-toggle-maybe))))))
  1267. (defun org-babel-show-result-all ()
  1268. "Unfold all results in the current buffer."
  1269. (mapc 'delete-overlay org-babel-hide-result-overlays)
  1270. (setq org-babel-hide-result-overlays nil))
  1271. ;;;###autoload
  1272. (defun org-babel-hide-result-toggle-maybe ()
  1273. "Toggle visibility of result at point."
  1274. (interactive)
  1275. (let ((case-fold-search t))
  1276. (and (org-match-line org-babel-result-regexp)
  1277. (progn (org-babel-hide-result-toggle) t))))
  1278. (defun org-babel-hide-result-toggle (&optional force)
  1279. "Toggle the visibility of the current result."
  1280. (interactive)
  1281. (save-excursion
  1282. (beginning-of-line)
  1283. (let ((case-fold-search t))
  1284. (unless (re-search-forward org-babel-result-regexp nil t)
  1285. (error "Not looking at a result line")))
  1286. (let ((start (progn (beginning-of-line 2) (1- (point))))
  1287. (end (progn
  1288. (while (looking-at org-babel-multi-line-header-regexp)
  1289. (forward-line 1))
  1290. (goto-char (1- (org-babel-result-end)))
  1291. (point)))
  1292. ov)
  1293. (if (memq t (mapcar (lambda (overlay)
  1294. (eq (overlay-get overlay 'invisible)
  1295. 'org-babel-hide-result))
  1296. (overlays-at start)))
  1297. (when (or (not force) (eq force 'off))
  1298. (mapc (lambda (ov)
  1299. (when (member ov org-babel-hide-result-overlays)
  1300. (setq org-babel-hide-result-overlays
  1301. (delq ov org-babel-hide-result-overlays)))
  1302. (when (eq (overlay-get ov 'invisible)
  1303. 'org-babel-hide-result)
  1304. (delete-overlay ov)))
  1305. (overlays-at start)))
  1306. (setq ov (make-overlay start end))
  1307. (overlay-put ov 'invisible 'org-babel-hide-result)
  1308. ;; make the block accessible to isearch
  1309. (overlay-put
  1310. ov 'isearch-open-invisible
  1311. (lambda (ov)
  1312. (when (member ov org-babel-hide-result-overlays)
  1313. (setq org-babel-hide-result-overlays
  1314. (delq ov org-babel-hide-result-overlays)))
  1315. (when (eq (overlay-get ov 'invisible)
  1316. 'org-babel-hide-result)
  1317. (delete-overlay ov))))
  1318. (push ov org-babel-hide-result-overlays)))))
  1319. ;; org-tab-after-check-for-cycling-hook
  1320. (add-hook 'org-tab-first-hook 'org-babel-hide-result-toggle-maybe)
  1321. ;; Remove overlays when changing major mode
  1322. (add-hook 'org-mode-hook
  1323. (lambda () (add-hook 'change-major-mode-hook
  1324. 'org-babel-show-result-all 'append 'local)))
  1325. (defun org-babel-params-from-properties (&optional lang no-eval)
  1326. "Retrieve source block parameters specified as properties.
  1327. LANG is the language of the source block, as a string. When
  1328. optional argument NO-EVAL is non-nil, do not evaluate Lisp values
  1329. in parameters.
  1330. Return a list of association lists of source block parameters
  1331. specified in the properties of the current outline entry."
  1332. (save-match-data
  1333. (list
  1334. ;; Header arguments specified with the header-args property at
  1335. ;; point of call.
  1336. (org-babel-parse-header-arguments
  1337. (org-entry-get (point) "header-args" 'inherit)
  1338. no-eval)
  1339. ;; Language-specific header arguments at point of call.
  1340. (and lang
  1341. (org-babel-parse-header-arguments
  1342. (org-entry-get (point) (concat "header-args:" lang) 'inherit)
  1343. no-eval)))))
  1344. (defun org-babel-balanced-split (string alts)
  1345. "Split STRING on instances of ALTS.
  1346. ALTS is a character, or cons of two character options where each
  1347. option may be either the numeric code of a single character or
  1348. a list of character alternatives. For example, to split on
  1349. balanced instances of \"[ \t]:\", set ALTS to ((32 9) . 58)."
  1350. (with-temp-buffer
  1351. (insert string)
  1352. (goto-char (point-min))
  1353. (let ((splitp (lambda (past next)
  1354. ;; Non-nil when there should be a split after NEXT
  1355. ;; character. PAST is the character before NEXT.
  1356. (pcase alts
  1357. (`(,(and first (pred consp)) . ,(and second (pred consp)))
  1358. (and (memq past first) (memq next second)))
  1359. (`(,first . ,(and second (pred consp)))
  1360. (and (eq past first) (memq next second)))
  1361. (`(,(and first (pred consp)) . ,second)
  1362. (and (memq past first) (eq next second)))
  1363. (`(,first . ,second)
  1364. (and (eq past first) (eq next second)))
  1365. ((pred (eq next)) t)
  1366. (_ nil))))
  1367. (partial nil)
  1368. (result nil))
  1369. (while (not (eobp))
  1370. (cond
  1371. ((funcall splitp (char-before) (char-after))
  1372. ;; There is a split after point. If ALTS is two-folds,
  1373. ;; remove last parsed character as it belongs to ALTS.
  1374. (when (consp alts) (pop partial))
  1375. ;; Include elements parsed so far in RESULTS and flush
  1376. ;; partial parsing.
  1377. (when partial
  1378. (push (apply #'string (nreverse partial)) result)
  1379. (setq partial nil))
  1380. (forward-char))
  1381. ((memq (char-after) '(?\( ?\[))
  1382. ;; Include everything between balanced brackets.
  1383. (let* ((origin (point))
  1384. (after (char-after))
  1385. (openings (list after)))
  1386. (forward-char)
  1387. (while (and openings (re-search-forward "[]()]" nil t))
  1388. (pcase (char-before)
  1389. ((and match (or ?\[ ?\()) (push match openings))
  1390. (?\] (when (eq ?\[ (car openings)) (pop openings)))
  1391. (_ (when (eq ?\( (car openings)) (pop openings)))))
  1392. (if (null openings)
  1393. (setq partial
  1394. (nconc (nreverse (string-to-list
  1395. (buffer-substring origin (point))))
  1396. partial))
  1397. ;; Un-balanced bracket. Backtrack.
  1398. (push after partial)
  1399. (goto-char (1+ origin)))))
  1400. ((and (eq ?\" (char-after)) (not (eq ?\\ (char-before))))
  1401. ;; Include everything from current double quote to next
  1402. ;; non-escaped double quote.
  1403. (let ((origin (point)))
  1404. (if (re-search-forward "[^\\]\"" nil t)
  1405. (setq partial
  1406. (nconc (nreverse (string-to-list
  1407. (buffer-substring origin (point))))
  1408. partial))
  1409. ;; No closing double quote. Backtrack.
  1410. (push ?\" partial)
  1411. (forward-char))))
  1412. (t (push (char-after) partial)
  1413. (forward-char))))
  1414. ;; Add pending parsing and return result.
  1415. (when partial (push (apply #'string (nreverse partial)) result))
  1416. (nreverse result))))
  1417. (defun org-babel-join-splits-near-ch (ch list)
  1418. "Join splits where \"=\" is on either end of the split."
  1419. (let ((last= (lambda (str) (= ch (aref str (1- (length str))))))
  1420. (first= (lambda (str) (= ch (aref str 0)))))
  1421. (reverse
  1422. (cl-reduce (lambda (acc el)
  1423. (let ((head (car acc)))
  1424. (if (and head (or (funcall last= head) (funcall first= el)))
  1425. (cons (concat head el) (cdr acc))
  1426. (cons el acc))))
  1427. list :initial-value nil))))
  1428. (defun org-babel-parse-header-arguments (string &optional no-eval)
  1429. "Parse header arguments in STRING.
  1430. When optional argument NO-EVAL is non-nil, do not evaluate Lisp
  1431. in parameters. Return an alist."
  1432. (when (org-string-nw-p string)
  1433. (org-babel-parse-multiple-vars
  1434. (delq nil
  1435. (mapcar
  1436. (lambda (arg)
  1437. (if (string-match
  1438. "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
  1439. arg)
  1440. (cons (intern (match-string 1 arg))
  1441. (org-babel-read (org-babel-chomp (match-string 2 arg))
  1442. no-eval))
  1443. (cons (intern (org-babel-chomp arg)) nil)))
  1444. (let ((raw (org-babel-balanced-split string '((32 9) . 58))))
  1445. (cons (car raw)
  1446. (mapcar (lambda (r) (concat ":" r)) (cdr raw)))))))))
  1447. (defun org-babel-parse-multiple-vars (header-arguments)
  1448. "Expand multiple variable assignments behind a single :var keyword.
  1449. This allows expression of multiple variables with one :var as
  1450. shown below.
  1451. #+PROPERTY: var foo=1, bar=2"
  1452. (let (results)
  1453. (mapc (lambda (pair)
  1454. (if (eq (car pair) :var)
  1455. (mapcar (lambda (v) (push (cons :var (org-trim v)) results))
  1456. (org-babel-join-splits-near-ch
  1457. 61 (org-babel-balanced-split (cdr pair) 32)))
  1458. (push pair results)))
  1459. header-arguments)
  1460. (nreverse results)))
  1461. (defun org-babel-process-params (params)
  1462. "Expand variables in PARAMS and add summary parameters."
  1463. (let* ((processed-vars (mapcar (lambda (el)
  1464. (if (consp el)
  1465. el
  1466. (org-babel-ref-parse el)))
  1467. (org-babel--get-vars params)))
  1468. (vars-and-names (if (and (assq :colname-names params)
  1469. (assq :rowname-names params))
  1470. (list processed-vars)
  1471. (org-babel-disassemble-tables
  1472. processed-vars
  1473. (cdr (assq :hlines params))
  1474. (cdr (assq :colnames params))
  1475. (cdr (assq :rownames params)))))
  1476. (raw-result (or (cdr (assq :results params)) ""))
  1477. (result-params (delete-dups
  1478. (append
  1479. (split-string (if (stringp raw-result)
  1480. raw-result
  1481. (eval raw-result t)))
  1482. (cdr (assq :result-params params))))))
  1483. (append
  1484. (mapcar (lambda (var) (cons :var var)) (car vars-and-names))
  1485. (list
  1486. (cons :colname-names (or (cdr (assq :colname-names params))
  1487. (cadr vars-and-names)))
  1488. (cons :rowname-names (or (cdr (assq :rowname-names params))
  1489. (cl-caddr vars-and-names)))
  1490. (cons :result-params result-params)
  1491. (cons :result-type (cond ((member "output" result-params) 'output)
  1492. ((member "value" result-params) 'value)
  1493. (t 'value))))
  1494. (cl-remove-if
  1495. (lambda (x) (memq (car x) '(:colname-names :rowname-names :result-params
  1496. :result-type :var)))
  1497. params))))
  1498. ;; row and column names
  1499. (defun org-babel-del-hlines (table)
  1500. "Remove all `hline's from TABLE."
  1501. (remq 'hline table))
  1502. (defun org-babel-get-colnames (table)
  1503. "Return the column names of TABLE.
  1504. Return a cons cell, the `car' of which contains the TABLE less
  1505. colnames, and the `cdr' of which contains a list of the column
  1506. names."
  1507. (if (eq 'hline (nth 1 table))
  1508. (cons (cddr table) (car table))
  1509. (cons (cdr table) (car table))))
  1510. (defun org-babel-get-rownames (table)
  1511. "Return the row names of TABLE.
  1512. Return a cons cell, the `car' of which contains the TABLE less
  1513. rownames, and the `cdr' of which contains a list of the rownames.
  1514. Note: this function removes any hlines in TABLE."
  1515. (let* ((table (org-babel-del-hlines table))
  1516. (rownames (funcall (lambda ()
  1517. (let ((tp table))
  1518. (mapcar
  1519. (lambda (_row)
  1520. (prog1
  1521. (pop (car tp))
  1522. (setq tp (cdr tp))))
  1523. table))))))
  1524. (cons table rownames)))
  1525. (defun org-babel-put-colnames (table colnames)
  1526. "Add COLNAMES to TABLE if they exist."
  1527. (if colnames (apply 'list colnames 'hline table) table))
  1528. (defun org-babel-put-rownames (table rownames)
  1529. "Add ROWNAMES to TABLE if they exist."
  1530. (if rownames
  1531. (mapcar (lambda (row)
  1532. (if (listp row)
  1533. (cons (or (pop rownames) "") row)
  1534. row))
  1535. table)
  1536. table))
  1537. (defun org-babel-pick-name (names selector)
  1538. "Select one out of an alist of row or column names.
  1539. SELECTOR can be either a list of names in which case those names
  1540. will be returned directly, or an index into the list NAMES in
  1541. which case the indexed names will be return."
  1542. (if (listp selector)
  1543. selector
  1544. (when names
  1545. (if (and selector (symbolp selector) (not (equal t selector)))
  1546. (cdr (assoc selector names))
  1547. (if (integerp selector)
  1548. (nth (- selector 1) names)
  1549. (cdr (car (last names))))))))
  1550. (defun org-babel-disassemble-tables (vars hlines colnames rownames)
  1551. "Parse tables for further processing.
  1552. Process the variables in VARS according to the HLINES,
  1553. ROWNAMES and COLNAMES header arguments. Return a list consisting
  1554. of the vars, cnames and rnames."
  1555. (let (cnames rnames)
  1556. (list
  1557. (mapcar
  1558. (lambda (var)
  1559. (when (listp (cdr var))
  1560. (when (and (not (equal colnames "no"))
  1561. (or colnames (and (eq (nth 1 (cdr var)) 'hline)
  1562. (not (member 'hline (cddr (cdr var)))))))
  1563. (let ((both (org-babel-get-colnames (cdr var))))
  1564. (setq cnames (cons (cons (car var) (cdr both))
  1565. cnames))
  1566. (setq var (cons (car var) (car both)))))
  1567. (when (and rownames (not (equal rownames "no")))
  1568. (let ((both (org-babel-get-rownames (cdr var))))
  1569. (setq rnames (cons (cons (car var) (cdr both))
  1570. rnames))
  1571. (setq var (cons (car var) (car both)))))
  1572. (when (and hlines (not (equal hlines "yes")))
  1573. (setq var (cons (car var) (org-babel-del-hlines (cdr var))))))
  1574. var)
  1575. vars)
  1576. (reverse cnames) (reverse rnames))))
  1577. (defun org-babel-reassemble-table (table colnames rownames)
  1578. "Add column and row names to a table.
  1579. Given a TABLE and set of COLNAMES and ROWNAMES add the names
  1580. to the table for reinsertion to org-mode."
  1581. (if (listp table)
  1582. (let ((table (if (and rownames (= (length table) (length rownames)))
  1583. (org-babel-put-rownames table rownames) table)))
  1584. (if (and colnames (listp (car table)) (= (length (car table))
  1585. (length colnames)))
  1586. (org-babel-put-colnames table colnames) table))
  1587. table))
  1588. (defun org-babel-where-is-src-block-head (&optional src-block)
  1589. "Find where the current source block begins.
  1590. If optional argument SRC-BLOCK is `src-block' type element, find
  1591. its current beginning instead.
  1592. Return the point at the beginning of the current source block.
  1593. Specifically at the beginning of the #+BEGIN_SRC line. Also set
  1594. match-data relatively to `org-babel-src-block-regexp', which see.
  1595. If the point is not on a source block then return nil."
  1596. (let ((element (or src-block (org-element-at-point))))
  1597. (when (eq (org-element-type element) 'src-block)
  1598. (let ((end (org-element-property :end element)))
  1599. (org-with-wide-buffer
  1600. ;; Ensure point is not on a blank line after the block.
  1601. (beginning-of-line)
  1602. (skip-chars-forward " \r\t\n" end)
  1603. (when (< (point) end)
  1604. (prog1 (goto-char (org-element-property :post-affiliated element))
  1605. (looking-at org-babel-src-block-regexp))))))))
  1606. ;;;###autoload
  1607. (defun org-babel-goto-src-block-head ()
  1608. "Go to the beginning of the current code block."
  1609. (interactive)
  1610. (let ((head (org-babel-where-is-src-block-head)))
  1611. (if head (goto-char head) (error "Not currently in a code block"))))
  1612. ;;;###autoload
  1613. (defun org-babel-goto-named-src-block (name)
  1614. "Go to a named source-code block."
  1615. (interactive
  1616. (let ((completion-ignore-case t)
  1617. (case-fold-search t)
  1618. (all-block-names (org-babel-src-block-names)))
  1619. (list (completing-read
  1620. "source-block name: " all-block-names nil t
  1621. (let* ((context (org-element-context))
  1622. (type (org-element-type context))
  1623. (noweb-ref
  1624. (and (memq type '(inline-src-block src-block))
  1625. (org-in-regexp (org-babel-noweb-wrap)))))
  1626. (cond
  1627. (noweb-ref
  1628. (buffer-substring
  1629. (+ (car noweb-ref) (length org-babel-noweb-wrap-start))
  1630. (- (cdr noweb-ref) (length org-babel-noweb-wrap-end))))
  1631. ((memq type '(babel-call inline-babel-call)) ;#+CALL:
  1632. (org-element-property :call context))
  1633. ((car (org-element-property :results context))) ;#+RESULTS:
  1634. ((let ((symbol (thing-at-point 'symbol))) ;Symbol.
  1635. (and symbol
  1636. (member-ignore-case symbol all-block-names)
  1637. symbol)))
  1638. (t "")))))))
  1639. (let ((point (org-babel-find-named-block name)))
  1640. (if point
  1641. ;; Taken from `org-open-at-point'.
  1642. (progn (org-mark-ring-push) (goto-char point) (org-show-context))
  1643. (message "source-code block `%s' not found in this buffer" name))))
  1644. (defun org-babel-find-named-block (name)
  1645. "Find a named source-code block.
  1646. Return the location of the source block identified by source
  1647. NAME, or nil if no such block exists. Set match data according
  1648. to `org-babel-named-src-block-regexp'."
  1649. (save-excursion
  1650. (goto-char (point-min))
  1651. (let ((regexp (org-babel-named-src-block-regexp-for-name name)))
  1652. (or (and (looking-at regexp)
  1653. (progn (goto-char (match-beginning 1))
  1654. (line-beginning-position)))
  1655. (ignore-errors (org-next-block 1 nil regexp))))))
  1656. (defun org-babel-src-block-names (&optional file)
  1657. "Return the names of source blocks in FILE or the current buffer."
  1658. (with-current-buffer (if file (find-file-noselect file) (current-buffer))
  1659. (org-with-point-at 1
  1660. (let ((regexp "^[ \t]*#\\+begin_src ")
  1661. (case-fold-search t)
  1662. (names nil))
  1663. (while (re-search-forward regexp nil t)
  1664. (let ((element (org-element-at-point)))
  1665. (when (eq 'src-block (org-element-type element))
  1666. (let ((name (org-element-property :name element)))
  1667. (when name (push name names))))))
  1668. names))))
  1669. ;;;###autoload
  1670. (defun org-babel-goto-named-result (name)
  1671. "Go to a named result."
  1672. (interactive
  1673. (let ((completion-ignore-case t))
  1674. (list (completing-read "Source-block name: "
  1675. (org-babel-result-names) nil t))))
  1676. (let ((point (org-babel-find-named-result name)))
  1677. (if point
  1678. ;; taken from `org-open-at-point'
  1679. (progn (goto-char point) (org-show-context))
  1680. (message "result `%s' not found in this buffer" name))))
  1681. (defun org-babel-find-named-result (name)
  1682. "Find a named result.
  1683. Return the location of the result named NAME in the current
  1684. buffer or nil if no such result exists."
  1685. (save-excursion
  1686. (goto-char (point-min))
  1687. (let ((case-fold-search t)
  1688. (re (format "^[ \t]*#\\+%s.*?:[ \t]*%s[ \t]*$"
  1689. org-babel-results-keyword
  1690. (regexp-quote name))))
  1691. (catch :found
  1692. (while (re-search-forward re nil t)
  1693. (let ((element (org-element-at-point)))
  1694. (when (or (eq (org-element-type element) 'keyword)
  1695. (< (point)
  1696. (org-element-property :post-affiliated element)))
  1697. (throw :found (line-beginning-position)))))))))
  1698. (defun org-babel-result-names (&optional file)
  1699. "Return the names of results in FILE or the current buffer."
  1700. (save-excursion
  1701. (when file (find-file file)) (goto-char (point-min))
  1702. (let ((case-fold-search t) names)
  1703. (while (re-search-forward org-babel-result-w-name-regexp nil t)
  1704. (setq names (cons (match-string-no-properties 9) names)))
  1705. names)))
  1706. ;;;###autoload
  1707. (defun org-babel-next-src-block (&optional arg)
  1708. "Jump to the next source block.
  1709. With optional prefix argument ARG, jump forward ARG many source blocks."
  1710. (interactive "p")
  1711. (org-next-block arg nil org-babel-src-block-regexp))
  1712. ;;;###autoload
  1713. (defun org-babel-previous-src-block (&optional arg)
  1714. "Jump to the previous source block.
  1715. With optional prefix argument ARG, jump backward ARG many source blocks."
  1716. (interactive "p")
  1717. (org-previous-block arg org-babel-src-block-regexp))
  1718. (defvar org-babel-load-languages)
  1719. ;;;###autoload
  1720. (defun org-babel-mark-block ()
  1721. "Mark current source block."
  1722. (interactive)
  1723. (let ((head (org-babel-where-is-src-block-head)))
  1724. (when head
  1725. (save-excursion
  1726. (goto-char head)
  1727. (looking-at org-babel-src-block-regexp))
  1728. (push-mark (match-end 5) nil t)
  1729. (goto-char (match-beginning 5)))))
  1730. (defun org-babel-demarcate-block (&optional arg)
  1731. "Wrap or split the code in the region or on the point.
  1732. When called from inside of a code block the current block is
  1733. split. When called from outside of a code block a new code block
  1734. is created. In both cases if the region is demarcated and if the
  1735. region is not active then the point is demarcated."
  1736. (interactive "P")
  1737. (let* ((info (org-babel-get-src-block-info 'light))
  1738. (start (org-babel-where-is-src-block-head))
  1739. (block (and start (match-string 0)))
  1740. (headers (and start (match-string 4)))
  1741. (stars (concat (make-string (or (org-current-level) 1) ?*) " "))
  1742. (upper-case-p (and block
  1743. (let (case-fold-search)
  1744. (string-match-p "#\\+BEGIN_SRC" block)))))
  1745. (if info
  1746. (mapc
  1747. (lambda (place)
  1748. (save-excursion
  1749. (goto-char place)
  1750. (let ((lang (nth 0 info))
  1751. (indent (make-string (current-indentation) ?\s)))
  1752. (when (string-match "^[[:space:]]*$"
  1753. (buffer-substring (point-at-bol)
  1754. (point-at-eol)))
  1755. (delete-region (point-at-bol) (point-at-eol)))
  1756. (insert (concat
  1757. (if (looking-at "^") "" "\n")
  1758. indent (if upper-case-p "#+END_SRC\n" "#+end_src\n")
  1759. (if arg stars indent) "\n"
  1760. indent (if upper-case-p "#+BEGIN_SRC " "#+begin_src ")
  1761. lang
  1762. (if (> (length headers) 1)
  1763. (concat " " headers) headers)
  1764. (if (looking-at "[\n\r]")
  1765. ""
  1766. (concat "\n" (make-string (current-column) ? )))))))
  1767. (move-end-of-line 2))
  1768. (sort (if (org-region-active-p) (list (mark) (point)) (list (point))) #'>))
  1769. (let ((start (point))
  1770. (lang (completing-read
  1771. "Lang: "
  1772. (mapcar #'symbol-name
  1773. (delete-dups
  1774. (append (mapcar #'car org-babel-load-languages)
  1775. (mapcar (lambda (el) (intern (car el)))
  1776. org-src-lang-modes))))))
  1777. (body (delete-and-extract-region
  1778. (if (org-region-active-p) (mark) (point)) (point))))
  1779. (insert (concat (if (looking-at "^") "" "\n")
  1780. (if arg (concat stars "\n") "")
  1781. (if upper-case-p "#+BEGIN_SRC " "#+begin_src ")
  1782. lang "\n" body
  1783. (if (or (= (length body) 0)
  1784. (string-suffix-p "\r" body)
  1785. (string-suffix-p "\n" body))
  1786. ""
  1787. "\n")
  1788. (if upper-case-p "#+END_SRC\n" "#+end_src\n")))
  1789. (goto-char start)
  1790. (move-end-of-line 1)))))
  1791. (defun org-babel--insert-results-keyword (name hash)
  1792. "Insert RESULTS keyword with NAME value at point.
  1793. If NAME is nil, results are anonymous. HASH is a string used as
  1794. the results hash, or nil. Leave point before the keyword."
  1795. (save-excursion (insert "\n")) ;open line to indent.
  1796. (org-indent-line)
  1797. (delete-char 1)
  1798. (insert (concat "#+" org-babel-results-keyword
  1799. (cond ((not hash) nil)
  1800. (org-babel-hash-show-time
  1801. (format "[%s %s]"
  1802. (format-time-string "(%F %T)")
  1803. hash))
  1804. (t (format "[%s]" hash)))
  1805. ":"
  1806. (when name (concat " " name))
  1807. "\n"))
  1808. ;; Make sure results are going to be followed by at least one blank
  1809. ;; line so they do not get merged with the next element, e.g.,
  1810. ;;
  1811. ;; #+results:
  1812. ;; : 1
  1813. ;;
  1814. ;; : fixed-width area, unrelated to the above.
  1815. (unless (looking-at "^[ \t]*$") (save-excursion (insert "\n")))
  1816. (beginning-of-line 0)
  1817. (when hash (org-babel-hide-hash)))
  1818. (defun org-babel--clear-results-maybe (hash)
  1819. "Clear results when hash doesn't match HASH.
  1820. When results hash does not match HASH, remove RESULTS keyword at
  1821. point, along with related contents. Do nothing if HASH is nil.
  1822. Return a non-nil value if results were cleared. In this case,
  1823. leave point where new results should be inserted."
  1824. (when hash
  1825. (let ((case-fold-search t)) (looking-at org-babel-result-regexp))
  1826. (unless (string= (match-string 1) hash)
  1827. (let* ((e (org-element-at-point))
  1828. (post (copy-marker (org-element-property :post-affiliated e))))
  1829. ;; Delete contents.
  1830. (delete-region post
  1831. (save-excursion
  1832. (goto-char (org-element-property :end e))
  1833. (skip-chars-backward " \t\n")
  1834. (line-beginning-position 2)))
  1835. ;; Delete RESULT keyword. However, if RESULTS keyword is
  1836. ;; orphaned, ignore this part. The deletion above already
  1837. ;; took care of it.
  1838. (unless (= (point) post)
  1839. (delete-region (line-beginning-position)
  1840. (line-beginning-position 2)))
  1841. (goto-char post)
  1842. (set-marker post nil)
  1843. t))))
  1844. (defun org-babel-where-is-src-block-result (&optional insert _info hash)
  1845. "Find where the current source block results begin.
  1846. Return the point at the beginning of the result of the current
  1847. source block, specifically at the beginning of the results line.
  1848. If no result exists for this block return nil, unless optional
  1849. argument INSERT is non-nil. In this case, create a results line
  1850. following the source block and return the position at its
  1851. beginning. In the case of inline code, remove the results part
  1852. instead.
  1853. If optional argument HASH is a string, remove contents related to
  1854. RESULTS keyword if its hash is different. Then update the latter
  1855. to HASH."
  1856. (let ((context (org-element-context)))
  1857. (catch :found
  1858. (org-with-wide-buffer
  1859. (pcase (org-element-type context)
  1860. ((or `inline-babel-call `inline-src-block)
  1861. ;; Results for inline objects are located right after them.
  1862. ;; There is no RESULTS line to insert either.
  1863. (let ((limit (org-element-property
  1864. :contents-end (org-element-property :parent context))))
  1865. (goto-char (org-element-property :end context))
  1866. (skip-chars-forward " \t\n" limit)
  1867. (throw :found
  1868. (and
  1869. (< (point) limit)
  1870. (let ((result (org-element-context)))
  1871. (and (eq (org-element-type result) 'macro)
  1872. (string= (org-element-property :key result)
  1873. "results")
  1874. (if (not insert) (point)
  1875. (delete-region
  1876. (point)
  1877. (progn
  1878. (goto-char (org-element-property :end result))
  1879. (skip-chars-backward " \t")
  1880. (point)))
  1881. (point))))))))
  1882. ((or `babel-call `src-block)
  1883. (let* ((name (org-element-property :name context))
  1884. (named-results (and name (org-babel-find-named-result name))))
  1885. (goto-char (or named-results (org-element-property :end context)))
  1886. (cond
  1887. ;; Existing results named after the current source.
  1888. (named-results
  1889. (when (org-babel--clear-results-maybe hash)
  1890. (org-babel--insert-results-keyword name hash))
  1891. (throw :found (point)))
  1892. ;; Named results expect but none to be found.
  1893. (name)
  1894. ;; No possible anonymous results at the very end of
  1895. ;; buffer or outside CONTEXT parent.
  1896. ((eq (point)
  1897. (or (org-element-property
  1898. :contents-end (org-element-property :parent context))
  1899. (point-max))))
  1900. ;; Check if next element is an anonymous result below
  1901. ;; the current block.
  1902. ((let* ((next (org-element-at-point))
  1903. (end (save-excursion
  1904. (goto-char
  1905. (org-element-property :post-affiliated next))
  1906. (line-end-position)))
  1907. (empty-result-re (concat org-babel-result-regexp "$"))
  1908. (case-fold-search t))
  1909. (re-search-forward empty-result-re end t))
  1910. (beginning-of-line)
  1911. (when (org-babel--clear-results-maybe hash)
  1912. (org-babel--insert-results-keyword nil hash))
  1913. (throw :found (point))))))
  1914. ;; Ignore other elements.
  1915. (_ (throw :found nil))))
  1916. ;; No result found. Insert a RESULTS keyword below element, if
  1917. ;; appropriate. In this case, ensure there is an empty line
  1918. ;; after the previous element.
  1919. (when insert
  1920. (save-excursion
  1921. (goto-char (min (org-element-property :end context) (point-max)))
  1922. (skip-chars-backward " \t\n")
  1923. (forward-line)
  1924. (unless (bolp) (insert "\n"))
  1925. (insert "\n")
  1926. (org-babel--insert-results-keyword
  1927. (org-element-property :name context) hash)
  1928. (point))))))
  1929. (defun org-babel-read-element (element)
  1930. "Read ELEMENT into emacs-lisp.
  1931. Return nil if ELEMENT cannot be read."
  1932. (org-with-wide-buffer
  1933. (goto-char (org-element-property :post-affiliated element))
  1934. (pcase (org-element-type element)
  1935. (`fixed-width
  1936. (let ((v (org-trim (org-element-property :value element))))
  1937. (or (org-babel--string-to-number v) v)))
  1938. (`table (org-babel-read-table))
  1939. (`plain-list (org-babel-read-list))
  1940. (`example-block
  1941. (let ((v (org-element-property :value element)))
  1942. (if (or org-src-preserve-indentation
  1943. (org-element-property :preserve-indent element))
  1944. v
  1945. (org-remove-indentation v))))
  1946. (`export-block
  1947. (org-remove-indentation (org-element-property :value element)))
  1948. (`paragraph
  1949. ;; Treat paragraphs containing a single link specially.
  1950. (skip-chars-forward " \t")
  1951. (if (and (looking-at org-link-bracket-re)
  1952. (save-excursion
  1953. (goto-char (match-end 0))
  1954. (skip-chars-forward " \r\t\n")
  1955. (<= (org-element-property :end element)
  1956. (point))))
  1957. (org-babel-read-link)
  1958. (buffer-substring-no-properties
  1959. (org-element-property :contents-begin element)
  1960. (org-element-property :contents-end element))))
  1961. ((or `center-block `quote-block `verse-block `special-block)
  1962. (org-remove-indentation
  1963. (buffer-substring-no-properties
  1964. (org-element-property :contents-begin element)
  1965. (org-element-property :contents-end element))))
  1966. (_ nil))))
  1967. (defun org-babel-read-result ()
  1968. "Read the result at point into emacs-lisp."
  1969. (and (not (save-excursion
  1970. (beginning-of-line)
  1971. (looking-at-p "[ \t]*$")))
  1972. (org-babel-read-element (org-element-at-point))))
  1973. (defun org-babel-read-table ()
  1974. "Read the table at point into emacs-lisp."
  1975. (mapcar (lambda (row)
  1976. (if (and (symbolp row) (equal row 'hline)) row
  1977. (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval)) row)))
  1978. (org-table-to-lisp)))
  1979. (defun org-babel-read-list ()
  1980. "Read the list at point into emacs-lisp."
  1981. (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval))
  1982. (cdr (org-list-to-lisp))))
  1983. (defvar org-link-types-re)
  1984. (defun org-babel-read-link ()
  1985. "Read the link at point into emacs-lisp.
  1986. If the path of the link is a file path it is expanded using
  1987. `expand-file-name'."
  1988. (let* ((case-fold-search t)
  1989. (raw (and (looking-at org-link-bracket-re)
  1990. (org-no-properties (match-string 1))))
  1991. (type (and (string-match org-link-types-re raw)
  1992. (match-string 1 raw))))
  1993. (cond
  1994. ((not type) (expand-file-name raw))
  1995. ((string= type "file")
  1996. (and (string-match "file\\(.*\\):\\(.+\\)" raw)
  1997. (expand-file-name (match-string 2 raw))))
  1998. (t raw))))
  1999. (defun org-babel-format-result (result &optional sep)
  2000. "Format RESULT for writing to file."
  2001. (let ((echo-res (lambda (r) (if (stringp r) r (format "%S" r)))))
  2002. (if (listp result)
  2003. ;; table result
  2004. (orgtbl-to-generic
  2005. result (list :sep (or sep "\t") :fmt echo-res))
  2006. ;; scalar result
  2007. (funcall echo-res result))))
  2008. (defun org-babel-insert-result (result &optional result-params info hash lang)
  2009. "Insert RESULT into the current buffer.
  2010. By default RESULT is inserted after the end of the current source
  2011. block. The RESULT of an inline source block usually will be
  2012. wrapped inside a `results' macro and placed on the same line as
  2013. the inline source block. The macro is stripped upon export.
  2014. Multiline and non-scalar RESULTS from inline source blocks are
  2015. not allowed. With optional argument RESULT-PARAMS controls
  2016. insertion of results in the Org mode file. RESULT-PARAMS can
  2017. take the following values:
  2018. replace - (default option) insert results after the source block
  2019. or inline source block replacing any previously
  2020. inserted results.
  2021. silent -- no results are inserted into the Org buffer but
  2022. the results are echoed to the minibuffer and are
  2023. ingested by Emacs (a potentially time consuming
  2024. process).
  2025. file ---- the results are interpreted as a file path, and are
  2026. inserted into the buffer using the Org file syntax.
  2027. list ---- the results are interpreted as an Org list.
  2028. raw ----- results are added directly to the Org file. This is
  2029. a good option if you code block will output Org
  2030. formatted text.
  2031. drawer -- results are added directly to the Org file as with
  2032. \"raw\", but are wrapped in a RESULTS drawer or results
  2033. macro, allowing them to later be replaced or removed
  2034. automatically.
  2035. org ----- results are added inside of a \"src_org{}\" or \"#+BEGIN_SRC
  2036. org\" block depending on whether the current source block is
  2037. inline or not. They are not comma-escaped when inserted,
  2038. but Org syntax here will be discarded when exporting the
  2039. file.
  2040. html ---- results are added inside of a #+BEGIN_EXPORT HTML block
  2041. or html export snippet depending on whether the current
  2042. source block is inline or not. This is a good option
  2043. if your code block will output html formatted text.
  2044. latex --- results are added inside of a #+BEGIN_EXPORT LATEX
  2045. block or latex export snippet depending on whether the
  2046. current source block is inline or not. This is a good
  2047. option if your code block will output latex formatted
  2048. text.
  2049. code ---- the results are extracted in the syntax of the source
  2050. code of the language being evaluated and are added
  2051. inside of a source block with the source-code language
  2052. set appropriately. Also, source block inlining is
  2053. preserved in this case. Note this relies on the
  2054. optional LANG argument.
  2055. list ---- the results are rendered as a list. This option not
  2056. allowed for inline source blocks.
  2057. table --- the results are rendered as a table. This option not
  2058. allowed for inline source blocks.
  2059. INFO may provide the values of these header arguments (in the
  2060. `header-arguments-alist' see the docstring for
  2061. `org-babel-get-src-block-info'):
  2062. :file --- the name of the file to which output should be written.
  2063. :wrap --- the effect is similar to `latex' in RESULT-PARAMS but
  2064. using the argument supplied to specify the export block
  2065. or snippet type."
  2066. (cond ((stringp result)
  2067. (setq result (org-no-properties result))
  2068. (when (member "file" result-params)
  2069. (setq result (org-babel-result-to-file
  2070. result (when (assq :file-desc (nth 2 info))
  2071. (or (cdr (assq :file-desc (nth 2 info)))
  2072. result))))))
  2073. ((listp result))
  2074. (t (setq result (format "%S" result))))
  2075. (if (and result-params (member "silent" result-params))
  2076. (progn (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
  2077. result)
  2078. (let ((inline (let ((context (org-element-context)))
  2079. (and (memq (org-element-type context)
  2080. '(inline-babel-call inline-src-block))
  2081. context))))
  2082. (when inline
  2083. (let ((warning
  2084. (or (and (member "table" result-params) "`:results table'")
  2085. (and (listp result) "list result")
  2086. (and (string-match-p "\n." result) "multiline result")
  2087. (and (member "list" result-params) "`:results list'"))))
  2088. (when warning
  2089. (user-error "Inline error: %s cannot be used" warning))))
  2090. (save-excursion
  2091. (let* ((visible-beg (point-min-marker))
  2092. (visible-end (copy-marker (point-max) t))
  2093. (inline (let ((context (org-element-context)))
  2094. (and (memq (org-element-type context)
  2095. '(inline-babel-call inline-src-block))
  2096. context)))
  2097. (existing-result (org-babel-where-is-src-block-result t nil hash))
  2098. (results-switches (cdr (assq :results_switches (nth 2 info))))
  2099. ;; When results exist outside of the current visible
  2100. ;; region of the buffer, be sure to widen buffer to
  2101. ;; update them.
  2102. (outside-scope (and existing-result
  2103. (buffer-narrowed-p)
  2104. (or (> visible-beg existing-result)
  2105. (<= visible-end existing-result))))
  2106. beg end indent)
  2107. ;; Ensure non-inline results end in a newline.
  2108. (when (and (org-string-nw-p result)
  2109. (not inline)
  2110. (not (string-equal (substring result -1) "\n")))
  2111. (setq result (concat result "\n")))
  2112. (unwind-protect
  2113. (progn
  2114. (when outside-scope (widen))
  2115. (if existing-result (goto-char existing-result)
  2116. (goto-char (org-element-property :end inline))
  2117. (skip-chars-backward " \t"))
  2118. (unless inline
  2119. (setq indent (current-indentation))
  2120. (forward-line 1))
  2121. (setq beg (point))
  2122. (cond
  2123. (inline
  2124. ;; Make sure new results are separated from the
  2125. ;; source code by one space.
  2126. (unless existing-result
  2127. (insert " ")
  2128. (setq beg (point))))
  2129. ((member "replace" result-params)
  2130. (delete-region (point) (org-babel-result-end)))
  2131. ((member "append" result-params)
  2132. (goto-char (org-babel-result-end)) (setq beg (point-marker)))
  2133. ((member "prepend" result-params))) ; already there
  2134. (setq results-switches
  2135. (if results-switches (concat " " results-switches) ""))
  2136. (let ((wrap
  2137. (lambda (start finish &optional no-escape no-newlines
  2138. inline-start inline-finish)
  2139. (when inline
  2140. (setq start inline-start)
  2141. (setq finish inline-finish)
  2142. (setq no-newlines t))
  2143. (let ((before-finish (copy-marker end)))
  2144. (goto-char end)
  2145. (insert (concat finish (unless no-newlines "\n")))
  2146. (goto-char beg)
  2147. (insert (concat start (unless no-newlines "\n")))
  2148. (unless no-escape
  2149. (org-escape-code-in-region
  2150. (min (point) before-finish) before-finish))
  2151. (goto-char end))))
  2152. (tabulablep
  2153. (lambda (r)
  2154. ;; Non-nil when result R can be turned into
  2155. ;; a table.
  2156. (and (proper-list-p r)
  2157. (cl-every
  2158. (lambda (e) (or (atom e) (proper-list-p e)))
  2159. result)))))
  2160. ;; insert results based on type
  2161. (cond
  2162. ;; Do nothing for an empty result.
  2163. ((null result))
  2164. ;; Insert a list if preferred.
  2165. ((member "list" result-params)
  2166. (insert
  2167. (org-trim
  2168. (org-list-to-generic
  2169. (cons 'unordered
  2170. (mapcar
  2171. (lambda (e)
  2172. (list (if (stringp e) e (format "%S" e))))
  2173. (if (listp result) result
  2174. (split-string result "\n" t))))
  2175. '(:splicep nil :istart "- " :iend "\n")))
  2176. "\n"))
  2177. ;; Try hard to print RESULT as a table. Give up if
  2178. ;; it contains an improper list.
  2179. ((funcall tabulablep result)
  2180. (goto-char beg)
  2181. (insert (concat (orgtbl-to-orgtbl
  2182. (if (cl-every
  2183. (lambda (e)
  2184. (or (eq e 'hline) (listp e)))
  2185. result)
  2186. result
  2187. (list result))
  2188. nil)
  2189. "\n"))
  2190. (goto-char beg)
  2191. (when (org-at-table-p) (org-table-align))
  2192. (goto-char (org-table-end)))
  2193. ;; Print verbatim a list that cannot be turned into
  2194. ;; a table.
  2195. ((listp result) (insert (format "%s\n" result)))
  2196. ((member "file" result-params)
  2197. (when inline
  2198. (setq result (org-macro-escape-arguments result)))
  2199. (insert result))
  2200. ((and inline (not (member "raw" result-params)))
  2201. (insert (org-macro-escape-arguments
  2202. (org-babel-chomp result "\n"))))
  2203. (t (goto-char beg) (insert result)))
  2204. (setq end (copy-marker (point) t))
  2205. ;; Possibly wrap result.
  2206. (cond
  2207. ((assq :wrap (nth 2 info))
  2208. (let* ((full (or (cdr (assq :wrap (nth 2 info))) "results"))
  2209. (split (split-string full))
  2210. (type (car split))
  2211. (opening-line (concat "#+begin_" full))
  2212. (closing-line (concat "#+end_" type)))
  2213. (cond
  2214. ;; Escape contents from "export" wrap. Wrap
  2215. ;; inline results within an export snippet with
  2216. ;; appropriate value.
  2217. ((eq t (compare-strings type nil nil "export" nil nil t))
  2218. (let ((backend (pcase split
  2219. (`(,_) "none")
  2220. (`(,_ ,b . ,_) b))))
  2221. (funcall wrap
  2222. opening-line closing-line
  2223. nil nil
  2224. (format "{{{results(@@%s:"
  2225. backend) "@@)}}}")))
  2226. ;; Escape contents from "example" wrap. Mark
  2227. ;; inline results as verbatim.
  2228. ((eq t (compare-strings type nil nil "example" nil nil t))
  2229. (funcall wrap
  2230. opening-line closing-line
  2231. nil nil
  2232. "{{{results(=" "=)}}}"))
  2233. ;; Escape contents from "src" wrap. Mark
  2234. ;; inline results as inline source code.
  2235. ((eq t (compare-strings type nil nil "src" nil nil t))
  2236. (let ((inline-open
  2237. (pcase split
  2238. (`(,_)
  2239. "{{{results(src_none{")
  2240. (`(,_ ,language)
  2241. (format "{{{results(src_%s{" language))
  2242. (`(,_ ,language . ,rest)
  2243. (let ((r (mapconcat #'identity rest " ")))
  2244. (format "{{{results(src_%s[%s]{"
  2245. language r))))))
  2246. (funcall wrap
  2247. opening-line closing-line
  2248. nil nil
  2249. inline-open "})}}}")))
  2250. ;; Do not escape contents in non-verbatim
  2251. ;; blocks. Return plain inline results.
  2252. (t
  2253. (funcall wrap
  2254. opening-line closing-line
  2255. t nil
  2256. "{{{results(" ")}}}")))))
  2257. ((member "html" result-params)
  2258. (funcall wrap "#+begin_export html" "#+end_export" nil nil
  2259. "{{{results(@@html:" "@@)}}}"))
  2260. ((member "latex" result-params)
  2261. (funcall wrap "#+begin_export latex" "#+end_export" nil nil
  2262. "{{{results(@@latex:" "@@)}}}"))
  2263. ((member "org" result-params)
  2264. (goto-char beg) (when (org-at-table-p) (org-cycle))
  2265. (funcall wrap "#+begin_src org" "#+end_src" nil nil
  2266. "{{{results(src_org{" "})}}}"))
  2267. ((member "code" result-params)
  2268. (let ((lang (or lang "none")))
  2269. (funcall wrap (format "#+begin_src %s%s" lang results-switches)
  2270. "#+end_src" nil nil
  2271. (format "{{{results(src_%s[%s]{" lang results-switches)
  2272. "})}}}")))
  2273. ((member "raw" result-params)
  2274. (goto-char beg) (when (org-at-table-p) (org-cycle)))
  2275. ((or (member "drawer" result-params)
  2276. ;; Stay backward compatible with <7.9.2
  2277. (member "wrap" result-params))
  2278. (goto-char beg) (when (org-at-table-p) (org-cycle))
  2279. (funcall wrap ":results:" ":end:" 'no-escape nil
  2280. "{{{results(" ")}}}"))
  2281. ((and inline (member "file" result-params))
  2282. (funcall wrap nil nil nil nil "{{{results(" ")}}}"))
  2283. ((and (not (funcall tabulablep result))
  2284. (not (member "file" result-params)))
  2285. (let ((org-babel-inline-result-wrap
  2286. ;; Hard code {{{results(...)}}} on top of
  2287. ;; customization.
  2288. (format "{{{results(%s)}}}"
  2289. org-babel-inline-result-wrap)))
  2290. (org-babel-examplify-region
  2291. beg end results-switches inline)))))
  2292. ;; Possibly indent results in par with #+results line.
  2293. (when (and (not inline) (numberp indent) (> indent 0)
  2294. ;; In this case `table-align' does the work
  2295. ;; for us.
  2296. (not (and (listp result)
  2297. (member "append" result-params))))
  2298. (indent-rigidly beg end indent))
  2299. (if (null result)
  2300. (if (member "value" result-params)
  2301. (message "Code block returned no value.")
  2302. (message "Code block produced no output."))
  2303. (message "Code block evaluation complete.")))
  2304. (set-marker end nil)
  2305. (when outside-scope (narrow-to-region visible-beg visible-end))
  2306. (set-marker visible-beg nil)
  2307. (set-marker visible-end nil)))))))
  2308. (defun org-babel-remove-result (&optional info keep-keyword)
  2309. "Remove the result of the current source block."
  2310. (interactive)
  2311. (let ((location (org-babel-where-is-src-block-result nil info))
  2312. (case-fold-search t))
  2313. (when location
  2314. (save-excursion
  2315. (goto-char location)
  2316. (when (looking-at org-babel-result-regexp)
  2317. (delete-region
  2318. (if keep-keyword (line-beginning-position 2)
  2319. (save-excursion
  2320. (skip-chars-backward " \r\t\n")
  2321. (line-beginning-position 2)))
  2322. (progn (forward-line) (org-babel-result-end))))))))
  2323. (defun org-babel-remove-inline-result (&optional datum)
  2324. "Remove the result of the current inline-src-block or babel call.
  2325. The result must be wrapped in a `results' macro to be removed.
  2326. Leading white space is trimmed."
  2327. (interactive)
  2328. (let* ((el (or datum (org-element-context))))
  2329. (when (memq (org-element-type el) '(inline-src-block inline-babel-call))
  2330. (org-with-wide-buffer
  2331. (goto-char (org-element-property :end el))
  2332. (skip-chars-backward " \t")
  2333. (let ((result (save-excursion
  2334. (skip-chars-forward
  2335. " \t\n"
  2336. (org-element-property
  2337. :contents-end (org-element-property :parent el)))
  2338. (org-element-context))))
  2339. (when (and (eq (org-element-type result) 'macro)
  2340. (string= (org-element-property :key result) "results"))
  2341. (delete-region ; And leading whitespace.
  2342. (point)
  2343. (progn (goto-char (org-element-property :end result))
  2344. (skip-chars-backward " \t\n")
  2345. (point)))))))))
  2346. (defun org-babel-remove-result-one-or-many (x)
  2347. "Remove the result of the current source block.
  2348. If called with a prefix argument, remove all result blocks
  2349. in the buffer."
  2350. (interactive "P")
  2351. (if x
  2352. (org-babel-map-src-blocks nil (org-babel-remove-result))
  2353. (org-babel-remove-result)))
  2354. (defun org-babel-result-end ()
  2355. "Return the point at the end of the current set of results."
  2356. (cond ((looking-at-p "^[ \t]*$") (point)) ;no result
  2357. ((looking-at-p (format "^[ \t]*%s[ \t]*$" org-link-bracket-re))
  2358. (line-beginning-position 2))
  2359. (t
  2360. (let ((element (org-element-at-point)))
  2361. (if (memq (org-element-type element)
  2362. ;; Possible results types.
  2363. '(drawer example-block export-block fixed-width item
  2364. plain-list special-block src-block table))
  2365. (save-excursion
  2366. (goto-char (min (point-max) ;for narrowed buffers
  2367. (org-element-property :end element)))
  2368. (skip-chars-backward " \r\t\n")
  2369. (line-beginning-position 2))
  2370. (point))))))
  2371. (defun org-babel-result-to-file (result &optional description)
  2372. "Convert RESULT into an Org link with optional DESCRIPTION.
  2373. If the `default-directory' is different from the containing
  2374. file's directory then expand relative links."
  2375. (when (stringp result)
  2376. (let ((same-directory?
  2377. (and buffer-file-name
  2378. (not (string= (expand-file-name default-directory)
  2379. (expand-file-name
  2380. (file-name-directory buffer-file-name)))))))
  2381. (format "[[file:%s]%s]"
  2382. (if (and default-directory buffer-file-name same-directory?)
  2383. (if (eq org-link-file-path-type 'adaptive)
  2384. (file-relative-name
  2385. (expand-file-name result default-directory)
  2386. (file-name-directory (buffer-file-name)))
  2387. (expand-file-name result default-directory))
  2388. result)
  2389. (if description (concat "[" description "]") "")))))
  2390. (defun org-babel-examplify-region (beg end &optional results-switches inline)
  2391. "Comment out region using the inline `==' or `: ' org example quote."
  2392. (interactive "*r")
  2393. (let ((maybe-cap
  2394. (lambda (str)
  2395. (if org-babel-uppercase-example-markers (upcase str) str))))
  2396. (if inline
  2397. (save-excursion
  2398. (goto-char beg)
  2399. (insert (format org-babel-inline-result-wrap
  2400. (delete-and-extract-region beg end))))
  2401. (let ((size (count-lines beg end)))
  2402. (save-excursion
  2403. (cond ((= size 0)) ; do nothing for an empty result
  2404. ((< size org-babel-min-lines-for-block-output)
  2405. (goto-char beg)
  2406. (dotimes (_ size)
  2407. (beginning-of-line 1) (insert ": ") (forward-line 1)))
  2408. (t
  2409. (goto-char beg)
  2410. (insert (if results-switches
  2411. (format "%s%s\n"
  2412. (funcall maybe-cap "#+begin_example")
  2413. results-switches)
  2414. (funcall maybe-cap "#+begin_example\n")))
  2415. (let ((p (point)))
  2416. (if (markerp end) (goto-char end) (forward-char (- end beg)))
  2417. (org-escape-code-in-region p (point)))
  2418. (insert (funcall maybe-cap "#+end_example\n")))))))))
  2419. (defun org-babel-update-block-body (new-body)
  2420. "Update the body of the current code block to NEW-BODY."
  2421. (let ((element (org-element-at-point)))
  2422. (unless (eq (org-element-type element) 'src-block)
  2423. (error "Not in a source block"))
  2424. (goto-char (org-babel-where-is-src-block-head element))
  2425. (let* ((ind (current-indentation))
  2426. (body-start (line-beginning-position 2))
  2427. (body (org-element-normalize-string
  2428. (if (or org-src-preserve-indentation
  2429. (org-element-property :preserve-indent element))
  2430. new-body
  2431. (with-temp-buffer
  2432. (insert (org-remove-indentation new-body))
  2433. (indent-rigidly
  2434. (point-min)
  2435. (point-max)
  2436. (+ ind org-edit-src-content-indentation))
  2437. (buffer-string))))))
  2438. (delete-region body-start
  2439. (org-with-wide-buffer
  2440. (goto-char (org-element-property :end element))
  2441. (skip-chars-backward " \t\n")
  2442. (line-beginning-position)))
  2443. (goto-char body-start)
  2444. (insert body))))
  2445. (defun org-babel-merge-params (&rest plists)
  2446. "Combine all parameter association lists in PLISTS.
  2447. Later elements of PLISTS override the values of previous elements.
  2448. This takes into account some special considerations for certain
  2449. parameters when merging lists."
  2450. (let* ((results-exclusive-groups
  2451. (mapcar (lambda (group) (mapcar #'symbol-name group))
  2452. (cdr (assq 'results org-babel-common-header-args-w-values))))
  2453. (exports-exclusive-groups
  2454. (mapcar (lambda (group) (mapcar #'symbol-name group))
  2455. (cdr (assq 'exports org-babel-common-header-args-w-values))))
  2456. (merge
  2457. (lambda (exclusive-groups &rest result-params)
  2458. ;; Maintain exclusivity of mutually exclusive parameters,
  2459. ;; as defined in EXCLUSIVE-GROUPS while merging lists in
  2460. ;; RESULT-PARAMS.
  2461. (let (output)
  2462. (dolist (new-params result-params (delete-dups output))
  2463. (dolist (new-param new-params)
  2464. (dolist (exclusive-group exclusive-groups)
  2465. (when (member new-param exclusive-group)
  2466. (setq output (cl-remove-if
  2467. (lambda (o) (member o exclusive-group))
  2468. output))))
  2469. (push new-param output))))))
  2470. (variable-index 0) ;Handle positional arguments.
  2471. clearnames
  2472. params ;Final parameters list.
  2473. ;; Some keywords accept multiple values. We need to treat
  2474. ;; them specially.
  2475. vars results exports)
  2476. (dolist (plist plists)
  2477. (dolist (pair plist)
  2478. (pcase pair
  2479. (`(:var . ,value)
  2480. (let ((name (cond
  2481. ((listp value) (car value))
  2482. ((string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*=" value)
  2483. (intern (match-string 1 value)))
  2484. (t nil))))
  2485. (cond
  2486. (name
  2487. (setq vars
  2488. (append (if (not (assoc name vars)) vars
  2489. (push name clearnames)
  2490. (cl-remove-if (lambda (p) (equal name (car p)))
  2491. vars))
  2492. (list (cons name pair)))))
  2493. ((and vars (nth variable-index vars))
  2494. ;; If no name is given and we already have named
  2495. ;; variables then assign to named variables in order.
  2496. (let ((name (car (nth variable-index vars))))
  2497. ;; Clear out colnames and rownames for replace vars.
  2498. (push name clearnames)
  2499. (setf (cddr (nth variable-index vars))
  2500. (concat (symbol-name name) "=" value))
  2501. (cl-incf variable-index)))
  2502. (t (error "Variable \"%s\" must be assigned a default value"
  2503. (cdr pair))))))
  2504. (`(:results . ,value)
  2505. (setq results (funcall merge
  2506. results-exclusive-groups
  2507. results
  2508. (split-string
  2509. (if (stringp value) value (eval value t))))))
  2510. (`(:exports . ,value)
  2511. (setq exports (funcall merge
  2512. exports-exclusive-groups
  2513. exports
  2514. (split-string (or value "")))))
  2515. ;; Regular keywords: any value overwrites the previous one.
  2516. (_ (setq params (cons pair (assq-delete-all (car pair) params)))))))
  2517. ;; Handle `:var' and clear out colnames and rownames for replaced
  2518. ;; variables.
  2519. (setq params (nconc (mapcar (lambda (v) (cons :var (cddr v))) vars)
  2520. params))
  2521. (dolist (name clearnames)
  2522. (dolist (param '(:colname-names :rowname-names))
  2523. (when (assq param params)
  2524. (setf (cdr (assq param params))
  2525. (cl-remove-if (lambda (pair) (equal name (car pair)))
  2526. (cdr (assq param params))))
  2527. (setq params
  2528. (cl-remove-if (lambda (pair) (and (equal (car pair) param)
  2529. (null (cdr pair))))
  2530. params)))))
  2531. ;; Handle other special keywords, which accept multiple values.
  2532. (setq params (nconc (list (cons :results (mapconcat #'identity results " "))
  2533. (cons :exports (mapconcat #'identity exports " ")))
  2534. params))
  2535. ;; Return merged params.
  2536. params))
  2537. (defun org-babel-noweb-p (params context)
  2538. "Check if PARAMS require expansion in CONTEXT.
  2539. CONTEXT may be one of :tangle, :export or :eval."
  2540. (let ((allowed-values (cl-case context
  2541. (:tangle '("yes" "tangle" "no-export" "strip-export"))
  2542. (:eval '("yes" "no-export" "strip-export" "eval"))
  2543. (:export '("yes")))))
  2544. (cl-some (lambda (v) (member v allowed-values))
  2545. (split-string (or (cdr (assq :noweb params)) "")))))
  2546. (defun org-babel-expand-noweb-references (&optional info parent-buffer)
  2547. "Expand Noweb references in the body of the current source code block.
  2548. For example the following reference would be replaced with the
  2549. body of the source-code block named `example-block'.
  2550. <<example-block>>
  2551. Note that any text preceding the <<foo>> construct on a line will
  2552. be interposed between the lines of the replacement text. So for
  2553. example if <<foo>> is placed behind a comment, then the entire
  2554. replacement text will also be commented.
  2555. This function must be called from inside of the buffer containing
  2556. the source-code block which holds BODY.
  2557. In addition the following syntax can be used to insert the
  2558. results of evaluating the source-code block named `example-block'.
  2559. <<example-block()>>
  2560. Any optional arguments can be passed to example-block by placing
  2561. the arguments inside the parenthesis following the convention
  2562. defined by `org-babel-lob'. For example
  2563. <<example-block(a=9)>>
  2564. would set the value of argument \"a\" equal to \"9\". Note that
  2565. these arguments are not evaluated in the current source-code
  2566. block but are passed literally to the \"example-block\"."
  2567. (let* ((parent-buffer (or parent-buffer (current-buffer)))
  2568. (info (or info (org-babel-get-src-block-info 'light)))
  2569. (lang (nth 0 info))
  2570. (body (nth 1 info))
  2571. (comment (string= "noweb" (cdr (assq :comments (nth 2 info)))))
  2572. (noweb-re (format "^\\(.*?\\)\\(%s\\)"
  2573. (with-current-buffer parent-buffer
  2574. (org-babel-noweb-wrap))))
  2575. (cache nil)
  2576. (c-wrap
  2577. (lambda (s)
  2578. ;; Comment string S, according to LANG mode. Return new
  2579. ;; string.
  2580. (unless org-babel-tangle-uncomment-comments
  2581. (with-temp-buffer
  2582. (funcall (org-src-get-lang-mode lang))
  2583. (comment-region (point)
  2584. (progn (insert s) (point)))
  2585. (org-trim (buffer-string))))))
  2586. (expand-body
  2587. (lambda (i)
  2588. ;; Expand body of code represented by block info I.
  2589. (let ((b (if (org-babel-noweb-p (nth 2 i) :eval)
  2590. (org-babel-expand-noweb-references i)
  2591. (nth 1 i))))
  2592. (if (not comment) b
  2593. (let ((cs (org-babel-tangle-comment-links i)))
  2594. (concat (funcall c-wrap (car cs)) "\n"
  2595. b "\n"
  2596. (funcall c-wrap (cadr cs))))))))
  2597. (expand-references
  2598. (lambda (ref cache)
  2599. (pcase (gethash ref cache)
  2600. (`(,last . ,previous)
  2601. ;; Ignore separator for last block.
  2602. (let ((strings (list (funcall expand-body last))))
  2603. (dolist (i previous)
  2604. (let ((parameters (nth 2 i)))
  2605. ;; Since we're operating in reverse order, first
  2606. ;; push separator, then body.
  2607. (push (or (cdr (assq :noweb-sep parameters)) "\n")
  2608. strings)
  2609. (push (funcall expand-body i) strings)))
  2610. (mapconcat #'identity strings "")))
  2611. ;; Raise an error about missing reference, or return the
  2612. ;; empty string.
  2613. ((guard (or org-babel-noweb-error-all-langs
  2614. (member lang org-babel-noweb-error-langs)))
  2615. (error "Cannot resolve %s (see `org-babel-noweb-error-langs')"
  2616. (org-babel-noweb-wrap ref)))
  2617. (_ "")))))
  2618. (replace-regexp-in-string
  2619. noweb-re
  2620. (lambda (m)
  2621. (with-current-buffer parent-buffer
  2622. (save-match-data
  2623. (let* ((prefix (match-string 1 m))
  2624. (id (match-string 3 m))
  2625. (evaluate (string-match-p "(.*)" id))
  2626. (expansion
  2627. (cond
  2628. (evaluate
  2629. ;; Evaluation can potentially modify the buffer
  2630. ;; and invalidate the cache: reset it.
  2631. (setq cache nil)
  2632. (let ((raw (org-babel-ref-resolve id)))
  2633. (if (stringp raw) raw (format "%S" raw))))
  2634. ;; Retrieve from the Library of Babel.
  2635. ((nth 2 (assoc-string id org-babel-library-of-babel)))
  2636. ;; Return the contents of headlines literally.
  2637. ((org-babel-ref-goto-headline-id id)
  2638. (org-babel-ref-headline-body))
  2639. ;; Look for a source block named SOURCE-NAME. If
  2640. ;; found, assume it is unique; do not look after
  2641. ;; `:noweb-ref' header argument.
  2642. ((org-with-point-at 1
  2643. (let ((r (org-babel-named-src-block-regexp-for-name id)))
  2644. (and (re-search-forward r nil t)
  2645. (not (org-in-commented-heading-p))
  2646. (funcall expand-body
  2647. (org-babel-get-src-block-info t))))))
  2648. ;; All Noweb references were cached in a previous
  2649. ;; run. Extract the information from the cache.
  2650. ((hash-table-p cache)
  2651. (funcall expand-references id cache))
  2652. ;; Though luck. We go into the long process of
  2653. ;; checking each source block and expand those
  2654. ;; with a matching Noweb reference. Since we're
  2655. ;; going to visit all source blocks in the
  2656. ;; document, cache information about them as well.
  2657. (t
  2658. (setq cache (make-hash-table :test #'equal))
  2659. (org-with-wide-buffer
  2660. (org-babel-map-src-blocks nil
  2661. (if (org-in-commented-heading-p)
  2662. (org-forward-heading-same-level nil t)
  2663. (let* ((info (org-babel-get-src-block-info t))
  2664. (ref (cdr (assq :noweb-ref (nth 2 info)))))
  2665. (push info (gethash ref cache))))))
  2666. (funcall expand-references id cache)))))
  2667. ;; Interpose PREFIX between every line.
  2668. (mapconcat #'identity
  2669. (split-string expansion "[\n\r]")
  2670. (concat "\n" prefix))))))
  2671. body t t 2)))
  2672. (defun org-babel--script-escape-inner (str)
  2673. (let (in-single in-double backslash out)
  2674. (mapc
  2675. (lambda (ch)
  2676. (setq
  2677. out
  2678. (if backslash
  2679. (progn
  2680. (setq backslash nil)
  2681. (cond
  2682. ((and in-single (eq ch ?'))
  2683. ;; Escaped single quote inside single quoted string:
  2684. ;; emit just a single quote, since we've changed the
  2685. ;; outer quotes to double.
  2686. (cons ch out))
  2687. ((eq ch ?\")
  2688. ;; Escaped double quote
  2689. (if in-single
  2690. ;; This should be interpreted as backslash+quote,
  2691. ;; not an escape. Emit a three backslashes
  2692. ;; followed by a quote (because one layer of
  2693. ;; quoting will be stripped by `org-babel-read').
  2694. (append (list ch ?\\ ?\\ ?\\) out)
  2695. ;; Otherwise we are in a double-quoted string. Emit
  2696. ;; a single escaped quote
  2697. (append (list ch ?\\) out)))
  2698. ((eq ch ?\\)
  2699. ;; Escaped backslash: emit a single escaped backslash
  2700. (append (list ?\\ ?\\) out))
  2701. ;; Other: emit a quoted backslash followed by whatever
  2702. ;; the character was (because one layer of quoting will
  2703. ;; be stripped by `org-babel-read').
  2704. (t (append (list ch ?\\ ?\\) out))))
  2705. (cl-case ch
  2706. (?\[ (if (or in-double in-single)
  2707. (cons ?\[ out)
  2708. (cons ?\( out)))
  2709. (?\] (if (or in-double in-single)
  2710. (cons ?\] out)
  2711. (cons ?\) out)))
  2712. (?\{ (if (or in-double in-single)
  2713. (cons ?\{ out)
  2714. (cons ?\( out)))
  2715. (?\} (if (or in-double in-single)
  2716. (cons ?\} out)
  2717. (cons ?\) out)))
  2718. (?, (if (or in-double in-single)
  2719. (cons ?, out) (cons ?\s out)))
  2720. (?\' (if in-double
  2721. (cons ?\' out)
  2722. (setq in-single (not in-single)) (cons ?\" out)))
  2723. (?\" (if in-single
  2724. (append (list ?\" ?\\) out)
  2725. (setq in-double (not in-double)) (cons ?\" out)))
  2726. (?\\ (unless (or in-single in-double)
  2727. (error "Can't handle backslash outside string in `org-babel-script-escape'"))
  2728. (setq backslash t)
  2729. out)
  2730. (t (cons ch out))))))
  2731. (string-to-list str))
  2732. (when (or in-single in-double)
  2733. (error "Unterminated string in `org-babel-script-escape'"))
  2734. (apply #'string (reverse out))))
  2735. (defun org-babel-script-escape (str &optional force)
  2736. "Safely convert tables into elisp lists."
  2737. (unless (stringp str)
  2738. (error "`org-babel-script-escape' expects a string"))
  2739. (let ((escaped
  2740. (cond
  2741. ((and (> (length str) 2)
  2742. (or (and (string-equal "[" (substring str 0 1))
  2743. (string-equal "]" (substring str -1)))
  2744. (and (string-equal "{" (substring str 0 1))
  2745. (string-equal "}" (substring str -1)))
  2746. (and (string-equal "(" (substring str 0 1))
  2747. (string-equal ")" (substring str -1)))))
  2748. (concat "'" (org-babel--script-escape-inner str)))
  2749. ((or force
  2750. (and (> (length str) 2)
  2751. (or (and (string-equal "'" (substring str 0 1))
  2752. (string-equal "'" (substring str -1)))
  2753. ;; We need to pass double-quoted strings
  2754. ;; through the backslash-twiddling bits, even
  2755. ;; though we don't need to change their
  2756. ;; delimiters.
  2757. (and (string-equal "\"" (substring str 0 1))
  2758. (string-equal "\"" (substring str -1))))))
  2759. (org-babel--script-escape-inner str))
  2760. (t str))))
  2761. (condition-case nil (org-babel-read escaped) (error escaped))))
  2762. (defun org-babel-read (cell &optional inhibit-lisp-eval)
  2763. "Convert the string value of CELL to a number if appropriate.
  2764. Otherwise if CELL looks like lisp (meaning it starts with a
  2765. \"(\", \"\\='\", \"\\=`\" or a \"[\") then read and evaluate it as
  2766. lisp, otherwise return it unmodified as a string. Optional
  2767. argument INHIBIT-LISP-EVAL inhibits lisp evaluation for
  2768. situations in which is it not appropriate."
  2769. (cond ((not (org-string-nw-p cell)) cell)
  2770. ((org-babel--string-to-number cell))
  2771. ((and (not inhibit-lisp-eval)
  2772. (or (memq (string-to-char cell) '(?\( ?' ?` ?\[))
  2773. (string= cell "*this*")))
  2774. (eval (read cell) t))
  2775. ((eq (string-to-char cell) ?\") (read cell))
  2776. (t (org-no-properties cell))))
  2777. (defun org-babel--string-to-number (string)
  2778. "If STRING represents a number return its value.
  2779. Otherwise return nil."
  2780. (unless (string-match-p "\\s-" (org-trim string))
  2781. (let ((interned-string (ignore-errors (read string))))
  2782. (when (numberp interned-string)
  2783. interned-string))))
  2784. (defun org-babel-import-elisp-from-file (file-name &optional separator)
  2785. "Read the results located at FILE-NAME into an elisp table.
  2786. If the table is trivial, then return it as a scalar."
  2787. (let ((result
  2788. (with-temp-buffer
  2789. (condition-case err
  2790. (progn
  2791. (org-table-import file-name separator)
  2792. (delete-file file-name)
  2793. (delq nil
  2794. (mapcar (lambda (row)
  2795. (and (not (eq row 'hline))
  2796. (mapcar #'org-babel-string-read row)))
  2797. (org-table-to-lisp))))
  2798. (error
  2799. (display-warning 'org-babel
  2800. (format "Error reading results: %S" err)
  2801. :error)
  2802. nil)))))
  2803. (pcase result
  2804. (`((,scalar)) scalar)
  2805. (`((,_ ,_ . ,_)) result)
  2806. (`(,scalar) scalar)
  2807. (_ result))))
  2808. (defun org-babel-string-read (cell)
  2809. "Strip nested \"s from around strings."
  2810. (org-babel-read (or (and (stringp cell)
  2811. (string-match "\"\\(.+\\)\"" cell)
  2812. (match-string 1 cell))
  2813. cell) t))
  2814. (defun org-babel-chomp (string &optional regexp)
  2815. "Strip a trailing space or carriage return from STRING.
  2816. The default regexp used is \"[ \\f\\t\\n\\r\\v]\" but another one
  2817. can be specified as the REGEXP argument."
  2818. (let ((regexp (or regexp "[ \f\t\n\r\v]")))
  2819. (while (and (> (length string) 0)
  2820. (string-match regexp (substring string -1)))
  2821. (setq string (substring string 0 -1)))
  2822. string))
  2823. (defun org-babel-process-file-name (name &optional no-quote-p)
  2824. "Prepare NAME to be used in an external process.
  2825. If NAME specifies a remote location, the remote portion of the
  2826. name is removed, since in that case the process will be executing
  2827. remotely. The file name is then processed by `expand-file-name'.
  2828. Unless second argument NO-QUOTE-P is non-nil, the file name is
  2829. additionally processed by `shell-quote-argument'."
  2830. (let ((f (org-babel-local-file-name (expand-file-name name))))
  2831. (if no-quote-p f (shell-quote-argument f))))
  2832. (defvar org-babel-temporary-directory)
  2833. (unless (or noninteractive (boundp 'org-babel-temporary-directory))
  2834. (defvar org-babel-temporary-directory
  2835. (or (and (boundp 'org-babel-temporary-directory)
  2836. (file-exists-p org-babel-temporary-directory)
  2837. org-babel-temporary-directory)
  2838. (make-temp-file "babel-" t))
  2839. "Directory to hold temporary files created to execute code blocks.
  2840. Used by `org-babel-temp-file'. This directory will be removed on
  2841. Emacs shutdown."))
  2842. (defcustom org-babel-remote-temporary-directory "/tmp/"
  2843. "Directory to hold temporary files on remote hosts."
  2844. :group 'org-babel
  2845. :type 'string)
  2846. (defmacro org-babel-result-cond (result-params scalar-form &rest table-forms)
  2847. "Call the code to parse raw string results according to RESULT-PARAMS."
  2848. (declare (indent 1)
  2849. (debug (form form &rest form)))
  2850. (org-with-gensyms (params)
  2851. `(let ((,params ,result-params))
  2852. (unless (member "none" ,params)
  2853. (if (or (member "scalar" ,params)
  2854. (member "verbatim" ,params)
  2855. (member "html" ,params)
  2856. (member "code" ,params)
  2857. (member "pp" ,params)
  2858. (member "file" ,params)
  2859. (and (or (member "output" ,params)
  2860. (member "raw" ,params)
  2861. (member "org" ,params)
  2862. (member "drawer" ,params))
  2863. (not (member "table" ,params))))
  2864. ,scalar-form
  2865. ,@table-forms)))))
  2866. (def-edebug-spec org-babel-result-cond (form form body))
  2867. (defun org-babel-temp-file (prefix &optional suffix)
  2868. "Create a temporary file in the `org-babel-temporary-directory'.
  2869. Passes PREFIX and SUFFIX directly to `make-temp-file' with the
  2870. value of `temporary-file-directory' temporarily set to the value
  2871. of `org-babel-temporary-directory'."
  2872. (if (file-remote-p default-directory)
  2873. (let ((prefix
  2874. (concat (file-remote-p default-directory)
  2875. (expand-file-name
  2876. prefix org-babel-remote-temporary-directory))))
  2877. (make-temp-file prefix nil suffix))
  2878. (let ((temporary-file-directory
  2879. (or (and (boundp 'org-babel-temporary-directory)
  2880. (file-exists-p org-babel-temporary-directory)
  2881. org-babel-temporary-directory)
  2882. temporary-file-directory)))
  2883. (make-temp-file prefix nil suffix))))
  2884. (defun org-babel-remove-temporary-directory ()
  2885. "Remove `org-babel-temporary-directory' on Emacs shutdown."
  2886. (when (and (boundp 'org-babel-temporary-directory)
  2887. (file-exists-p org-babel-temporary-directory))
  2888. ;; taken from `delete-directory' in files.el
  2889. (condition-case nil
  2890. (progn
  2891. (mapc (lambda (file)
  2892. ;; This test is equivalent to
  2893. ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
  2894. ;; but more efficient
  2895. (if (eq t (car (file-attributes file)))
  2896. (delete-directory file)
  2897. (delete-file file)))
  2898. (directory-files org-babel-temporary-directory 'full
  2899. directory-files-no-dot-files-regexp))
  2900. (delete-directory org-babel-temporary-directory))
  2901. (error
  2902. (message "Failed to remove temporary Org-babel directory %s"
  2903. (if (boundp 'org-babel-temporary-directory)
  2904. org-babel-temporary-directory
  2905. "[directory not defined]"))))))
  2906. (add-hook 'kill-emacs-hook 'org-babel-remove-temporary-directory)
  2907. (defun org-babel-one-header-arg-safe-p (pair safe-list)
  2908. "Determine if the PAIR is a safe babel header arg according to SAFE-LIST.
  2909. For the format of SAFE-LIST, see `org-babel-safe-header-args'."
  2910. (and (consp pair)
  2911. (keywordp (car pair))
  2912. (stringp (cdr pair))
  2913. (or
  2914. (memq (car pair) safe-list)
  2915. (let ((entry (assq (car pair) safe-list)))
  2916. (and entry
  2917. (consp entry)
  2918. (cond ((functionp (cdr entry))
  2919. (funcall (cdr entry) (cdr pair)))
  2920. ((listp (cdr entry))
  2921. (member (cdr pair) (cdr entry)))
  2922. (t nil)))))))
  2923. (defun org-babel-generate-file-param (src-name params)
  2924. "Calculate the filename for source block results.
  2925. The directory is calculated from the :output-dir property of the
  2926. source block; if not specified, use the current directory.
  2927. If the source block has a #+NAME and the :file parameter does not
  2928. contain any period characters, then the :file parameter is
  2929. treated as an extension, and the output file name is the
  2930. concatenation of the directory (as calculated above), the block
  2931. name, a period, and the parameter value as a file extension.
  2932. Otherwise, the :file parameter is treated as a full file name,
  2933. and the output file name is the directory (as calculated above)
  2934. plus the parameter value."
  2935. (let* ((file-cons (assq :file params))
  2936. (file-ext-cons (assq :file-ext params))
  2937. (file-ext (cdr-safe file-ext-cons))
  2938. (dir (cdr-safe (assq :output-dir params)))
  2939. fname)
  2940. ;; create the output-dir if it does not exist
  2941. (when dir
  2942. (make-directory dir t))
  2943. (if file-cons
  2944. ;; :file given; add :output-dir if given
  2945. (when dir
  2946. (setcdr file-cons (concat (file-name-as-directory dir) (cdr file-cons))))
  2947. ;; :file not given; compute from name and :file-ext if possible
  2948. (when (and src-name file-ext)
  2949. (if dir
  2950. (setq fname (concat (file-name-as-directory (or dir ""))
  2951. src-name "." file-ext))
  2952. (setq fname (concat src-name "." file-ext)))
  2953. (setq params (cons (cons :file fname) params))))
  2954. params))
  2955. (defun org-babel-graphical-output-file (params)
  2956. "File where a babel block should send graphical output, per PARAMS.
  2957. Return nil if no graphical output is expected. Raise an error if
  2958. the output file is ill-defined."
  2959. (let ((file (cdr (assq :file params))))
  2960. (cond (file (and (member "graphics" (cdr (assq :result-params params)))
  2961. file))
  2962. ((assq :file-ext params)
  2963. (user-error ":file-ext given but no :file generated; did you forget \
  2964. to name a block?"))
  2965. (t (user-error "No :file header argument given; cannot create \
  2966. graphical result")))))
  2967. (defun org-babel-make-language-alias (new old)
  2968. "Make source blocks of type NEW aliases for those of type OLD.
  2969. NEW and OLD should be strings. This function should be called
  2970. after the babel API for OLD-type source blocks is fully defined.
  2971. Callers of this function will probably want to add an entry to
  2972. `org-src-lang-modes' as well."
  2973. (dolist (fn '("execute" "expand-body" "prep-session"
  2974. "variable-assignments" "load-session"
  2975. "edit-prep"))
  2976. (let ((sym (intern-soft (concat "org-babel-" fn ":" old))))
  2977. (when (and sym (fboundp sym))
  2978. (defalias (intern (concat "org-babel-" fn ":" new)) sym))))
  2979. ;; Technically we don't need a `dolist' for just one variable, but
  2980. ;; we keep it for symmetry/ease of future expansion.
  2981. (dolist (var '("default-header-args"))
  2982. (let ((sym (intern-soft (concat "org-babel-" var ":" old))))
  2983. (when (and sym (boundp sym))
  2984. (defvaralias (intern (concat "org-babel-" var ":" new)) sym)))))
  2985. (provide 'ob-core)
  2986. ;; Local variables:
  2987. ;; generated-autoload-file: "org-loaddefs.el"
  2988. ;; End:
  2989. ;;; ob-core.el ends here