ob-core.el 118 KB

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