ob-core.el 118 KB

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