ob-core.el 110 KB

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