ob-core.el 119 KB

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