ob.el 72 KB

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