ob-core.el 121 KB

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