ob-core.el 125 KB

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