ob.el 72 KB

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