ob-core.el 118 KB

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