ob-core.el 119 KB

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