ob-core.el 127 KB

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