ob-core.el 121 KB

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