ob-core.el 111 KB

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