ob-core.el 132 KB

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