ob-core.el 120 KB

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