ob-core.el 119 KB

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