ob-core.el 119 KB

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