ob-core.el 130 KB

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