ob-core.el 121 KB

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