ob-core.el 110 KB

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