ob-core.el 120 KB

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