ob.el 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773
  1. ;;; ob.el --- working with code blocks in org-mode
  2. ;; Copyright (C) 2009, 2010 Free Software Foundation, Inc.
  3. ;; Author: Eric Schulte, Dan Davison
  4. ;; Keywords: literate programming, reproducible research
  5. ;; Homepage: http://orgmode.org
  6. ;; Version: 7.01trans
  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. ;;; Commentary:
  19. ;; See the online documentation for more information
  20. ;;
  21. ;; http://orgmode.org/worg/org-contrib/babel/
  22. ;;; Code:
  23. (eval-when-compile
  24. (require 'cl))
  25. (require 'org-macs)
  26. (defvar org-babel-call-process-region-original)
  27. (declare-function show-all "outline" ())
  28. (declare-function tramp-compat-make-temp-file "tramp-compat"
  29. (filename &optional dir-flag))
  30. (declare-function tramp-dissect-file-name "tramp" (name &optional nodefault))
  31. (declare-function tramp-file-name-user "tramp" (vec))
  32. (declare-function tramp-file-name-host "tramp" (vec))
  33. (declare-function with-parsed-tramp-file-name "tramp" (filename var &rest body))
  34. (declare-function org-icompleting-read "org" (&rest args))
  35. (declare-function org-edit-src-code "org-src"
  36. (&optional context code edit-buffer-name quietp))
  37. (declare-function org-edit-src-exit "org-src" (&optional context))
  38. (declare-function org-open-at-point "org" (&optional in-emacs reference-buffer))
  39. (declare-function org-save-outline-visibility "org" (use-markers &rest body))
  40. (declare-function org-outline-overlay-data "org" (&optional use-markers))
  41. (declare-function org-set-outline-overlay-data "org" (data))
  42. (declare-function org-narrow-to-subtree "org" ())
  43. (declare-function org-entry-get "org" (pom property &optional inherit literal-nil))
  44. (declare-function org-make-options-regexp "org" (kwds &optional extra))
  45. (declare-function org-do-remove-indentation "org" (&optional n))
  46. (declare-function org-show-context "org" (&optional key))
  47. (declare-function org-at-table-p "org" (&optional table-type))
  48. (declare-function org-cycle "org" (&optional arg))
  49. (declare-function org-uniquify "org" (list))
  50. (declare-function org-table-import "org-table" (file arg))
  51. (declare-function org-add-hook "org-compat" (hook function &optional append local))
  52. (declare-function org-table-align "org-table" ())
  53. (declare-function org-table-end "org-table" (&optional table-type))
  54. (declare-function orgtbl-to-generic "org-table" (table params))
  55. (declare-function orgtbl-to-orgtbl "org-table" (table params))
  56. (declare-function org-babel-lob-get-info "ob-lob" nil)
  57. (declare-function org-babel-ref-split-args "ob-ref" (arg-string))
  58. (declare-function org-babel-ref-variables "ob-ref" (params))
  59. (declare-function org-babel-ref-resolve-reference "ob-ref" (ref &optional params))
  60. (declare-function org-babel-lob-execute-maybe "ob-lob" ())
  61. (defgroup org-babel nil
  62. "Code block evaluation and management in `org-mode' documents."
  63. :tag "Babel"
  64. :group 'org)
  65. (defcustom org-confirm-babel-evaluate t
  66. "Confirm before evaluation.
  67. Require confirmation before interactively evaluating code
  68. blocks in Org-mode buffers. The default value of this variable
  69. is t, meaning confirmation is required for any code block
  70. evaluation. This variable can be set to nil to inhibit any
  71. future confirmation requests. This variable can also be set to a
  72. function which takes two arguments the language of the code block
  73. and the body of the code block. Such a function should then
  74. return a non-nil value if the user should be prompted for
  75. execution or nil if no prompt is required.
  76. Warning: Disabling confirmation may result in accidental
  77. evaluation of potentially harmful code. It may be advisable
  78. remove code block execution from C-c C-c as further protection
  79. against accidental code block evaluation. The
  80. `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
  81. remove code block execution from the C-c C-c keybinding."
  82. :group 'org-babel
  83. :type '(choice boolean function))
  84. ;; don't allow this variable to be changed through file settings
  85. (put 'org-confirm-babel-evaluate 'safe-local-variable (lambda (x) (eq x t)))
  86. (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
  87. "Remove code block evaluation from the C-c C-c key binding."
  88. :group 'org-babel
  89. :type 'boolean)
  90. (defvar org-babel-src-name-regexp
  91. "^[ \t]*#\\+\\(srcname\\|source\\|function\\):[ \t]*"
  92. "Regular expression used to match a source name line.")
  93. (defvar org-babel-src-name-w-name-regexp
  94. (concat org-babel-src-name-regexp
  95. "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)")
  96. "Regular expression matching source name lines with a name.")
  97. (defvar org-babel-src-block-regexp
  98. (concat
  99. ;; (1) indentation (2) lang
  100. "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
  101. ;; (3) switches
  102. "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
  103. ;; (4) header arguments
  104. "\\([^\n]*\\)\n"
  105. ;; (5) body
  106. "\\([^\000]+?\n\\)[ \t]*#\\+end_src")
  107. "Regexp used to identify code blocks.")
  108. (defvar org-babel-inline-src-block-regexp
  109. (concat
  110. ;; (1) replacement target (2) lang
  111. "[ \f\t\n\r\v]\\(src_\\([^ \f\t\n\r\v]+\\)"
  112. ;; (3,4) (unused, headers)
  113. "\\(\\|\\[\\(.*?\\)\\]\\)"
  114. ;; (5) body
  115. "{\\([^\f\n\r\v]+?\\)}\\)")
  116. "Regexp used to identify inline src-blocks.")
  117. (defun org-babel-get-src-block-info (&optional header-vars-only)
  118. "Get information on the current source block.
  119. Returns a list
  120. (language body header-arguments-alist switches name function-args indent).
  121. Unless HEADER-VARS-ONLY is non-nil, any variable
  122. references provided in 'function call style' (i.e. in a
  123. parenthesised argument list following the src block name) are
  124. added to the header-arguments-alist."
  125. (let ((case-fold-search t) head info args indent)
  126. (if (setq head (org-babel-where-is-src-block-head))
  127. (save-excursion
  128. (goto-char head)
  129. (setq info (org-babel-parse-src-block-match))
  130. (setq indent (car (last info)))
  131. (setq info (butlast info))
  132. (forward-line -1)
  133. (if (and (looking-at org-babel-src-name-w-name-regexp)
  134. (match-string 2))
  135. (progn
  136. (setq info (append info (list (org-babel-clean-text-properties
  137. (match-string 2)))))
  138. ;; Note that e.g. "name()" and "name( )" result in
  139. ;; ((:var . "")). We maintain that behaviour, and the
  140. ;; resulting non-nil sixth element is relied upon in
  141. ;; org-babel-exp-code to detect a functional-style
  142. ;; block in those cases. However, "name" without any
  143. ;; parentheses would result in the same thing, so we
  144. ;; explicitly avoid that.
  145. (if (setq args (match-string 4))
  146. (setq info
  147. (append info (list
  148. (mapcar
  149. (lambda (ref) (cons :var ref))
  150. (org-babel-ref-split-args args))))))
  151. (unless header-vars-only
  152. (setf (nth 2 info)
  153. (org-babel-merge-params (nth 5 info) (nth 2 info)))))
  154. (setq info (append info (list nil nil))))
  155. (append info (list indent)))
  156. (if (save-excursion ;; inline source block
  157. (re-search-backward "[ \f\t\n\r\v]" nil t)
  158. (looking-at org-babel-inline-src-block-regexp))
  159. (org-babel-parse-inline-src-block-match)
  160. nil))))
  161. (defun org-babel-confirm-evaluate (info)
  162. "Confirm evaluation of the code block INFO.
  163. This behavior can be suppressed by setting the value of
  164. `org-confirm-babel-evaluate' to nil, in which case all future
  165. interactive code block evaluations will proceed without any
  166. confirmation from the user.
  167. Note disabling confirmation may result in accidental evaluation
  168. of potentially harmful code."
  169. (let* ((eval (or (cdr (assoc :eval (nth 2 info)))
  170. (when (assoc :noeval (nth 2 info)) "no")))
  171. (query (or (equal eval "query")
  172. (and (functionp org-confirm-babel-evaluate)
  173. (funcall org-confirm-babel-evaluate
  174. (nth 0 info) (nth 1 info)))
  175. org-confirm-babel-evaluate)))
  176. (if (or (equal eval "never") (equal eval "no")
  177. (and query
  178. (not (yes-or-no-p
  179. (format "Evaluate this%scode on your system? "
  180. (if info (format " %s " (nth 0 info)) " "))))))
  181. (prog1 nil (message "evaluation aborted"))
  182. t)))
  183. ;;;###autoload
  184. (defun org-babel-execute-safely-maybe ()
  185. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  186. (org-babel-execute-maybe)))
  187. (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-execute-safely-maybe)
  188. ;;;###autoload
  189. (defun org-babel-execute-maybe ()
  190. (interactive)
  191. (or (org-babel-execute-src-block-maybe)
  192. (org-babel-lob-execute-maybe)))
  193. (defun org-babel-execute-src-block-maybe ()
  194. "Conditionally execute a source block.
  195. Detect if this is context for a Babel src-block and if so
  196. then run `org-babel-execute-src-block'."
  197. (interactive)
  198. (let ((info (org-babel-get-src-block-info)))
  199. (if info
  200. (progn (org-babel-execute-src-block current-prefix-arg info) t) nil)))
  201. ;;;###autoload
  202. (defun org-babel-expand-src-block-maybe ()
  203. "Conditionally expand a source block.
  204. Detect if this is context for a org-babel src-block and if so
  205. then run `org-babel-expand-src-block'."
  206. (interactive)
  207. (let ((info (org-babel-get-src-block-info)))
  208. (if info
  209. (progn (org-babel-expand-src-block current-prefix-arg info) t)
  210. nil)))
  211. ;;;###autoload
  212. (defun org-babel-load-in-session-maybe ()
  213. "Conditionally load a source block in a session.
  214. Detect if this is context for a org-babel src-block and if so
  215. then run `org-babel-load-in-session'."
  216. (interactive)
  217. (let ((info (org-babel-get-src-block-info)))
  218. (if info
  219. (progn (org-babel-load-in-session current-prefix-arg info) t)
  220. nil)))
  221. (add-hook 'org-metaup-hook 'org-babel-load-in-session-maybe)
  222. ;;;###autoload
  223. (defun org-babel-pop-to-session-maybe ()
  224. "Conditionally pop to a session.
  225. Detect if this is context for a org-babel src-block and if so
  226. then run `org-babel-pop-to-session'."
  227. (interactive)
  228. (let ((info (org-babel-get-src-block-info)))
  229. (if info (progn (org-babel-pop-to-session current-prefix-arg info) t) nil)))
  230. (add-hook 'org-metadown-hook 'org-babel-pop-to-session-maybe)
  231. (defconst org-babel-header-arg-names
  232. '(cache cmdline colnames dir exports file noweb results
  233. session tangle var eval noeval comments)
  234. "Common header arguments used by org-babel.
  235. Note that individual languages may define their own language
  236. specific header arguments as well.")
  237. (defvar org-babel-default-header-args
  238. '((:session . "none") (:results . "replace") (:exports . "code")
  239. (:cache . "no") (:noweb . "no") (:hlines . "no") (:tangle . "no"))
  240. "Default arguments to use when evaluating a source block.")
  241. (defvar org-babel-default-inline-header-args
  242. '((:session . "none") (:results . "silent") (:exports . "results"))
  243. "Default arguments to use when evaluating an inline source block.")
  244. (defvar org-babel-current-buffer-properties)
  245. (make-variable-buffer-local 'org-babel-current-buffer-properties)
  246. (defvar org-babel-result-regexp
  247. "^[ \t]*#\\+res\\(ults\\|name\\)\\(\\[\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*"
  248. "Regular expression used to match result lines.
  249. If the results are associated with a hash key then the hash will
  250. be saved in the second match data.")
  251. (defvar org-babel-result-w-name-regexp
  252. (concat org-babel-result-regexp
  253. "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
  254. (defvar org-babel-min-lines-for-block-output 10
  255. "The minimum number of lines for block output.
  256. If number of lines of output is equal to or exceeds this
  257. value, the output is placed in a #+begin_example...#+end_example
  258. block. Otherwise the output is marked as literal by inserting
  259. colons at the starts of the lines. This variable only takes
  260. effect if the :results output option is in effect.")
  261. (defvar org-babel-noweb-error-langs nil
  262. "Languages for which Babel will raise literate programming errors.
  263. List of languages for which errors should be raised when the
  264. source code block satisfying a noweb reference in this language
  265. can not be resolved.")
  266. (defvar org-babel-hash-show 4
  267. "Number of initial characters to show of a hidden results hash.")
  268. (defvar org-babel-after-execute-hook nil
  269. "Hook for functions to be called after `org-babel-execute-src-block'")
  270. (defun org-babel-named-src-block-regexp-for-name (name)
  271. "This generates a regexp used to match a src block named NAME."
  272. (concat org-babel-src-name-regexp (regexp-quote name) "[ \t\n]*"
  273. (substring org-babel-src-block-regexp 1)))
  274. ;;; functions
  275. (defvar call-process-region)
  276. ;;;###autoload
  277. (defun org-babel-execute-src-block (&optional arg info params)
  278. "Execute the current source code block.
  279. Insert the results of execution into the buffer. Source code
  280. execution and the collection and formatting of results can be
  281. controlled through a variety of header arguments.
  282. With prefix argument ARG, force re-execution even if a an
  283. existing result cached in the buffer would otherwise have been
  284. returned.
  285. Optionally supply a value for INFO in the form returned by
  286. `org-babel-get-src-block-info'.
  287. Optionally supply a value for PARAMS which will be merged with
  288. the header arguments specified at the front of the source code
  289. block."
  290. (interactive)
  291. (let ((info (or info (org-babel-get-src-block-info))))
  292. (when (org-babel-confirm-evaluate info)
  293. (let* ((lang (nth 0 info))
  294. (params (setf
  295. (nth 2 info)
  296. (sort (org-babel-merge-params (nth 2 info) params)
  297. (lambda (el1 el2) (string< (symbol-name (car el1))
  298. (symbol-name (car el2)))))))
  299. (new-hash
  300. (if (and (cdr (assoc :cache params))
  301. (string= "yes" (cdr (assoc :cache params))))
  302. (org-babel-sha1-hash info)))
  303. (old-hash (org-babel-result-hash info))
  304. (body (setf (nth 1 info)
  305. (if (and (cdr (assoc :noweb params))
  306. (string= "yes" (cdr (assoc :noweb params))))
  307. (org-babel-expand-noweb-references info)
  308. (nth 1 info))))
  309. (result-params (split-string (or (cdr (assoc :results params)) "")))
  310. (result-type (cond ((member "output" result-params) 'output)
  311. ((member "value" result-params) 'value)
  312. (t 'value)))
  313. (cmd (intern (concat "org-babel-execute:" lang)))
  314. (dir (cdr (assoc :dir params)))
  315. (default-directory
  316. (or (and dir (file-name-as-directory dir)) default-directory))
  317. (org-babel-call-process-region-original
  318. (if (boundp 'org-babel-call-process-region-original)
  319. org-babel-call-process-region-original
  320. (symbol-function 'call-process-region)))
  321. (indent (car (last info)))
  322. result)
  323. (unwind-protect
  324. (flet ((call-process-region (&rest args)
  325. (apply 'org-babel-tramp-handle-call-process-region args)))
  326. (unless (fboundp cmd)
  327. (error "No org-babel-execute function for %s!" lang))
  328. (if (and (not arg) new-hash (equal new-hash old-hash))
  329. (save-excursion ;; return cached result
  330. (goto-char (org-babel-where-is-src-block-result nil info))
  331. (end-of-line 1) (forward-char 1)
  332. (setq result (org-babel-read-result))
  333. (message (replace-regexp-in-string
  334. "%" "%%" (format "%S" result))) result)
  335. (message "executing %s code block%s..."
  336. (capitalize lang)
  337. (if (nth 4 info) (format " (%s)" (nth 4 info)) ""))
  338. (setq result (funcall cmd body params))
  339. (if (eq result-type 'value)
  340. (setq result (if (and (or (member "vector" result-params)
  341. (member "table" result-params))
  342. (not (listp result)))
  343. (list (list result))
  344. result)))
  345. (org-babel-insert-result
  346. result result-params info new-hash indent lang)
  347. (run-hooks 'org-babel-after-execute-hook)
  348. result))
  349. (setq call-process-region 'org-babel-call-process-region-original))))))
  350. (defun org-babel-expand-body:generic (body params &optional processed-params)
  351. "Expand BODY with PARAMS.
  352. Expand a block of code with org-babel according to it's header
  353. arguments. This generic implementation of body expansion is
  354. called for languages which have not defined their own specific
  355. org-babel-expand-body:lang function." body)
  356. ;;;###autoload
  357. (defun org-babel-expand-src-block (&optional arg info params)
  358. "Expand the current source code block.
  359. Expand according to the source code block's header
  360. arguments and pop open the results in a preview buffer."
  361. (interactive)
  362. (let* ((info (or info (org-babel-get-src-block-info)))
  363. (lang (nth 0 info))
  364. (params (setf (nth 2 info)
  365. (sort (org-babel-merge-params (nth 2 info) params)
  366. (lambda (el1 el2) (string< (symbol-name (car el1))
  367. (symbol-name (car el2)))))))
  368. (body (setf (nth 1 info)
  369. (if (and (cdr (assoc :noweb params))
  370. (string= "yes" (cdr (assoc :noweb params))))
  371. (org-babel-expand-noweb-references info) (nth 1 info))))
  372. (cmd (intern (concat "org-babel-expand-body:" lang)))
  373. (expanded (funcall (if (fboundp cmd) cmd 'org-babel-expand-body:generic)
  374. body params)))
  375. (org-edit-src-code
  376. nil expanded (concat "*Org-Babel Preview " (buffer-name) "[ " lang " ]*"))))
  377. ;;;###autoload
  378. (defun org-babel-load-in-session (&optional arg info)
  379. "Load the body of the current source-code block.
  380. Evaluate the header arguments for the source block before
  381. entering the session. After loading the body this pops open the
  382. session."
  383. (interactive)
  384. (let* ((info (or info (org-babel-get-src-block-info)))
  385. (lang (nth 0 info))
  386. (params (nth 2 info))
  387. (body (setf (nth 1 info)
  388. (if (and (cdr (assoc :noweb params))
  389. (string= "yes" (cdr (assoc :noweb params))))
  390. (org-babel-expand-noweb-references info)
  391. (nth 1 info))))
  392. (session (cdr (assoc :session params)))
  393. (dir (cdr (assoc :dir params)))
  394. (default-directory
  395. (or (and dir (file-name-as-directory dir)) default-directory))
  396. (cmd (intern (concat "org-babel-load-session:" lang))))
  397. (unless (fboundp cmd)
  398. (error "No org-babel-load-session function for %s!" lang))
  399. (pop-to-buffer (funcall cmd session body params))
  400. (end-of-line 1)))
  401. ;;;###autoload
  402. (defun org-babel-initiate-session (&optional arg info)
  403. "Initiate session for current code block.
  404. If called with a prefix argument then evaluate the header arguments
  405. for the code block before entering the session. Copy the body
  406. of the code block to the kill ring."
  407. (interactive "P")
  408. (let* ((info (or info (org-babel-get-src-block-info)))
  409. (lang (nth 0 info))
  410. (body (nth 1 info))
  411. (params (nth 2 info))
  412. (session (cdr (assoc :session params)))
  413. (dir (cdr (assoc :dir params)))
  414. (default-directory
  415. (or (and dir (file-name-as-directory dir)) default-directory))
  416. (cmd (intern (format "org-babel-%s-initiate-session" lang)))
  417. (cmd2 (intern (concat "org-babel-prep-session:" lang))))
  418. (if (and (stringp session) (string= session "none"))
  419. (error "This block is not using a session!"))
  420. (unless (fboundp cmd)
  421. (error "No org-babel-initiate-session function for %s!" lang))
  422. (with-temp-buffer (insert (org-babel-trim body))
  423. (copy-region-as-kill (point-min) (point-max)))
  424. (when arg
  425. (unless (fboundp cmd2)
  426. (error "No org-babel-prep-session function for %s!" lang))
  427. (funcall cmd2 session params))
  428. (funcall cmd session params)))
  429. ;;;###autoload
  430. (defun org-babel-switch-to-session (&optional arg info)
  431. "Switch to the session of the current code block.
  432. Uses `org-babel-initiate-session' to start the session. If called
  433. with a prefix argument then this is passed on to
  434. `org-babel-initiate-session'."
  435. (interactive "P")
  436. (pop-to-buffer (org-babel-initiate-session arg info))
  437. (end-of-line 1))
  438. (defalias 'org-babel-pop-to-session 'org-babel-switch-to-session)
  439. ;;;###autoload
  440. (defun org-babel-switch-to-session-with-code (&optional arg info)
  441. "Switch to code buffer and display session."
  442. (interactive "P")
  443. (flet ((swap-windows
  444. ()
  445. (let ((other-window-buffer (window-buffer (next-window))))
  446. (set-window-buffer (next-window) (current-buffer))
  447. (set-window-buffer (selected-window) other-window-buffer))
  448. (other-window 1)))
  449. (let ((info (org-babel-get-src-block-info))
  450. (org-src-window-setup 'reorganize-frame))
  451. (save-excursion
  452. (org-babel-switch-to-session arg info))
  453. (org-edit-src-code))
  454. (swap-windows)))
  455. (defmacro org-babel-do-in-edit-buffer (&rest body)
  456. "Evaluate BODY in edit buffer if there is a code block at point.
  457. Return t if a code block was found at point, nil otherwise."
  458. `(let ((org-src-window-setup 'switch-invisibly))
  459. (when (org-edit-src-code nil nil nil 'quietly)
  460. (unwind-protect (progn ,@body)
  461. (if (org-bound-and-true-p org-edit-src-from-org-mode)
  462. (org-edit-src-exit)))
  463. t)))
  464. (defun org-babel-do-key-sequence-in-edit-buffer (key)
  465. "Read key sequence and execute the command in edit buffer.
  466. Enter a key sequence to be executed in the language major-mode
  467. edit buffer. For example, TAB will alter the contents of the
  468. Org-mode code block according to the effect of TAB in the
  469. language major-mode buffer. For languages that support
  470. interactive sessions, this can be used to send code from the Org
  471. buffer to the session for evaluation using the native major-mode
  472. evaluation mechanisms."
  473. (interactive "kEnter key-sequence to execute in edit buffer: ")
  474. (org-babel-do-in-edit-buffer
  475. (call-interactively
  476. (key-binding (or key (read-key-sequence nil))))))
  477. (defvar org-bracket-link-regexp)
  478. ;;;###autoload
  479. (defun org-babel-open-src-block-result (&optional re-run)
  480. "If `point' is on a src block then open the results of the
  481. source code block, otherwise return nil. With optional prefix
  482. argument RE-RUN the source-code block is evaluated even if
  483. results already exist."
  484. (interactive "P")
  485. (when (org-babel-get-src-block-info)
  486. (save-excursion
  487. ;; go to the results, if there aren't any then run the block
  488. (goto-char (or (and (not re-run) (org-babel-where-is-src-block-result))
  489. (progn (org-babel-execute-src-block)
  490. (org-babel-where-is-src-block-result))))
  491. (end-of-line 1)
  492. (while (looking-at "[\n\r\t\f ]") (forward-char 1))
  493. ;; open the results
  494. (if (looking-at org-bracket-link-regexp)
  495. ;; file results
  496. (org-open-at-point)
  497. (let ((results (org-babel-read-result)))
  498. (flet ((echo-res (result)
  499. (if (stringp result) result (format "%S" result))))
  500. (pop-to-buffer (get-buffer-create "org-babel-results"))
  501. (delete-region (point-min) (point-max))
  502. (if (listp results)
  503. ;; table result
  504. (insert (orgtbl-to-generic results '(:sep "\t" :fmt echo-res)))
  505. ;; scalar result
  506. (insert (echo-res results))))))
  507. t)))
  508. ;;;###autoload
  509. (defun org-babel-execute-buffer (&optional arg)
  510. "Execute source code blocks in a buffer.
  511. Call `org-babel-execute-src-block' on every source block in
  512. the current buffer."
  513. (interactive "P")
  514. (save-excursion
  515. (org-save-outline-visibility t
  516. (goto-char (point-min))
  517. (show-all)
  518. (while (re-search-forward org-babel-src-block-regexp nil t)
  519. (let ((pos-end (match-end 0)))
  520. (goto-char (match-beginning 0))
  521. (org-babel-execute-src-block arg)
  522. (goto-char pos-end))))))
  523. ;;;###autoload
  524. (defun org-babel-execute-subtree (&optional arg)
  525. "Execute source code blocks in a subtree.
  526. Call `org-babel-execute-src-block' on every source block in
  527. the current subtree."
  528. (interactive "P")
  529. (save-restriction
  530. (save-excursion
  531. (org-narrow-to-subtree)
  532. (org-babel-execute-buffer arg)
  533. (widen))))
  534. ;;;###autoload
  535. (defun org-babel-sha1-hash (&optional info)
  536. "Generate an sha1 hash based on the value of info."
  537. (interactive)
  538. (let* ((info (or info (org-babel-get-src-block-info)))
  539. (hash (sha1 (format "%s-%s" (mapconcat (lambda (arg) (format "%S" arg))
  540. (nth 2 info) ":")
  541. (nth 1 info)))))
  542. (when (interactive-p) (message hash))
  543. hash))
  544. (defun org-babel-result-hash (&optional info)
  545. "Return the in-buffer hash associated with INFO."
  546. (org-babel-where-is-src-block-result nil info)
  547. (org-babel-clean-text-properties (match-string 3)))
  548. (defun org-babel-hide-hash ()
  549. "Hide the hash in the current results line.
  550. Only the initial `org-babel-hash-show' characters of the hash
  551. will remain visible."
  552. (add-to-invisibility-spec '(org-babel-hide-hash . t))
  553. (save-excursion
  554. (when (and (re-search-forward org-babel-result-regexp nil t)
  555. (match-string 3))
  556. (let* ((start (match-beginning 3))
  557. (hide-start (+ org-babel-hash-show start))
  558. (end (match-end 3))
  559. (hash (match-string 3))
  560. ov1 ov2)
  561. (setq ov1 (make-overlay start hide-start))
  562. (setq ov2 (make-overlay hide-start end))
  563. (overlay-put ov2 'invisible 'org-babel-hide-hash)
  564. (overlay-put ov1 'babel-hash hash)))))
  565. (defun org-babel-hide-all-hashes ()
  566. "Hide the hash in the current buffer.
  567. Only the initial `org-babel-hash-show' characters of each hash
  568. will remain visible. This function should be called as part of
  569. the `org-mode-hook'."
  570. (save-excursion
  571. (while (re-search-forward org-babel-result-regexp nil t)
  572. (goto-char (match-beginning 0))
  573. (org-babel-hide-hash)
  574. (goto-char (match-end 0)))))
  575. (add-hook 'org-mode-hook 'org-babel-hide-all-hashes)
  576. (defun org-babel-hash-at-point (&optional point)
  577. "Return the value of the hash at POINT.
  578. The hash is also added as the last element of the kill ring.
  579. This can be called with C-c C-c."
  580. (interactive)
  581. (let ((hash (car (delq nil (mapcar
  582. (lambda (ol) (overlay-get ol 'babel-hash))
  583. (overlays-at (or point (point))))))))
  584. (when hash (kill-new hash) (message hash))))
  585. (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-hash-at-point)
  586. (defun org-babel-result-hide-spec ()
  587. "Hide portions of results lines.
  588. Add `org-babel-hide-result' as an invisibility spec for hiding
  589. portions of results lines."
  590. (add-to-invisibility-spec '(org-babel-hide-result . t)))
  591. (add-hook 'org-mode-hook 'org-babel-result-hide-spec)
  592. (defvar org-babel-hide-result-overlays nil
  593. "Overlays hiding results.")
  594. (defun org-babel-result-hide-all ()
  595. "Fold all results in the current buffer."
  596. (interactive)
  597. (org-babel-show-result-all)
  598. (save-excursion
  599. (while (re-search-forward org-babel-result-regexp nil t)
  600. (save-excursion (goto-char (match-beginning 0))
  601. (org-babel-hide-result-toggle-maybe)))))
  602. (defun org-babel-show-result-all ()
  603. "Unfold all results in the current buffer."
  604. (mapc 'delete-overlay org-babel-hide-result-overlays)
  605. (setq org-babel-hide-result-overlays nil))
  606. ;;;###autoload
  607. (defun org-babel-hide-result-toggle-maybe ()
  608. "Toggle visibility of result at point."
  609. (interactive)
  610. (let ((case-fold-search t))
  611. (if (save-excursion
  612. (beginning-of-line 1)
  613. (looking-at org-babel-result-regexp))
  614. (progn (org-babel-hide-result-toggle)
  615. t) ;; to signal that we took action
  616. nil))) ;; to signal that we did not
  617. (defun org-babel-hide-result-toggle (&optional force)
  618. "Toggle the visibility of the current result."
  619. (interactive)
  620. (save-excursion
  621. (beginning-of-line)
  622. (if (re-search-forward org-babel-result-regexp nil t)
  623. (let ((start (progn (beginning-of-line 2) (- (point) 1)))
  624. (end (progn (goto-char (- (org-babel-result-end) 1)) (point)))
  625. ov)
  626. (if (memq t (mapcar (lambda (overlay)
  627. (eq (overlay-get overlay 'invisible)
  628. 'org-babel-hide-result))
  629. (overlays-at start)))
  630. (if (or (not force) (eq force 'off))
  631. (mapc (lambda (ov)
  632. (when (member ov org-babel-hide-result-overlays)
  633. (setq org-babel-hide-result-overlays
  634. (delq ov org-babel-hide-result-overlays)))
  635. (when (eq (overlay-get ov 'invisible)
  636. 'org-babel-hide-result)
  637. (delete-overlay ov)))
  638. (overlays-at start)))
  639. (setq ov (make-overlay start end))
  640. (overlay-put ov 'invisible 'org-babel-hide-result)
  641. ;; make the block accessible to isearch
  642. (overlay-put
  643. ov 'isearch-open-invisible
  644. (lambda (ov)
  645. (when (member ov org-babel-hide-result-overlays)
  646. (setq org-babel-hide-result-overlays
  647. (delq ov org-babel-hide-result-overlays)))
  648. (when (eq (overlay-get ov 'invisible)
  649. 'org-babel-hide-result)
  650. (delete-overlay ov))))
  651. (push ov org-babel-hide-result-overlays)))
  652. (error "Not looking at a result line"))))
  653. ;; org-tab-after-check-for-cycling-hook
  654. (add-hook 'org-tab-first-hook 'org-babel-hide-result-toggle-maybe)
  655. ;; Remove overlays when changing major mode
  656. (add-hook 'org-mode-hook
  657. (lambda () (org-add-hook 'change-major-mode-hook
  658. 'org-babel-show-result-all 'append 'local)))
  659. (defmacro org-babel-map-src-blocks (file &rest body)
  660. "Evaluate BODY forms on each source-block in FILE.
  661. If FILE is nil evaluate BODY forms on source blocks in current
  662. buffer. During evaluation of BODY the following local variables
  663. are set relative to the currently matched code block.
  664. full-block ------- string holding the entirety of the code block
  665. beg-block -------- point at the beginning of the code block
  666. end-block -------- point at the end of the matched code block
  667. lang ------------- string holding the language of the code block
  668. beg-lang --------- point at the beginning of the lang
  669. end-lang --------- point at the end of the lang
  670. switches --------- string holding the switches
  671. beg-switches ----- point at the beginning of the switches
  672. end-switches ----- point at the end of the switches
  673. header-args ------ string holding the header-args
  674. beg-header-args -- point at the beginning of the header-args
  675. end-header-args -- point at the end of the header-args
  676. body ------------- string holding the body of the code block
  677. beg-body --------- point at the beginning of the body
  678. end-body --------- point at the end of the body"
  679. (declare (indent 1))
  680. `(let ((visited-p (or (null ,file)
  681. (get-file-buffer (expand-file-name ,file))))
  682. (point (point)) to-be-removed)
  683. (save-window-excursion
  684. (when ,file (find-file ,file))
  685. (setq to-be-removed (current-buffer))
  686. (goto-char (point-min))
  687. (while (re-search-forward org-babel-src-block-regexp nil t)
  688. (goto-char (match-beginning 0))
  689. (let ((full-block (match-string 0))
  690. (beg-block (match-beginning 0))
  691. (end-block (match-beginning 0))
  692. (lang (match-string 2))
  693. (beg-lang (match-beginning 2))
  694. (end-lang (match-end 2))
  695. (switches (match-string 3))
  696. (beg-switches (match-beginning 3))
  697. (end-switches (match-end 3))
  698. (header-args (match-string 4))
  699. (beg-header-args (match-beginning 4))
  700. (end-header-args (match-end 4))
  701. (body (match-string 5))
  702. (beg-body (match-beginning 5))
  703. (end-body (match-end 5)))
  704. (save-match-data ,@body))
  705. (goto-char (match-end 0))))
  706. (unless visited-p
  707. (kill-buffer to-be-removed))
  708. (goto-char point)))
  709. (defvar org-file-properties)
  710. (defun org-babel-params-from-properties (&optional lang)
  711. "Retrieve parameters specified as properties.
  712. Return an association list of any source block params which
  713. may be specified in the properties of the current outline entry."
  714. (save-match-data
  715. (let (val sym)
  716. (delq nil
  717. (mapcar
  718. (lambda (header-arg)
  719. (and (setq val
  720. (or (condition-case nil
  721. (org-entry-get (point) header-arg t)
  722. (error nil))
  723. (cdr (assoc header-arg org-file-properties))))
  724. (cons (intern (concat ":" header-arg)) val)))
  725. (mapcar
  726. 'symbol-name
  727. (append
  728. org-babel-header-arg-names
  729. (progn
  730. (setq sym (intern (concat "org-babel-header-arg-names:" lang)))
  731. (and (boundp sym) (eval sym))))))))))
  732. (defun org-babel-params-from-buffer ()
  733. "Retrieve per-buffer parameters.
  734. Return an association list of any source block params which
  735. may be specified at the top of the current buffer."
  736. (or org-babel-current-buffer-properties
  737. (setq org-babel-current-buffer-properties
  738. (save-match-data
  739. (save-excursion
  740. (save-restriction
  741. (widen)
  742. (goto-char (point-min))
  743. (when (re-search-forward
  744. (org-make-options-regexp (list "BABEL")) nil t)
  745. (org-babel-parse-header-arguments
  746. (org-match-string-no-properties 2)))))))))
  747. (defvar org-src-preserve-indentation)
  748. (defun org-babel-parse-src-block-match ()
  749. "Parse the results from a match of the `org-babel-src-block-regexp'."
  750. (let* ((block-indentation (length (match-string 1)))
  751. (lang (org-babel-clean-text-properties (match-string 2)))
  752. (lang-headers (intern (concat "org-babel-default-header-args:" lang)))
  753. (switches (match-string 3))
  754. (body (org-babel-clean-text-properties (match-string 5)))
  755. (preserve-indentation (or org-src-preserve-indentation
  756. (string-match "-i\\>" switches))))
  757. (list lang
  758. ;; get block body less properties, protective commas, and indentation
  759. (with-temp-buffer
  760. (save-match-data
  761. (insert (org-babel-strip-protective-commas body))
  762. (unless preserve-indentation (org-do-remove-indentation))
  763. (buffer-string)))
  764. (org-babel-merge-params
  765. org-babel-default-header-args
  766. (org-babel-params-from-buffer)
  767. (org-babel-params-from-properties lang)
  768. (if (boundp lang-headers) (eval lang-headers) nil)
  769. (org-babel-parse-header-arguments
  770. (org-babel-clean-text-properties (or (match-string 4) ""))))
  771. switches
  772. block-indentation)))
  773. (defun org-babel-parse-inline-src-block-match ()
  774. "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
  775. (let* ((lang (org-babel-clean-text-properties (match-string 2)))
  776. (lang-headers (intern (concat "org-babel-default-header-args:" lang))))
  777. (list lang
  778. (org-babel-strip-protective-commas
  779. (org-babel-clean-text-properties (match-string 5)))
  780. (org-babel-merge-params
  781. org-babel-default-inline-header-args
  782. (org-babel-params-from-buffer)
  783. (org-babel-params-from-properties lang)
  784. (if (boundp lang-headers) (eval lang-headers) nil)
  785. (org-babel-parse-header-arguments
  786. (org-babel-clean-text-properties (or (match-string 4) "")))))))
  787. (defun org-babel-parse-header-arguments (arg-string)
  788. "Parse a string of header arguments returning an alist."
  789. (if (> (length arg-string) 0)
  790. (delq nil
  791. (mapcar
  792. (lambda (arg)
  793. (if (string-match
  794. "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
  795. arg)
  796. (cons (intern (concat ":" (match-string 1 arg)))
  797. (let ((raw (org-babel-chomp (match-string 2 arg))))
  798. (if (org-babel-number-p raw)
  799. raw (org-babel-read raw))))
  800. (cons (intern (concat ":" arg)) nil)))
  801. (split-string (concat " " arg-string) "[ \f\t\n\r\v]+:" t)))))
  802. (defun org-babel-process-params (params)
  803. "Parse params and resolve references.
  804. Return a list (session vars result-params result-type colnames rownames)."
  805. (let* ((session (cdr (assoc :session params)))
  806. (vars-and-names (org-babel-disassemble-tables
  807. (org-babel-ref-variables params)
  808. (cdr (assoc :hlines params))
  809. (cdr (assoc :colnames params))
  810. (cdr (assoc :rownames params))))
  811. (vars (car vars-and-names))
  812. (colnames (cadr vars-and-names))
  813. (rownames (caddr vars-and-names))
  814. (result-params (split-string (or (cdr (assoc :results params)) "")))
  815. (result-type (cond ((member "output" result-params) 'output)
  816. ((member "value" result-params) 'value)
  817. (t 'value))))
  818. (list session vars result-params result-type colnames rownames)))
  819. ;; row and column names
  820. (defun org-babel-del-hlines (table)
  821. "Remove all 'hlines from TABLE."
  822. (remove 'hline table))
  823. (defun org-babel-get-colnames (table)
  824. "Return the column names of TABLE.
  825. Return a cons cell, the `car' of which contains the TABLE less
  826. colnames, and the `cdr' of which contains a list of the column
  827. names."
  828. (if (equal 'hline (nth 1 table))
  829. (cons (cddr table) (car table))
  830. (cons (cdr table) (car table))))
  831. (defun org-babel-get-rownames (table)
  832. "Return the row names of TABLE.
  833. Return a cons cell, the `car' of which contains the TABLE less
  834. colnames, and the `cdr' of which contains a list of the column
  835. names. Note: this function removes any hlines in TABLE."
  836. (flet ((trans (table) (apply #'mapcar* #'list table)))
  837. (let* ((width (apply 'max (mapcar (lambda (el) (if (listp el) (length el) 0)) table)))
  838. (table (trans (mapcar (lambda (row)
  839. (if (not (equal row 'hline))
  840. row
  841. (setq row '())
  842. (dotimes (n width) (setq row (cons 'hline row)))
  843. row))
  844. table))))
  845. (cons (mapcar (lambda (row) (if (equal (car row) 'hline) 'hline row))
  846. (trans (cdr table)))
  847. (remove 'hline (car table))))))
  848. (defun org-babel-put-colnames (table colnames)
  849. "Add COLNAMES to TABLE if they exist."
  850. (if colnames (apply 'list colnames 'hline table) table))
  851. (defun org-babel-put-rownames (table rownames)
  852. "Add ROWNAMES to TABLE if they exist."
  853. (if rownames
  854. (mapcar (lambda (row)
  855. (if (listp row)
  856. (cons (or (pop rownames) "") row)
  857. row)) table)
  858. table))
  859. (defun org-babel-pick-name (names selector)
  860. "Select one out of an alist of row or column names.
  861. SELECTOR can be either a list of names in which case those names
  862. will be returned directly, or an index into the list NAMES in
  863. which case the indexed names will be return."
  864. (if (listp selector)
  865. selector
  866. (when names
  867. (if (and selector (symbolp selector) (not (equal t selector)))
  868. (cdr (assoc selector names))
  869. (if (integerp selector)
  870. (nth (- selector 1) names)
  871. (cdr (car (last names))))))))
  872. (defun org-babel-disassemble-tables (vars hlines colnames rownames)
  873. "Parse tables for further processing.
  874. Process the variables in VARS according to the HLINES,
  875. ROWNAMES and COLNAMES header arguments. Return a list consisting
  876. of the vars, cnames and rnames."
  877. (let (cnames rnames)
  878. (list
  879. (mapcar
  880. (lambda (var)
  881. (when (listp (cdr var))
  882. (when (and (not (equal colnames "no"))
  883. (or colnames (and (equal (nth 1 (cdr var)) 'hline)
  884. (not (member 'hline (cddr (cdr var)))))))
  885. (let ((both (org-babel-get-colnames (cdr var))))
  886. (setq cnames (cons (cons (car var) (cdr both))
  887. cnames))
  888. (setq var (cons (car var) (car both)))))
  889. (when (and rownames (not (equal rownames "no")))
  890. (let ((both (org-babel-get-rownames (cdr var))))
  891. (setq rnames (cons (cons (car var) (cdr both))
  892. rnames))
  893. (setq var (cons (car var) (car both)))))
  894. (when (and hlines (not (equal hlines "yes")))
  895. (setq var (cons (car var) (org-babel-del-hlines (cdr var))))))
  896. var)
  897. vars)
  898. cnames rnames)))
  899. (defun org-babel-reassemble-table (table colnames rownames)
  900. "Add column and row names to a table.
  901. Given a TABLE and set of COLNAMES and ROWNAMES add the names
  902. to the table for reinsertion to org-mode."
  903. (if (listp table)
  904. ((lambda (table)
  905. (if (and colnames (listp (car table)) (= (length (car table))
  906. (length colnames)))
  907. (org-babel-put-colnames table colnames) table))
  908. (if (and rownames (= (length table) (length rownames)))
  909. (org-babel-put-rownames table rownames) table))
  910. table))
  911. (defun org-babel-where-is-src-block-head ()
  912. "Find where the current source block begins.
  913. Return the point at the beginning of the current source
  914. block. Specifically at the beginning of the #+BEGIN_SRC line.
  915. If the point is not on a source block then return nil."
  916. (let ((initial (point)) top bottom)
  917. (or
  918. (save-excursion ;; on a source name line
  919. (beginning-of-line 1)
  920. (and (looking-at org-babel-src-name-regexp) (forward-line 1)
  921. (looking-at org-babel-src-block-regexp)
  922. (point)))
  923. (save-excursion ;; on a #+begin_src line
  924. (beginning-of-line 1)
  925. (and (looking-at org-babel-src-block-regexp)
  926. (point)))
  927. (save-excursion ;; inside a src block
  928. (and
  929. (re-search-backward "^[ \t]*#\\+begin_src" nil t) (setq top (point))
  930. (re-search-forward "^[ \t]*#\\+end_src" nil t) (setq bottom (point))
  931. (< top initial) (< initial bottom)
  932. (progn (goto-char top) (beginning-of-line 1)
  933. (looking-at org-babel-src-block-regexp))
  934. (point))))))
  935. ;;;###autoload
  936. (defun org-babel-goto-named-src-block (name)
  937. "Go to a named source-code block."
  938. (interactive
  939. (let ((completion-ignore-case t))
  940. (list (org-icompleting-read "source-block name: "
  941. (org-babel-src-block-names) nil t))))
  942. (let ((point (org-babel-find-named-block name)))
  943. (if point
  944. ;; taken from `org-open-at-point'
  945. (progn (goto-char point) (org-show-context))
  946. (message "source-code block '%s' not found in this buffer" name))))
  947. (defun org-babel-find-named-block (name)
  948. "Find a named source-code block.
  949. Return the location of the source block identified by source
  950. NAME, or nil if no such block exists. Set match data according to
  951. org-babel-named-src-block-regexp."
  952. (save-excursion
  953. (let ((case-fold-search t)
  954. (regexp (org-babel-named-src-block-regexp-for-name name)) msg)
  955. (goto-char (point-min))
  956. (when (or (re-search-forward regexp nil t)
  957. (re-search-backward regexp nil t))
  958. (match-beginning 0)))))
  959. (defun org-babel-src-block-names (&optional file)
  960. "Returns the names of source blocks in FILE or the current buffer."
  961. (save-excursion
  962. (when file (find-file file)) (goto-char (point-min))
  963. (let (names)
  964. (while (re-search-forward org-babel-src-name-w-name-regexp nil t)
  965. (setq names (cons (org-babel-clean-text-properties (match-string 2))
  966. names)))
  967. names)))
  968. ;;;###autoload
  969. (defun org-babel-goto-named-result (name)
  970. "Go to a named result."
  971. (interactive
  972. (let ((completion-ignore-case t))
  973. (list (org-icompleting-read "source-block name: "
  974. (org-babel-result-names) nil t))))
  975. (let ((point (org-babel-find-named-result name)))
  976. (if point
  977. ;; taken from `org-open-at-point'
  978. (progn (goto-char point) (org-show-context))
  979. (message "result '%s' not found in this buffer" name))))
  980. (defun org-babel-find-named-result (name)
  981. "Find a named result.
  982. Return the location of the result named NAME in the current
  983. buffer or nil if no such result exists."
  984. (save-excursion
  985. (goto-char (point-min))
  986. (when (re-search-forward
  987. (concat org-babel-result-regexp
  988. "[ \t]" (regexp-quote name) "[ \t\n\f\v\r]") nil t)
  989. (beginning-of-line 0) (point))))
  990. (defun org-babel-result-names (&optional file)
  991. "Returns the names of results in FILE or the current buffer."
  992. (save-excursion
  993. (when file (find-file file)) (goto-char (point-min))
  994. (let (names)
  995. (while (re-search-forward org-babel-result-w-name-regexp nil t)
  996. (setq names (cons (org-babel-clean-text-properties (match-string 4))
  997. names)))
  998. names)))
  999. ;;;###autoload
  1000. (defun org-babel-next-src-block (&optional arg)
  1001. "Jump to the next source block.
  1002. With optional prefix argument ARG, jump forward ARG many source blocks."
  1003. (interactive "P")
  1004. (when (looking-at org-babel-src-block-regexp) (forward-char 1))
  1005. (condition-case nil
  1006. (re-search-forward org-babel-src-block-regexp nil nil (or arg 1))
  1007. (error (error "No further code blocks")))
  1008. (goto-char (match-beginning 0)) (org-show-context))
  1009. ;;;###autoload
  1010. (defun org-babel-previous-src-block (&optional arg)
  1011. "Jump to the previous source block.
  1012. With optional prefix argument ARG, jump backward ARG many source blocks."
  1013. (interactive "P")
  1014. (condition-case nil
  1015. (re-search-backward org-babel-src-block-regexp nil nil (or arg 1))
  1016. (error (error "No previous code blocks")))
  1017. (goto-char (match-beginning 0)) (org-show-context))
  1018. (defvar org-babel-lob-one-liner-regexp)
  1019. (defun org-babel-where-is-src-block-result (&optional insert info hash indent)
  1020. "Find where the current source block results begin.
  1021. Return the point at the beginning of the result of the current
  1022. source block. Specifically at the beginning of the results line.
  1023. If no result exists for this block then create a results line
  1024. following the source block."
  1025. (save-excursion
  1026. (let* ((on-lob-line (progn (beginning-of-line 1)
  1027. (looking-at org-babel-lob-one-liner-regexp)))
  1028. (name (if on-lob-line
  1029. (nth 0 (org-babel-lob-get-info))
  1030. (nth 4 (or info (org-babel-get-src-block-info)))))
  1031. (head (unless on-lob-line (org-babel-where-is-src-block-head)))
  1032. found beg end)
  1033. (when head (goto-char head))
  1034. (setq
  1035. found ;; was there a result (before we potentially insert one)
  1036. (or
  1037. (and
  1038. ;; named results:
  1039. ;; - return t if it is found, else return nil
  1040. ;; - if it does not need to be rebuilt, then don't set end
  1041. ;; - if it does need to be rebuilt then do set end
  1042. name (setq beg (org-babel-find-named-result name))
  1043. (prog1 beg
  1044. (when (and hash (not (string= hash (match-string 3))))
  1045. (goto-char beg) (setq end beg) ;; beginning of result
  1046. (forward-line 1)
  1047. (delete-region end (org-babel-result-end)) nil)))
  1048. (and
  1049. ;; unnamed results:
  1050. ;; - return t if it is found, else return nil
  1051. ;; - if it is found, and the hash doesn't match, delete and set end
  1052. (or on-lob-line (re-search-forward "^[ \t]*#\\+end_src" nil t))
  1053. (progn (end-of-line 1)
  1054. (if (eobp) (insert "\n") (forward-char 1))
  1055. (setq end (point))
  1056. (or (and (not name)
  1057. (progn ;; unnamed results line already exists
  1058. (re-search-forward "[^ \f\t\n\r\v]" nil t)
  1059. (beginning-of-line 1)
  1060. (looking-at
  1061. (concat org-babel-result-regexp "\n")))
  1062. (prog1 (point)
  1063. ;; must remove and rebuild if hash!=old-hash
  1064. (if (and hash (not (string= hash (match-string 3))))
  1065. (prog1 nil
  1066. (forward-line 1)
  1067. (delete-region
  1068. end (org-babel-result-end)))
  1069. (setq end nil)))))))))
  1070. (if (and insert end)
  1071. (progn
  1072. (goto-char end)
  1073. (unless beg
  1074. (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
  1075. (insert (concat
  1076. (if indent
  1077. (mapconcat
  1078. (lambda (el) " ")
  1079. (number-sequence 1 indent) "")
  1080. "")
  1081. "#+results"
  1082. (when hash (concat "["hash"]"))
  1083. ":"
  1084. (when name (concat " " name)) "\n"))
  1085. (unless beg (insert "\n") (backward-char))
  1086. (beginning-of-line 0)
  1087. (if hash (org-babel-hide-hash))
  1088. (point))
  1089. found))))
  1090. (defvar org-block-regexp)
  1091. (defun org-babel-read-result ()
  1092. "Read the result at `point' into emacs-lisp."
  1093. (let ((case-fold-search t) result-string)
  1094. (cond
  1095. ((org-at-table-p) (org-babel-read-table))
  1096. ((looking-at org-bracket-link-regexp) (org-babel-read-link))
  1097. ((looking-at org-block-regexp) (org-babel-trim (match-string 4)))
  1098. ((looking-at "^[ \t]*: ")
  1099. (setq result-string
  1100. (org-babel-trim
  1101. (mapconcat (lambda (line)
  1102. (if (and (> (length line) 1)
  1103. (string-match "^[ \t]*: \\(.+\\)" line))
  1104. (match-string 1 line)
  1105. line))
  1106. (split-string
  1107. (buffer-substring
  1108. (point) (org-babel-result-end)) "[\r\n]+")
  1109. "\n")))
  1110. (or (org-babel-number-p result-string) result-string))
  1111. ((looking-at org-babel-result-regexp)
  1112. (save-excursion (forward-line 1) (org-babel-read-result))))))
  1113. (defun org-babel-read-table ()
  1114. "Read the table at `point' into emacs-lisp."
  1115. (mapcar (lambda (row)
  1116. (if (and (symbolp row) (equal row 'hline)) row
  1117. (mapcar #'org-babel-read row)))
  1118. (org-table-to-lisp)))
  1119. (defvar org-link-types-re)
  1120. (defun org-babel-read-link ()
  1121. "Read the link at `point' into emacs-lisp.
  1122. If the path of the link is a file path it is expanded using
  1123. `expand-file-name'."
  1124. (let* ((case-fold-search t)
  1125. (raw (and (looking-at org-bracket-link-regexp)
  1126. (org-babel-clean-text-properties (match-string 1))))
  1127. (type (and (string-match org-link-types-re raw)
  1128. (match-string 1 raw))))
  1129. (cond
  1130. ((not type) (expand-file-name raw))
  1131. ((string= type "file")
  1132. (and (string-match "file\\(.*\\):\\(.+\\)" raw)
  1133. (expand-file-name (match-string 2 raw))))
  1134. (t raw))))
  1135. (defun org-babel-insert-result
  1136. (result &optional result-params info hash indent lang)
  1137. "Insert RESULT into the current buffer.
  1138. By default RESULT is inserted after the end of the
  1139. current source block. With optional argument RESULT-PARAMS
  1140. controls insertion of results in the org-mode file.
  1141. RESULT-PARAMS can take the following values...
  1142. replace - (default option) insert results after the source block
  1143. replacing any previously inserted results
  1144. silent -- no results are inserted
  1145. file ---- the results are interpreted as a file path, and are
  1146. inserted into the buffer using the Org-mode file syntax
  1147. raw ----- results are added directly to the org-mode file. This
  1148. is a good option if you code block will output org-mode
  1149. formatted text.
  1150. org ----- similar in effect to raw, only the results are wrapped
  1151. in an org code block. Similar to the raw option, on
  1152. export the results will be interpreted as org-formatted
  1153. text, however by wrapping the results in an org code
  1154. block they can be replaced upon re-execution of the
  1155. code block.
  1156. html ---- results are added inside of a #+BEGIN_HTML block. This
  1157. is a good option if you code block will output html
  1158. formatted text.
  1159. latex --- results are added inside of a #+BEGIN_LATEX block.
  1160. This is a good option if you code block will output
  1161. latex formatted text.
  1162. code ---- the results are extracted in the syntax of the source
  1163. code of the language being evaluated and are added
  1164. inside of a #+BEGIN_SRC block with the source-code
  1165. language set appropriately. Note this relies on the
  1166. optional LANG argument."
  1167. (if (stringp result)
  1168. (progn
  1169. (setq result (org-babel-clean-text-properties result))
  1170. (when (member "file" result-params)
  1171. (setq result (org-babel-result-to-file result))))
  1172. (unless (listp result) (setq result (format "%S" result))))
  1173. (if (and result-params (member "silent" result-params))
  1174. (progn
  1175. (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
  1176. result)
  1177. (when (and (stringp result) ;; ensure results end in a newline
  1178. (not (or (string-equal (substring result -1) "\n")
  1179. (string-equal (substring result -1) "\r"))))
  1180. (setq result (concat result "\n")))
  1181. (save-excursion
  1182. (let ((existing-result (org-babel-where-is-src-block-result
  1183. t info hash indent))
  1184. (results-switches
  1185. (cdr (assoc :results_switches (nth 2 info))))
  1186. beg end)
  1187. (if (not existing-result)
  1188. (setq beg (point))
  1189. (goto-char existing-result)
  1190. (save-excursion
  1191. (re-search-forward "#" nil t)
  1192. (setq indent (- (current-column) 1)))
  1193. (forward-line 1)
  1194. (setq beg (point))
  1195. (cond
  1196. ((member "replace" result-params)
  1197. (delete-region (point) (org-babel-result-end)))
  1198. ((member "append" result-params)
  1199. (goto-char (org-babel-result-end)) (setq beg (point)))
  1200. ((member "prepend" result-params) ;; already there
  1201. )))
  1202. (setq results-switches
  1203. (if results-switches (concat " " results-switches) ""))
  1204. (cond
  1205. ;; assume the result is a table if it's not a string
  1206. ((not (stringp result))
  1207. (insert (concat (orgtbl-to-orgtbl
  1208. (if (or (eq 'hline (car result))
  1209. (and (listp (car result))
  1210. (listp (cdr (car result)))))
  1211. result (list result))
  1212. '(:fmt (lambda (cell) (format "%s" cell)))) "\n"))
  1213. (goto-char beg) (when (org-at-table-p) (org-table-align)))
  1214. ((member "file" result-params)
  1215. (insert result))
  1216. ((member "html" result-params)
  1217. (insert (format "#+BEGIN_HTML%s\n%s#+END_HTML\n"
  1218. results-switches result)))
  1219. ((member "latex" result-params)
  1220. (insert (format "#+BEGIN_LaTeX%s\n%s#+END_LaTeX\n"
  1221. results-switches result)))
  1222. ((member "code" result-params)
  1223. (insert (format "#+BEGIN_SRC %s%s\n%s#+END_SRC\n"
  1224. (or lang "none") results-switches result)))
  1225. ((member "org" result-params)
  1226. (insert (format "#+BEGIN_SRC org\n%s#+END_SRC\n" result)))
  1227. ((member "raw" result-params)
  1228. (save-excursion (insert result)) (if (org-at-table-p) (org-cycle)))
  1229. (t
  1230. (org-babel-examplize-region
  1231. (point) (progn (insert result) (point)) results-switches)))
  1232. ;; possibly indent the results to match the #+results line
  1233. (setq end (if (listp result) (org-table-end) (point)))
  1234. (when (and indent (> indent 0)
  1235. ;; in this case `table-align' does the work for us
  1236. (not (and (listp result)
  1237. (member "append" result-params))))
  1238. (indent-rigidly beg end indent))))
  1239. (if (= (length result) 0)
  1240. (if (member "value" result-params)
  1241. (message "No result returned by source block")
  1242. (message "Source block produced no output"))
  1243. (message "finished"))))
  1244. (defun org-babel-remove-result (&optional info)
  1245. "Remove the result of the current source block."
  1246. (interactive)
  1247. (let ((location (org-babel-where-is-src-block-result nil info)) start)
  1248. (when location
  1249. (save-excursion
  1250. (goto-char location) (setq start (point)) (forward-line 1)
  1251. (delete-region start (org-babel-result-end))))))
  1252. (defun org-babel-result-end ()
  1253. "Return the point at the end of the current set of results"
  1254. (save-excursion
  1255. (if (org-at-table-p)
  1256. (progn (goto-char (org-table-end)) (point))
  1257. (let ((case-fold-search t))
  1258. (cond
  1259. ((looking-at "[ \t]*#\\+begin_latex")
  1260. (re-search-forward "[ \t]*#\\+end_latex" nil t)
  1261. (forward-line 1))
  1262. ((looking-at "[ \t]*#\\+begin_html")
  1263. (re-search-forward "[ \t]*#\\+end_html" nil t)
  1264. (forward-line 1))
  1265. ((looking-at "[ \t]*#\\+begin_example")
  1266. (re-search-forward "[ \t]*#\\+end_example" nil t)
  1267. (forward-line 1))
  1268. ((looking-at "[ \t]*#\\+begin_src")
  1269. (re-search-forward "[ \t]*#\\+end_src" nil t)
  1270. (forward-line 1))
  1271. (t (progn (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
  1272. (forward-line 1))))))
  1273. (point))))
  1274. (defun org-babel-result-to-file (result)
  1275. "Convert RESULT into an `org-mode' link.
  1276. If the `default-directory' is different from the containing
  1277. file's directory then expand relative links."
  1278. (format
  1279. "[[file:%s]]"
  1280. (if (and default-directory
  1281. buffer-file-name
  1282. (not (string= (expand-file-name default-directory)
  1283. (expand-file-name
  1284. (file-name-directory buffer-file-name)))))
  1285. (expand-file-name result default-directory)
  1286. result)))
  1287. (defun org-babel-examplize-region (beg end &optional results-switches)
  1288. "Comment out region using the ': ' org example quote."
  1289. (interactive "*r")
  1290. (let ((size (count-lines beg end)))
  1291. (save-excursion
  1292. (cond ((= size 0)
  1293. (error (concat "This should be impossible:"
  1294. "a newline was appended to result if missing")))
  1295. ((< size org-babel-min-lines-for-block-output)
  1296. (goto-char beg)
  1297. (dotimes (n size)
  1298. (beginning-of-line 1) (insert ": ") (forward-line 1)))
  1299. (t
  1300. (goto-char beg)
  1301. (insert (if results-switches
  1302. (format "#+begin_example%s\n" results-switches)
  1303. "#+begin_example\n"))
  1304. (forward-char (- end beg))
  1305. (insert "#+end_example\n"))))))
  1306. (defun org-babel-merge-params (&rest plists)
  1307. "Combine all parameter association lists in PLISTS.
  1308. Later elements of PLISTS override the values of previous element.
  1309. This takes into account some special considerations for certain
  1310. parameters when merging lists."
  1311. (let ((results-exclusive-groups
  1312. '(("file" "vector" "table" "scalar" "raw" "org"
  1313. "html" "latex" "code" "pp")
  1314. ("replace" "silent" "append" "prepend")
  1315. ("output" "value")))
  1316. (exports-exclusive-groups
  1317. '(("code" "results" "both" "none")))
  1318. params results exports tangle noweb cache vars var ref shebang comments)
  1319. (flet ((e-merge (exclusive-groups &rest result-params)
  1320. ;; maintain exclusivity of mutually exclusive parameters
  1321. (let (output)
  1322. (mapc (lambda (new-params)
  1323. (mapc (lambda (new-param)
  1324. (mapc (lambda (exclusive-group)
  1325. (when (member new-param exclusive-group)
  1326. (mapcar (lambda (excluded-param)
  1327. (setq output
  1328. (delete
  1329. excluded-param
  1330. output)))
  1331. exclusive-group)))
  1332. exclusive-groups)
  1333. (setq output (org-uniquify
  1334. (cons new-param output))))
  1335. new-params))
  1336. result-params)
  1337. output)))
  1338. (mapc (lambda (plist)
  1339. (mapc (lambda (pair)
  1340. (case (car pair)
  1341. (:var
  1342. ;; we want only one specification per variable
  1343. (when (string-match
  1344. (concat "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
  1345. "[ \t]*\\([^\f\n\r\v]+\\)$") (cdr pair))
  1346. ;; TODO: When is this not true?
  1347. (setq var (intern (match-string 1 (cdr pair)))
  1348. ref (match-string 2 (cdr pair))
  1349. vars (cons (cons var ref)
  1350. (assq-delete-all var vars)))))
  1351. (:results
  1352. (setq results
  1353. (e-merge results-exclusive-groups
  1354. results (split-string (cdr pair)))))
  1355. (:file
  1356. (when (cdr pair)
  1357. (setq results (e-merge results-exclusive-groups
  1358. results '("file")))
  1359. (unless (or (member "both" exports)
  1360. (member "none" exports)
  1361. (member "code" exports))
  1362. (setq exports (e-merge exports-exclusive-groups
  1363. exports '("results"))))
  1364. (setq params
  1365. (cons pair
  1366. (assq-delete-all (car pair) params)))))
  1367. (:exports
  1368. (setq exports
  1369. (e-merge exports-exclusive-groups
  1370. exports (split-string (cdr pair)))))
  1371. (:tangle ;; take the latest -- always overwrite
  1372. (setq tangle (or (list (cdr pair)) tangle)))
  1373. (:noweb
  1374. (setq noweb
  1375. (e-merge '(("yes" "no")) noweb
  1376. (split-string (or (cdr pair) "")))))
  1377. (:cache
  1378. (setq cache
  1379. (e-merge '(("yes" "no")) cache
  1380. (split-string (or (cdr pair) "")))))
  1381. (:shebang ;; take the latest -- always overwrite
  1382. (setq shebang (or (list (cdr pair)) shebang)))
  1383. (:comments
  1384. (setq comments
  1385. (e-merge '(("yes" "no")) comments
  1386. (split-string (or (cdr pair) "")))))
  1387. (t ;; replace: this covers e.g. :session
  1388. (setq params
  1389. (cons pair
  1390. (assq-delete-all (car pair) params))))))
  1391. plist))
  1392. plists))
  1393. (setq vars (mapcar (lambda (pair) (format "%s=%s" (car pair) (cdr pair))) vars))
  1394. (while vars (setq params (cons (cons :var (pop vars)) params)))
  1395. (cons (cons :comments (mapconcat 'identity comments " "))
  1396. (cons (cons :shebang (mapconcat 'identity shebang " "))
  1397. (cons (cons :cache (mapconcat 'identity cache " "))
  1398. (cons (cons :noweb (mapconcat 'identity noweb " "))
  1399. (cons (cons :tangle (mapconcat 'identity tangle " "))
  1400. (cons (cons :exports
  1401. (mapconcat 'identity exports " "))
  1402. (cons
  1403. (cons :results
  1404. (mapconcat 'identity results " "))
  1405. params)))))))))
  1406. (defun org-babel-expand-noweb-references (&optional info parent-buffer)
  1407. "Expand Noweb references in the body of the current source code block.
  1408. For example the following reference would be replaced with the
  1409. body of the source-code block named 'example-block'.
  1410. <<example-block>>
  1411. Note that any text preceding the <<foo>> construct on a line will
  1412. be interposed between the lines of the replacement text. So for
  1413. example if <<foo>> is placed behind a comment, then the entire
  1414. replacement text will also be commented.
  1415. This function must be called from inside of the buffer containing
  1416. the source-code block which holds BODY.
  1417. In addition the following syntax can be used to insert the
  1418. results of evaluating the source-code block named 'example-block'.
  1419. <<example-block()>>
  1420. Any optional arguments can be passed to example-block by placing
  1421. the arguments inside the parenthesis following the convention
  1422. defined by `org-babel-lob'. For example
  1423. <<example-block(a=9)>>
  1424. would set the value of argument \"a\" equal to \"9\". Note that
  1425. these arguments are not evaluated in the current source-code
  1426. block but are passed literally to the \"example-block\"."
  1427. (let* ((parent-buffer (or parent-buffer (current-buffer)))
  1428. (info (or info (org-babel-get-src-block-info)))
  1429. (lang (nth 0 info))
  1430. (body (nth 1 info))
  1431. (new-body "") index source-name evaluate prefix)
  1432. (flet ((nb-add (text)
  1433. (setq new-body (concat new-body text))))
  1434. (with-temp-buffer
  1435. (insert body) (goto-char (point-min))
  1436. (setq index (point))
  1437. (while (and (re-search-forward "<<\\(.+?\\)>>" nil t))
  1438. (save-match-data (setf source-name (match-string 1)))
  1439. (save-match-data (setq evaluate (string-match "\(.*\)" source-name)))
  1440. (save-match-data
  1441. (setq prefix
  1442. (buffer-substring (match-beginning 0)
  1443. (save-excursion
  1444. (beginning-of-line 1) (point)))))
  1445. ;; add interval to new-body (removing noweb reference)
  1446. (goto-char (match-beginning 0))
  1447. (nb-add (buffer-substring index (point)))
  1448. (goto-char (match-end 0))
  1449. (setq index (point))
  1450. (nb-add (with-current-buffer parent-buffer
  1451. (mapconcat ;; interpose PREFIX between every line
  1452. #'identity
  1453. (split-string
  1454. (if evaluate
  1455. (let ((raw (org-babel-ref-resolve-reference
  1456. source-name nil)))
  1457. (if (stringp raw) raw (format "%S" raw)))
  1458. (save-restriction
  1459. (widen)
  1460. (let ((point (org-babel-find-named-block
  1461. source-name)))
  1462. (if point
  1463. (save-excursion
  1464. (goto-char point)
  1465. (org-babel-trim
  1466. (org-babel-expand-noweb-references
  1467. (org-babel-get-src-block-info))))
  1468. ;; optionally raise an error if named
  1469. ;; source-block doesn't exist
  1470. (if (member lang org-babel-noweb-error-langs)
  1471. (error "%s"
  1472. (concat
  1473. "<<" source-name ">> "
  1474. "could not be resolved (see "
  1475. "`org-babel-noweb-error-langs')"))
  1476. "")))))
  1477. "[\n\r]") (concat "\n" prefix)))))
  1478. (nb-add (buffer-substring index (point-max)))))
  1479. new-body))
  1480. (defun org-babel-clean-text-properties (text)
  1481. "Strip all properties from text return."
  1482. (when text
  1483. (set-text-properties 0 (length text) nil text) text))
  1484. (defun org-babel-strip-protective-commas (body)
  1485. "Strip protective commas from bodies of source blocks."
  1486. (replace-regexp-in-string "^,#" "#" body))
  1487. (defun org-babel-read (cell)
  1488. "Convert the string value of CELL to a number if appropriate.
  1489. Otherwise if cell looks like lisp (meaning it starts with a
  1490. \"(\" or a \"'\") then read it as lisp, otherwise return it
  1491. unmodified as a string.
  1492. This is taken almost directly from `org-read-prop'."
  1493. (if (and (stringp cell) (not (equal cell "")))
  1494. (or (org-babel-number-p cell)
  1495. (if (or (equal "(" (substring cell 0 1))
  1496. (equal "'" (substring cell 0 1))
  1497. (equal "`" (substring cell 0 1)))
  1498. (eval (read cell))
  1499. (progn (set-text-properties 0 (length cell) nil cell) cell)))
  1500. cell))
  1501. (defun org-babel-number-p (string)
  1502. "Return t if STRING represents a number."
  1503. (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string)
  1504. (= (length (substring string (match-beginning 0)
  1505. (match-end 0)))
  1506. (length string)))
  1507. (string-to-number string)))
  1508. (defun org-babel-import-elisp-from-file (file-name &optional separator)
  1509. "Read the results located at FILE-NAME into an elisp table.
  1510. If the table is trivial, then return it as a scalar."
  1511. (let (result)
  1512. (save-window-excursion
  1513. (with-temp-buffer
  1514. (condition-case nil
  1515. (progn
  1516. (org-table-import file-name separator)
  1517. (delete-file file-name)
  1518. (setq result (mapcar (lambda (row)
  1519. (mapcar #'org-babel-string-read row))
  1520. (org-table-to-lisp))))
  1521. (error nil)))
  1522. (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
  1523. (if (consp (car result))
  1524. (if (null (cdr (car result)))
  1525. (caar result)
  1526. result)
  1527. (car result))
  1528. result))))
  1529. (defun org-babel-string-read (cell)
  1530. "Strip nested \"s from around strings."
  1531. (org-babel-read (or (and (stringp cell)
  1532. (string-match "\\\"\\(.+\\)\\\"" cell)
  1533. (match-string 1 cell))
  1534. cell)))
  1535. (defun org-babel-reverse-string (string)
  1536. "Return the reverse of STRING."
  1537. (apply 'string (reverse (string-to-list string))))
  1538. (defun org-babel-chomp (string &optional regexp)
  1539. "Strip trailing spaces and carriage returns from STRING.
  1540. Default regexp used is \"[ \f\t\n\r\v]\" but can be
  1541. overwritten by specifying a regexp as a second argument."
  1542. (let ((regexp (or regexp "[ \f\t\n\r\v]")))
  1543. (while (and (> (length string) 0)
  1544. (string-match regexp (substring string -1)))
  1545. (setq string (substring string 0 -1)))
  1546. string))
  1547. (defun org-babel-trim (string &optional regexp)
  1548. "Strip leading and trailing spaces and carriage returns from STRING.
  1549. Like `org-babel-chomp' only it runs on both the front and back
  1550. of the string."
  1551. (org-babel-chomp (org-babel-reverse-string
  1552. (org-babel-chomp (org-babel-reverse-string string) regexp))
  1553. regexp))
  1554. (defvar org-babel-org-babel-call-process-region-original nil)
  1555. (defun org-babel-tramp-handle-call-process-region
  1556. (start end program &optional delete buffer display &rest args)
  1557. "Use tramp to handle call-process-region.
  1558. Fixes a bug in `tramp-handle-call-process-region'."
  1559. (if (and (featurep 'tramp) (file-remote-p default-directory))
  1560. (let ((tmpfile (tramp-compat-make-temp-file "")))
  1561. (write-region start end tmpfile)
  1562. (when delete (delete-region start end))
  1563. (unwind-protect
  1564. ;; (apply 'call-process program tmpfile buffer display args)
  1565. ;; bug in tramp
  1566. (apply 'process-file program tmpfile buffer display args)
  1567. (delete-file tmpfile)))
  1568. ;; org-babel-call-process-region-original is the original emacs definition. It
  1569. ;; is in scope from the let binding in org-babel-execute-src-block
  1570. (apply org-babel-call-process-region-original
  1571. start end program delete buffer display args)))
  1572. (defun org-babel-maybe-remote-file (file)
  1573. "Conditionally parse information on a remote connnection.
  1574. If FILE specifies a remove file, then parse the information on
  1575. the remote connection."
  1576. (if (file-remote-p default-directory)
  1577. (let* ((vec (tramp-dissect-file-name default-directory))
  1578. (user (tramp-file-name-user vec))
  1579. (host (tramp-file-name-host vec)))
  1580. (concat "/" user (when user "@") host ":" file))
  1581. file))
  1582. (defun org-babel-tramp-localname (file)
  1583. "Return the local name component of FILE."
  1584. (if (file-remote-p file)
  1585. (let (localname)
  1586. (with-parsed-tramp-file-name file nil
  1587. localname))
  1588. file))
  1589. (defvar org-babel-temporary-directory
  1590. (or (and (boundp 'org-babel-temporary-directory)
  1591. org-babel-temporary-directory)
  1592. (make-temp-file "babel-" t))
  1593. "Directory to hold temporary files created to execute code blocks.
  1594. Used by `org-babel-temp-file'. This directory will be removed on
  1595. Emacs shutdown.")
  1596. (defun org-babel-temp-file (prefix &optional suffix)
  1597. "Create a temporary file in the `org-babel-temporary-directory'.
  1598. Passes PREFIX and SUFFIX directly to `make-temp-file' with the
  1599. value of `temporary-file-directory' temporarily set to the value
  1600. of `org-babel-temporary-directory'."
  1601. (if (file-remote-p default-directory)
  1602. (make-temp-file
  1603. (concat (file-remote-p default-directory)
  1604. (expand-file-name
  1605. prefix temporary-file-directory)
  1606. nil suffix))
  1607. (let ((temporary-file-directory (expand-file-name
  1608. org-babel-temporary-directory
  1609. temporary-file-directory)))
  1610. (make-temp-file prefix nil suffix))))
  1611. (defun org-babel-remove-temporary-directory ()
  1612. "Remove `org-babel-temporary-directory' on Emacs shutdown."
  1613. (when (boundp 'org-babel-temporary-directory)
  1614. ;; taken from `delete-directory' in files.el
  1615. (mapc (lambda (file)
  1616. ;; This test is equivalent to
  1617. ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
  1618. ;; but more efficient
  1619. (if (eq t (car (file-attributes file)))
  1620. (delete-directory file)
  1621. (delete-file file)))
  1622. ;; We do not want to delete "." and "..".
  1623. (directory-files org-babel-temporary-directory 'full
  1624. "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
  1625. (delete-directory org-babel-temporary-directory)))
  1626. (add-hook 'kill-emacs-hook 'org-babel-remove-temporary-directory)
  1627. (provide 'ob)
  1628. ;; arch-tag: 01a7ebee-06c5-4ee4-a709-e660d28c0af1
  1629. ;;; ob.el ends here