ob-core.el 118 KB

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