ob-core.el 111 KB

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