ob-core.el 102 KB

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