ob-core.el 121 KB

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