ob.el 73 KB

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