ob-core.el 125 KB

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