ob-core.el 132 KB

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