ob-core.el 120 KB

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