org.el: remove useless comment.
[org-mode/org-mode-NeilSmithlineMods.git] / lisp / ob.el
blobdbbcaff7393d1e4cca5fe955191ecd7b0b0c857b
1 ;;; ob.el --- working with code blocks in org-mode
3 ;; Copyright (C) 2009, 2010 Free Software Foundation, Inc.
5 ;; Author: Eric Schulte, Dan Davison
6 ;; Keywords: literate programming, reproducible research
7 ;; Homepage: http://orgmode.org
8 ;; Version: 7.5
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;; Commentary:
27 ;; See the online documentation for more information
29 ;; http://orgmode.org/worg/org-contrib/babel/
31 ;;; Code:
32 (eval-when-compile
33 (require 'cl))
34 (require 'ob-eval)
35 (require 'org-macs)
37 (defvar org-babel-call-process-region-original)
38 (defvar org-src-lang-modes)
39 (defvar org-babel-library-of-babel)
40 (declare-function show-all "outline" ())
41 (declare-function tramp-compat-make-temp-file "tramp-compat"
42 (filename &optional dir-flag))
43 (declare-function tramp-dissect-file-name "tramp" (name &optional nodefault))
44 (declare-function tramp-file-name-user "tramp" (vec))
45 (declare-function tramp-file-name-host "tramp" (vec))
46 (declare-function with-parsed-tramp-file-name "tramp" (filename var &rest body))
47 (declare-function org-icompleting-read "org" (&rest args))
48 (declare-function org-edit-src-code "org-src"
49 (&optional context code edit-buffer-name quietp))
50 (declare-function org-edit-src-exit "org-src" (&optional context))
51 (declare-function org-open-at-point "org" (&optional in-emacs reference-buffer))
52 (declare-function org-save-outline-visibility "org" (use-markers &rest body))
53 (declare-function org-outline-overlay-data "org" (&optional use-markers))
54 (declare-function org-set-outline-overlay-data "org" (data))
55 (declare-function org-narrow-to-subtree "org" ())
56 (declare-function org-entry-get "org"
57 (pom property &optional inherit literal-nil))
58 (declare-function org-make-options-regexp "org" (kwds &optional extra))
59 (declare-function org-do-remove-indentation "org" (&optional n))
60 (declare-function org-show-context "org" (&optional key))
61 (declare-function org-at-table-p "org" (&optional table-type))
62 (declare-function org-cycle "org" (&optional arg))
63 (declare-function org-uniquify "org" (list))
64 (declare-function org-current-level "org" ())
65 (declare-function org-table-import "org-table" (file arg))
66 (declare-function org-add-hook "org-compat"
67 (hook function &optional append local))
68 (declare-function org-table-align "org-table" ())
69 (declare-function org-table-end "org-table" (&optional table-type))
70 (declare-function orgtbl-to-generic "org-table" (table params))
71 (declare-function orgtbl-to-orgtbl "org-table" (table params))
72 (declare-function org-babel-tangle-comment-links "ob-tangle" (&optional info))
73 (declare-function org-babel-lob-get-info "ob-lob" nil)
74 (declare-function org-babel-ref-split-args "ob-ref" (arg-string))
75 (declare-function org-babel-ref-parse "ob-ref" (assignment))
76 (declare-function org-babel-ref-resolve "ob-ref" (ref))
77 (declare-function org-babel-lob-execute-maybe "ob-lob" ())
78 (declare-function org-number-sequence "org-compat" (from &optional to inc))
79 (declare-function org-at-item-p "org-list" ())
80 (declare-function org-list-parse-list "org-list" (&optional delete))
81 (declare-function org-list-to-generic "org-list" (LIST PARAMS))
82 (declare-function org-list-struct "org-list" ())
83 (declare-function org-list-prevs-alist "org-list" (struct))
84 (declare-function org-list-get-list-end "org-list" (item struct prevs))
86 (defgroup org-babel nil
87 "Code block evaluation and management in `org-mode' documents."
88 :tag "Babel"
89 :group 'org)
91 (defcustom org-confirm-babel-evaluate t
92 "Confirm before evaluation.
93 Require confirmation before interactively evaluating code
94 blocks in Org-mode buffers. The default value of this variable
95 is t, meaning confirmation is required for any code block
96 evaluation. This variable can be set to nil to inhibit any
97 future confirmation requests. This variable can also be set to a
98 function which takes two arguments the language of the code block
99 and the body of the code block. Such a function should then
100 return a non-nil value if the user should be prompted for
101 execution or nil if no prompt is required.
103 Warning: Disabling confirmation may result in accidental
104 evaluation of potentially harmful code. It may be advisable
105 remove code block execution from C-c C-c as further protection
106 against accidental code block evaluation. The
107 `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
108 remove code block execution from the C-c C-c keybinding."
109 :group 'org-babel
110 :type '(choice boolean function))
111 ;; don't allow this variable to be changed through file settings
112 (put 'org-confirm-babel-evaluate 'safe-local-variable (lambda (x) (eq x t)))
114 (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
115 "Remove code block evaluation from the C-c C-c key binding."
116 :group 'org-babel
117 :type 'boolean)
119 (defvar org-babel-src-name-regexp
120 "^[ \t]*#\\+\\(srcname\\|source\\|function\\):[ \t]*"
121 "Regular expression used to match a source name line.")
123 (defvar org-babel-multi-line-header-regexp
124 "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
125 "Regular expression used to match multi-line header arguments.")
127 (defvar org-babel-src-name-w-name-regexp
128 (concat org-babel-src-name-regexp
129 "\\("
130 org-babel-multi-line-header-regexp
131 "\\)*"
132 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)")
133 "Regular expression matching source name lines with a name.")
135 (defvar org-babel-src-block-regexp
136 (concat
137 ;; (1) indentation (2) lang
138 "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
139 ;; (3) switches
140 "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
141 ;; (4) header arguments
142 "\\([^\n]*\\)\n"
143 ;; (5) body
144 "\\([^\000]*?\n*\\)[ \t]*#\\+end_src")
145 "Regexp used to identify code blocks.")
147 (defvar org-babel-inline-src-block-regexp
148 (concat
149 ;; (1) replacement target (2) lang
150 "[^-[:alnum:]]\\(src_\\([^ \f\t\n\r\v]+\\)"
151 ;; (3,4) (unused, headers)
152 "\\(\\|\\[\\(.*?\\)\\]\\)"
153 ;; (5) body
154 "{\\([^\f\n\r\v]+?\\)}\\)")
155 "Regexp used to identify inline src-blocks.")
157 (defun org-babel-get-header (params key &optional others)
158 "Select only header argument of type KEY from a list.
159 Optional argument OTHERS indicates that only the header that do
160 not match KEY should be returned."
161 (delq nil
162 (mapcar
163 (lambda (p) (when (funcall (if others #'not #'identity) (eq (car p) key)) p))
164 params)))
166 (defun org-babel-get-src-block-info (&optional light)
167 "Get information on the current source block.
169 Optional argument LIGHT does not resolve remote variable
170 references; a process which could likely result in the execution
171 of other code blocks.
173 Returns a list
174 (language body header-arguments-alist switches name indent)."
175 (let ((case-fold-search t) head info name indent)
176 ;; full code block
177 (if (setq head (org-babel-where-is-src-block-head))
178 (save-excursion
179 (goto-char head)
180 (setq info (org-babel-parse-src-block-match))
181 (setq indent (car (last info)))
182 (setq info (butlast info))
183 (while (and (forward-line -1)
184 (looking-at org-babel-multi-line-header-regexp))
185 (setf (nth 2 info)
186 (org-babel-merge-params
187 (nth 2 info)
188 (org-babel-parse-header-arguments (match-string 1)))))
189 (when (looking-at org-babel-src-name-w-name-regexp)
190 (setq name (org-babel-clean-text-properties (match-string 4)))
191 (when (match-string 6)
192 (setf (nth 2 info) ;; merge functional-syntax vars and header-args
193 (org-babel-merge-params
194 (mapcar (lambda (ref) (cons :var ref))
195 (org-babel-ref-split-args (match-string 6)))
196 (nth 2 info))))))
197 ;; inline source block
198 (when (save-excursion (re-search-backward "[ \f\t\n\r\v]" nil t)
199 (looking-at org-babel-inline-src-block-regexp))
200 (setq info (org-babel-parse-inline-src-block-match))))
201 ;; resolve variable references and add summary parameters
202 (when (and info (not light))
203 (setf (nth 2 info) (org-babel-process-params (nth 2 info))))
204 (when info (append info (list name indent)))))
206 (defun org-babel-confirm-evaluate (info)
207 "Confirm evaluation of the code block INFO.
208 This behavior can be suppressed by setting the value of
209 `org-confirm-babel-evaluate' to nil, in which case all future
210 interactive code block evaluations will proceed without any
211 confirmation from the user.
213 Note disabling confirmation may result in accidental evaluation
214 of potentially harmful code."
215 (let* ((eval (or (cdr (assoc :eval (nth 2 info)))
216 (when (assoc :noeval (nth 2 info)) "no")))
217 (query (cond ((equal eval "query") t)
218 ((functionp org-confirm-babel-evaluate)
219 (funcall org-confirm-babel-evaluate
220 (nth 0 info) (nth 1 info)))
221 (t org-confirm-babel-evaluate))))
222 (if (or (equal eval "never") (equal eval "no")
223 (and query
224 (not (yes-or-no-p
225 (format "Evaluate this%scode block%son your system? "
226 (if info (format " %s " (nth 0 info)) " ")
227 (if (nth 4 info)
228 (format " (%s) " (nth 4 info)) " "))))))
229 (prog1 nil (message "Evaluation %s"
230 (if (or (equal eval "never") (equal eval "no"))
231 "Disabled" "Aborted")))
232 t)))
234 ;;;###autoload
235 (defun org-babel-execute-safely-maybe ()
236 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
237 (org-babel-execute-maybe)))
239 (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-execute-safely-maybe)
241 ;;;###autoload
242 (defun org-babel-execute-maybe ()
243 (interactive)
244 (or (org-babel-execute-src-block-maybe)
245 (org-babel-lob-execute-maybe)))
247 (defun org-babel-execute-src-block-maybe ()
248 "Conditionally execute a source block.
249 Detect if this is context for a Babel src-block and if so
250 then run `org-babel-execute-src-block'."
251 (interactive)
252 (let ((info (org-babel-get-src-block-info)))
253 (if info
254 (progn (org-babel-eval-wipe-error-buffer)
255 (org-babel-execute-src-block current-prefix-arg info) t) nil)))
257 ;;;###autoload
258 (defun org-babel-expand-src-block-maybe ()
259 "Conditionally expand a source block.
260 Detect if this is context for a org-babel src-block and if so
261 then run `org-babel-expand-src-block'."
262 (interactive)
263 (let ((info (org-babel-get-src-block-info)))
264 (if info
265 (progn (org-babel-expand-src-block current-prefix-arg info) t)
266 nil)))
268 ;;;###autoload
269 (defun org-babel-load-in-session-maybe ()
270 "Conditionally load a source block in a session.
271 Detect if this is context for a org-babel src-block and if so
272 then run `org-babel-load-in-session'."
273 (interactive)
274 (let ((info (org-babel-get-src-block-info)))
275 (if info
276 (progn (org-babel-load-in-session current-prefix-arg info) t)
277 nil)))
279 (add-hook 'org-metaup-hook 'org-babel-load-in-session-maybe)
281 ;;;###autoload
282 (defun org-babel-pop-to-session-maybe ()
283 "Conditionally pop to a session.
284 Detect if this is context for a org-babel src-block and if so
285 then run `org-babel-pop-to-session'."
286 (interactive)
287 (let ((info (org-babel-get-src-block-info)))
288 (if info (progn (org-babel-pop-to-session current-prefix-arg info) t) nil)))
290 (add-hook 'org-metadown-hook 'org-babel-pop-to-session-maybe)
292 (defconst org-babel-header-arg-names
293 '(cache cmdline colnames dir exports file noweb results
294 session tangle var eval noeval comments no-expand)
295 "Common header arguments used by org-babel.
296 Note that individual languages may define their own language
297 specific header arguments as well.")
299 (defvar org-babel-default-header-args
300 '((:session . "none") (:results . "replace") (:exports . "code")
301 (:cache . "no") (:noweb . "no") (:hlines . "no") (:tangle . "no"))
302 "Default arguments to use when evaluating a source block.")
304 (defvar org-babel-default-inline-header-args
305 '((:session . "none") (:results . "replace") (:exports . "results"))
306 "Default arguments to use when evaluating an inline source block.")
308 (defvar org-babel-current-buffer-properties nil
309 "Local cache for buffer properties.")
310 (make-variable-buffer-local 'org-babel-current-buffer-properties)
312 (defvar org-babel-result-regexp
313 "^[ \t]*#\\+res\\(ults\\|name\\)\\(\\[\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*"
314 "Regular expression used to match result lines.
315 If the results are associated with a hash key then the hash will
316 be saved in the second match data.")
318 (defvar org-babel-result-w-name-regexp
319 (concat org-babel-result-regexp
320 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
322 (defvar org-babel-min-lines-for-block-output 10
323 "The minimum number of lines for block output.
324 If number of lines of output is equal to or exceeds this
325 value, the output is placed in a #+begin_example...#+end_example
326 block. Otherwise the output is marked as literal by inserting
327 colons at the starts of the lines. This variable only takes
328 effect if the :results output option is in effect.")
330 (defvar org-babel-noweb-error-langs nil
331 "Languages for which Babel will raise literate programming errors.
332 List of languages for which errors should be raised when the
333 source code block satisfying a noweb reference in this language
334 can not be resolved.")
336 (defvar org-babel-hash-show 4
337 "Number of initial characters to show of a hidden results hash.")
339 (defvar org-babel-after-execute-hook nil
340 "Hook for functions to be called after `org-babel-execute-src-block'")
341 (defun org-babel-named-src-block-regexp-for-name (name)
342 "This generates a regexp used to match a src block named NAME."
343 (concat org-babel-src-name-regexp (regexp-quote name) "[ \t\n]*"
344 (substring org-babel-src-block-regexp 1)))
346 ;;; functions
347 (defvar call-process-region)
348 ;;;###autoload
350 (defun org-babel-execute-src-block (&optional arg info params)
351 "Execute the current source code block.
352 Insert the results of execution into the buffer. Source code
353 execution and the collection and formatting of results can be
354 controlled through a variety of header arguments.
356 With prefix argument ARG, force re-execution even if a an
357 existing result cached in the buffer would otherwise have been
358 returned.
360 Optionally supply a value for INFO in the form returned by
361 `org-babel-get-src-block-info'.
363 Optionally supply a value for PARAMS which will be merged with
364 the header arguments specified at the front of the source code
365 block."
366 (interactive)
367 (let ((info (or info (org-babel-get-src-block-info))))
368 (when (org-babel-confirm-evaluate info)
369 (let* ((lang (nth 0 info))
370 (params (if params
371 (org-babel-process-params
372 (org-babel-merge-params (nth 2 info) params))
373 (nth 2 info)))
374 (cache? (and (not arg) (cdr (assoc :cache params))
375 (string= "yes" (cdr (assoc :cache params)))))
376 (result-params (cdr (assoc :result-params params)))
377 (new-hash (when cache? (org-babel-sha1-hash info)))
378 (old-hash (when cache? (org-babel-result-hash info)))
379 (body (setf (nth 1 info)
380 (let ((noweb (cdr (assoc :noweb params))))
381 (if (and noweb
382 (or (string= "yes" noweb)
383 (string= "tangle" noweb)))
384 (org-babel-expand-noweb-references info)
385 (nth 1 info)))))
386 (dir (cdr (assoc :dir params)))
387 (default-directory
388 (or (and dir (file-name-as-directory dir)) default-directory))
389 (org-babel-call-process-region-original
390 (if (boundp 'org-babel-call-process-region-original)
391 org-babel-call-process-region-original
392 (symbol-function 'call-process-region)))
393 (indent (car (last info)))
394 result cmd)
395 (unwind-protect
396 (flet ((call-process-region (&rest args)
397 (apply 'org-babel-tramp-handle-call-process-region args)))
398 (flet ((lang-check (f)
399 (let ((f (intern (concat "org-babel-execute:" f))))
400 (when (fboundp f) f))))
401 (setq cmd
402 (or (lang-check lang)
403 (lang-check (symbol-name
404 (cdr (assoc lang org-src-lang-modes))))
405 (error "No org-babel-execute function for %s!" lang))))
406 (if (and (not arg) new-hash (equal new-hash old-hash))
407 (save-excursion ;; return cached result
408 (goto-char (org-babel-where-is-src-block-result nil info))
409 (end-of-line 1) (forward-char 1)
410 (setq result (org-babel-read-result))
411 (message (replace-regexp-in-string
412 "%" "%%" (format "%S" result))) result)
413 (message "executing %s code block%s..."
414 (capitalize lang)
415 (if (nth 4 info) (format " (%s)" (nth 4 info)) ""))
416 (setq result
417 ((lambda (result)
418 (if (and (eq (cdr (assoc :result-type params)) 'value)
419 (or (member "vector" result-params)
420 (member "table" result-params))
421 (not (listp result)))
422 (list (list result)) result))
423 (funcall cmd body params)))
424 ;; if non-empty result and :file then write to :file
425 (when (cdr (assoc :file params))
426 (when result
427 (with-temp-file (cdr (assoc :file params))
428 (insert
429 (org-babel-format-result
430 result (cdr (assoc :sep (nth 2 info)))))))
431 (setq result (cdr (assoc :file params))))
432 (org-babel-insert-result
433 result result-params info new-hash indent lang)
434 (run-hooks 'org-babel-after-execute-hook)
435 result))
436 (setq call-process-region 'org-babel-call-process-region-original))))))
438 (defun org-babel-expand-body:generic (body params &optional var-lines)
439 "Expand BODY with PARAMS.
440 Expand a block of code with org-babel according to it's header
441 arguments. This generic implementation of body expansion is
442 called for languages which have not defined their own specific
443 org-babel-expand-body:lang function."
444 (mapconcat #'identity (append var-lines (list body)) "\n"))
446 ;;;###autoload
447 (defun org-babel-expand-src-block (&optional arg info params)
448 "Expand the current source code block.
449 Expand according to the source code block's header
450 arguments and pop open the results in a preview buffer."
451 (interactive)
452 (let* ((info (or info (org-babel-get-src-block-info)))
453 (lang (nth 0 info))
454 (params (setf (nth 2 info)
455 (sort (org-babel-merge-params (nth 2 info) params)
456 (lambda (el1 el2) (string< (symbol-name (car el1))
457 (symbol-name (car el2)))))))
458 (body (setf (nth 1 info)
459 (if (and (cdr (assoc :noweb params))
460 (string= "yes" (cdr (assoc :noweb params))))
461 (org-babel-expand-noweb-references info) (nth 1 info))))
462 (expand-cmd (intern (concat "org-babel-expand-body:" lang)))
463 (assignments-cmd (intern (concat "org-babel-variable-assignments:" lang)))
464 (expanded
465 (if (fboundp expand-cmd) (funcall expand-cmd body params)
466 (org-babel-expand-body:generic
467 body params (and (fboundp assignments-cmd) (funcall assignments-cmd params))))))
468 (org-edit-src-code
469 nil expanded (concat "*Org-Babel Preview " (buffer-name) "[ " lang " ]*"))))
471 ;;;###autoload
472 (defun org-babel-load-in-session (&optional arg info)
473 "Load the body of the current source-code block.
474 Evaluate the header arguments for the source block before
475 entering the session. After loading the body this pops open the
476 session."
477 (interactive)
478 (let* ((info (or info (org-babel-get-src-block-info)))
479 (lang (nth 0 info))
480 (params (nth 2 info))
481 (body (setf (nth 1 info)
482 (if (and (cdr (assoc :noweb params))
483 (string= "yes" (cdr (assoc :noweb params))))
484 (org-babel-expand-noweb-references info)
485 (nth 1 info))))
486 (session (cdr (assoc :session params)))
487 (dir (cdr (assoc :dir params)))
488 (default-directory
489 (or (and dir (file-name-as-directory dir)) default-directory))
490 (cmd (intern (concat "org-babel-load-session:" lang))))
491 (unless (fboundp cmd)
492 (error "No org-babel-load-session function for %s!" lang))
493 (pop-to-buffer (funcall cmd session body params))
494 (end-of-line 1)))
496 ;;;###autoload
497 (defun org-babel-initiate-session (&optional arg info)
498 "Initiate session for current code block.
499 If called with a prefix argument then resolve any variable
500 references in the header arguments and assign these variables in
501 the session. Copy the body of the code block to the kill ring."
502 (interactive "P")
503 (let* ((info (or info (org-babel-get-src-block-info (not arg))))
504 (lang (nth 0 info))
505 (body (nth 1 info))
506 (params (nth 2 info))
507 (session (cdr (assoc :session params)))
508 (dir (cdr (assoc :dir params)))
509 (default-directory
510 (or (and dir (file-name-as-directory dir)) default-directory))
511 (init-cmd (intern (format "org-babel-%s-initiate-session" lang)))
512 (prep-cmd (intern (concat "org-babel-prep-session:" lang))))
513 (if (and (stringp session) (string= session "none"))
514 (error "This block is not using a session!"))
515 (unless (fboundp init-cmd)
516 (error "No org-babel-initiate-session function for %s!" lang))
517 (with-temp-buffer (insert (org-babel-trim body))
518 (copy-region-as-kill (point-min) (point-max)))
519 (when arg
520 (unless (fboundp prep-cmd)
521 (error "No org-babel-prep-session function for %s!" lang))
522 (funcall prep-cmd session params))
523 (funcall init-cmd session params)))
525 ;;;###autoload
526 (defun org-babel-switch-to-session (&optional arg info)
527 "Switch to the session of the current code block.
528 Uses `org-babel-initiate-session' to start the session. If called
529 with a prefix argument then this is passed on to
530 `org-babel-initiate-session'."
531 (interactive "P")
532 (pop-to-buffer (org-babel-initiate-session arg info))
533 (end-of-line 1))
535 (defalias 'org-babel-pop-to-session 'org-babel-switch-to-session)
537 ;;;###autoload
538 (defun org-babel-switch-to-session-with-code (&optional arg info)
539 "Switch to code buffer and display session."
540 (interactive "P")
541 (flet ((swap-windows
543 (let ((other-window-buffer (window-buffer (next-window))))
544 (set-window-buffer (next-window) (current-buffer))
545 (set-window-buffer (selected-window) other-window-buffer))
546 (other-window 1)))
547 (let ((info (org-babel-get-src-block-info))
548 (org-src-window-setup 'reorganize-frame))
549 (save-excursion
550 (org-babel-switch-to-session arg info))
551 (org-edit-src-code))
552 (swap-windows)))
554 (defmacro org-babel-do-in-edit-buffer (&rest body)
555 "Evaluate BODY in edit buffer if there is a code block at point.
556 Return t if a code block was found at point, nil otherwise."
557 `(let ((org-src-window-setup 'switch-invisibly))
558 (when (and (org-babel-where-is-src-block-head)
559 (org-edit-src-code nil nil nil))
560 (unwind-protect (progn ,@body)
561 (if (org-bound-and-true-p org-edit-src-from-org-mode)
562 (org-edit-src-exit)))
563 t)))
565 (defun org-babel-do-key-sequence-in-edit-buffer (key)
566 "Read key sequence and execute the command in edit buffer.
567 Enter a key sequence to be executed in the language major-mode
568 edit buffer. For example, TAB will alter the contents of the
569 Org-mode code block according to the effect of TAB in the
570 language major-mode buffer. For languages that support
571 interactive sessions, this can be used to send code from the Org
572 buffer to the session for evaluation using the native major-mode
573 evaluation mechanisms."
574 (interactive "kEnter key-sequence to execute in edit buffer: ")
575 (org-babel-do-in-edit-buffer
576 (call-interactively
577 (key-binding (or key (read-key-sequence nil))))))
579 (defvar org-bracket-link-regexp)
580 ;;;###autoload
581 (defun org-babel-open-src-block-result (&optional re-run)
582 "If `point' is on a src block then open the results of the
583 source code block, otherwise return nil. With optional prefix
584 argument RE-RUN the source-code block is evaluated even if
585 results already exist."
586 (interactive "P")
587 (let ((info (org-babel-get-src-block-info)))
588 (when info
589 (save-excursion
590 ;; go to the results, if there aren't any then run the block
591 (goto-char (or (and (not re-run) (org-babel-where-is-src-block-result))
592 (progn (org-babel-execute-src-block)
593 (org-babel-where-is-src-block-result))))
594 (end-of-line 1)
595 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
596 ;; open the results
597 (if (looking-at org-bracket-link-regexp)
598 ;; file results
599 (org-open-at-point)
600 (let ((r (org-babel-format-result
601 (org-babel-read-result) (cdr (assoc :sep (nth 2 info))))))
602 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
603 (delete-region (point-min) (point-max))
604 (insert r)))
605 t))))
607 ;;;###autoload
608 (defmacro org-babel-map-src-blocks (file &rest body)
609 "Evaluate BODY forms on each source-block in FILE.
610 If FILE is nil evaluate BODY forms on source blocks in current
611 buffer. During evaluation of BODY the following local variables
612 are set relative to the currently matched code block.
614 full-block ------- string holding the entirety of the code block
615 beg-block -------- point at the beginning of the code block
616 end-block -------- point at the end of the matched code block
617 lang ------------- string holding the language of the code block
618 beg-lang --------- point at the beginning of the lang
619 end-lang --------- point at the end of the lang
620 switches --------- string holding the switches
621 beg-switches ----- point at the beginning of the switches
622 end-switches ----- point at the end of the switches
623 header-args ------ string holding the header-args
624 beg-header-args -- point at the beginning of the header-args
625 end-header-args -- point at the end of the header-args
626 body ------------- string holding the body of the code block
627 beg-body --------- point at the beginning of the body
628 end-body --------- point at the end of the body"
629 (declare (indent 1))
630 (let ((tempvar (make-symbol "file")))
631 `(let* ((,tempvar ,file)
632 (visited-p (or (null ,tempvar)
633 (get-file-buffer (expand-file-name ,tempvar))))
634 (point (point)) to-be-removed)
635 (save-window-excursion
636 (when ,tempvar (find-file ,tempvar))
637 (setq to-be-removed (current-buffer))
638 (goto-char (point-min))
639 (while (re-search-forward org-babel-src-block-regexp nil t)
640 (goto-char (match-beginning 0))
641 (let ((full-block (match-string 0))
642 (beg-block (match-beginning 0))
643 (end-block (match-end 0))
644 (lang (match-string 2))
645 (beg-lang (match-beginning 2))
646 (end-lang (match-end 2))
647 (switches (match-string 3))
648 (beg-switches (match-beginning 3))
649 (end-switches (match-end 3))
650 (header-args (match-string 4))
651 (beg-header-args (match-beginning 4))
652 (end-header-args (match-end 4))
653 (body (match-string 5))
654 (beg-body (match-beginning 5))
655 (end-body (match-end 5)))
656 ,@body
657 (goto-char end-block))))
658 (unless visited-p (kill-buffer to-be-removed))
659 (goto-char point))))
661 ;;;###autoload
662 (defmacro org-babel-map-inline-src-blocks (file &rest body)
663 "Evaluate BODY forms on each inline source-block in FILE.
664 If FILE is nil evaluate BODY forms on source blocks in current
665 buffer."
666 (declare (indent 1))
667 (let ((tempvar (make-symbol "file")))
668 `(let* ((,tempvar ,file)
669 (visited-p (or (null ,tempvar)
670 (get-file-buffer (expand-file-name ,tempvar))))
671 (point (point)) to-be-removed)
672 (save-window-excursion
673 (when ,tempvar (find-file ,tempvar))
674 (setq to-be-removed (current-buffer))
675 (goto-char (point-min))
676 (while (re-search-forward org-babel-inline-src-block-regexp nil t)
677 (goto-char (match-beginning 1))
678 (save-match-data ,@body)
679 (goto-char (match-end 0))))
680 (unless visited-p (kill-buffer to-be-removed))
681 (goto-char point))))
683 ;;;###autoload
684 (defun org-babel-execute-buffer (&optional arg)
685 "Execute source code blocks in a buffer.
686 Call `org-babel-execute-src-block' on every source block in
687 the current buffer."
688 (interactive "P")
689 (org-babel-eval-wipe-error-buffer)
690 (org-save-outline-visibility t
691 (org-babel-map-src-blocks nil
692 (org-babel-execute-src-block arg))
693 (org-babel-map-inline-src-blocks nil
694 (org-babel-execute-src-block arg))))
696 ;;;###autoload
697 (defun org-babel-execute-subtree (&optional arg)
698 "Execute source code blocks in a subtree.
699 Call `org-babel-execute-src-block' on every source block in
700 the current subtree."
701 (interactive "P")
702 (save-restriction
703 (save-excursion
704 (org-narrow-to-subtree)
705 (org-babel-execute-buffer arg)
706 (widen))))
708 ;;;###autoload
709 (defun org-babel-sha1-hash (&optional info)
710 "Generate an sha1 hash based on the value of info."
711 (interactive)
712 (let ((print-level nil)
713 (info (or info (org-babel-get-src-block-info))))
714 (setf (nth 2 info)
715 (sort (copy-sequence (nth 2 info))
716 (lambda (a b) (string< (car a) (car b)))))
717 ((lambda (hash) (when (interactive-p) (message hash)) hash)
718 (sha1 (format "%s-%s"
719 (mapconcat
720 #'identity
721 (delq nil
722 (mapcar
723 (lambda (arg)
724 (let ((v (cdr arg)))
725 (when (and v (not (and (sequencep v)
726 (not (consp v))
727 (= (length v) 0))))
728 ((lambda (el) (format "%S" el))
729 (cond
730 ((and (listp v) ; lists are sorted
731 (member (car arg) '(:result-params)))
732 (sort v #'string<))
733 ((and (stringp v) ; strings are sorted
734 (member (car arg) '(:results :exports)))
735 (mapconcat #'identity (sort (split-string v)
736 #'string<) " "))
737 (t v)))))) ; atomic are left untouched
738 (nth 2 info))) ":")
739 (nth 1 info))))))
741 (defun org-babel-result-hash (&optional info)
742 "Return the in-buffer hash associated with INFO."
743 (org-babel-where-is-src-block-result nil info)
744 (org-babel-clean-text-properties (match-string 3)))
746 (defun org-babel-hide-hash ()
747 "Hide the hash in the current results line.
748 Only the initial `org-babel-hash-show' characters of the hash
749 will remain visible."
750 (add-to-invisibility-spec '(org-babel-hide-hash . t))
751 (save-excursion
752 (when (and (re-search-forward org-babel-result-regexp nil t)
753 (match-string 3))
754 (let* ((start (match-beginning 3))
755 (hide-start (+ org-babel-hash-show start))
756 (end (match-end 3))
757 (hash (match-string 3))
758 ov1 ov2)
759 (setq ov1 (make-overlay start hide-start))
760 (setq ov2 (make-overlay hide-start end))
761 (overlay-put ov2 'invisible 'org-babel-hide-hash)
762 (overlay-put ov1 'babel-hash hash)))))
764 (defun org-babel-hide-all-hashes ()
765 "Hide the hash in the current buffer.
766 Only the initial `org-babel-hash-show' characters of each hash
767 will remain visible. This function should be called as part of
768 the `org-mode-hook'."
769 (save-excursion
770 (while (re-search-forward org-babel-result-regexp nil t)
771 (goto-char (match-beginning 0))
772 (org-babel-hide-hash)
773 (goto-char (match-end 0)))))
774 (add-hook 'org-mode-hook 'org-babel-hide-all-hashes)
776 (defun org-babel-hash-at-point (&optional point)
777 "Return the value of the hash at POINT.
778 The hash is also added as the last element of the kill ring.
779 This can be called with C-c C-c."
780 (interactive)
781 (let ((hash (car (delq nil (mapcar
782 (lambda (ol) (overlay-get ol 'babel-hash))
783 (overlays-at (or point (point))))))))
784 (when hash (kill-new hash) (message hash))))
785 (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-hash-at-point)
787 (defun org-babel-result-hide-spec ()
788 "Hide portions of results lines.
789 Add `org-babel-hide-result' as an invisibility spec for hiding
790 portions of results lines."
791 (add-to-invisibility-spec '(org-babel-hide-result . t)))
792 (add-hook 'org-mode-hook 'org-babel-result-hide-spec)
794 (defvar org-babel-hide-result-overlays nil
795 "Overlays hiding results.")
797 (defun org-babel-result-hide-all ()
798 "Fold all results in the current buffer."
799 (interactive)
800 (org-babel-show-result-all)
801 (save-excursion
802 (while (re-search-forward org-babel-result-regexp nil t)
803 (save-excursion (goto-char (match-beginning 0))
804 (org-babel-hide-result-toggle-maybe)))))
806 (defun org-babel-show-result-all ()
807 "Unfold all results in the current buffer."
808 (mapc 'delete-overlay org-babel-hide-result-overlays)
809 (setq org-babel-hide-result-overlays nil))
811 ;;;###autoload
812 (defun org-babel-hide-result-toggle-maybe ()
813 "Toggle visibility of result at point."
814 (interactive)
815 (let ((case-fold-search t))
816 (if (save-excursion
817 (beginning-of-line 1)
818 (looking-at org-babel-result-regexp))
819 (progn (org-babel-hide-result-toggle)
820 t) ;; to signal that we took action
821 nil))) ;; to signal that we did not
823 (defun org-babel-hide-result-toggle (&optional force)
824 "Toggle the visibility of the current result."
825 (interactive)
826 (save-excursion
827 (beginning-of-line)
828 (if (re-search-forward org-babel-result-regexp nil t)
829 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
830 (end (progn (goto-char (- (org-babel-result-end) 1)) (point)))
832 (if (memq t (mapcar (lambda (overlay)
833 (eq (overlay-get overlay 'invisible)
834 'org-babel-hide-result))
835 (overlays-at start)))
836 (if (or (not force) (eq force 'off))
837 (mapc (lambda (ov)
838 (when (member ov org-babel-hide-result-overlays)
839 (setq org-babel-hide-result-overlays
840 (delq ov org-babel-hide-result-overlays)))
841 (when (eq (overlay-get ov 'invisible)
842 'org-babel-hide-result)
843 (delete-overlay ov)))
844 (overlays-at start)))
845 (setq ov (make-overlay start end))
846 (overlay-put ov 'invisible 'org-babel-hide-result)
847 ;; make the block accessible to isearch
848 (overlay-put
849 ov 'isearch-open-invisible
850 (lambda (ov)
851 (when (member ov org-babel-hide-result-overlays)
852 (setq org-babel-hide-result-overlays
853 (delq ov org-babel-hide-result-overlays)))
854 (when (eq (overlay-get ov 'invisible)
855 'org-babel-hide-result)
856 (delete-overlay ov))))
857 (push ov org-babel-hide-result-overlays)))
858 (error "Not looking at a result line"))))
860 ;; org-tab-after-check-for-cycling-hook
861 (add-hook 'org-tab-first-hook 'org-babel-hide-result-toggle-maybe)
862 ;; Remove overlays when changing major mode
863 (add-hook 'org-mode-hook
864 (lambda () (org-add-hook 'change-major-mode-hook
865 'org-babel-show-result-all 'append 'local)))
867 (defvar org-file-properties)
868 (defun org-babel-params-from-properties (&optional lang)
869 "Retrieve parameters specified as properties.
870 Return an association list of any source block params which
871 may be specified in the properties of the current outline entry."
872 (save-match-data
873 (let (val sym)
874 (delq nil
875 (mapcar
876 (lambda (header-arg)
877 (and (setq val
878 (or (org-entry-get (point) header-arg t)
879 (org-entry-get (point) (concat ":" header-arg) t)))
880 (cons (intern (concat ":" header-arg))
881 (org-babel-read val))))
882 (mapcar
883 'symbol-name
884 (append
885 org-babel-header-arg-names
886 (progn
887 (setq sym (intern (concat "org-babel-header-arg-names:" lang)))
888 (and (boundp sym) (eval sym))))))))))
890 (defun org-babel-params-from-buffer ()
891 "Retrieve per-buffer parameters.
892 Return an association list of any source block params which
893 may be specified in the current buffer."
894 (or org-babel-current-buffer-properties
895 (save-match-data
896 (save-excursion
897 (save-restriction
898 (widen)
899 (goto-char (point-min))
900 (while (re-search-forward
901 (org-make-options-regexp (list "BABEL")) nil t)
902 (setq org-babel-current-buffer-properties
903 (org-babel-merge-params
904 org-babel-current-buffer-properties
905 (org-babel-parse-header-arguments
906 (org-match-string-no-properties 2)))))
907 org-babel-current-buffer-properties)))))
909 (defvar org-src-preserve-indentation)
910 (defun org-babel-parse-src-block-match ()
911 "Parse the results from a match of the `org-babel-src-block-regexp'."
912 (let* ((block-indentation (length (match-string 1)))
913 (lang (org-babel-clean-text-properties (match-string 2)))
914 (lang-headers (intern (concat "org-babel-default-header-args:" lang)))
915 (switches (match-string 3))
916 (body (org-babel-clean-text-properties (match-string 5)))
917 (preserve-indentation (or org-src-preserve-indentation
918 (string-match "-i\\>" switches))))
919 (list lang
920 ;; get block body less properties, protective commas, and indentation
921 (with-temp-buffer
922 (save-match-data
923 (insert (org-babel-strip-protective-commas body))
924 (unless preserve-indentation (org-do-remove-indentation))
925 (buffer-string)))
926 (org-babel-merge-params
927 org-babel-default-header-args
928 (org-babel-params-from-buffer)
929 (org-babel-params-from-properties lang)
930 (if (boundp lang-headers) (eval lang-headers) nil)
931 (org-babel-parse-header-arguments
932 (org-babel-clean-text-properties (or (match-string 4) ""))))
933 switches
934 block-indentation)))
936 (defun org-babel-parse-inline-src-block-match ()
937 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
938 (let* ((lang (org-babel-clean-text-properties (match-string 2)))
939 (lang-headers (intern (concat "org-babel-default-header-args:" lang))))
940 (list lang
941 (org-babel-strip-protective-commas
942 (org-babel-clean-text-properties (match-string 5)))
943 (org-babel-merge-params
944 org-babel-default-inline-header-args
945 (org-babel-params-from-buffer)
946 (org-babel-params-from-properties lang)
947 (if (boundp lang-headers) (eval lang-headers) nil)
948 (org-babel-parse-header-arguments
949 (org-babel-clean-text-properties (or (match-string 4) "")))))))
951 (defun org-babel-parse-header-arguments (arg-string)
952 "Parse a string of header arguments returning an alist."
953 (when (> (length arg-string) 0)
954 (delq nil
955 (mapcar
956 (lambda (arg)
957 (if (string-match
958 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
959 arg)
960 (cons (intern (match-string 1 arg))
961 (org-babel-read (org-babel-chomp (match-string 2 arg))))
962 (cons (intern (org-babel-chomp arg)) nil)))
963 (let ((balance 0) (partial nil) (lst nil) (last 0))
964 (mapc (lambda (ch) ; split on [] balanced instances of [ \t]:
965 (setq balance (+ balance
966 (cond ((equal 91 ch) 1)
967 ((equal 93 ch) -1)
968 (t 0))))
969 (setq partial (cons ch partial))
970 (when (and (= ch 58) (= balance 0)
971 (or (= last 32) (= last 9)))
972 (setq lst (cons (apply #'string (nreverse (cddr partial)))
973 lst))
974 (setq partial (list ch)))
975 (setq last ch))
976 (string-to-list arg-string))
977 (nreverse (cons (apply #'string (nreverse partial)) lst)))))))
979 (defun org-babel-process-params (params)
980 "Expand variables in PARAMS and add summary parameters."
981 (let* ((vars-and-names (org-babel-disassemble-tables
982 (mapcar (lambda (el)
983 (if (consp (cdr el))
984 (cdr el) (org-babel-ref-parse (cdr el))))
985 (org-babel-get-header params :var))
986 (cdr (assoc :hlines params))
987 (cdr (assoc :colnames params))
988 (cdr (assoc :rownames params))))
989 (raw-result (or (cdr (assoc :results params)) ""))
990 (result-params (append
991 (split-string (if (stringp raw-result)
992 raw-result
993 (eval raw-result)))
994 (cdr (assoc :result-params params)))))
995 (append
996 (mapcar (lambda (var) (cons :var var)) (car vars-and-names))
997 (list
998 (cons :colname-names (cadr vars-and-names))
999 (cons :rowname-names (caddr vars-and-names))
1000 (cons :result-params result-params)
1001 (cons :result-type (cond ((member "output" result-params) 'output)
1002 ((member "value" result-params) 'value)
1003 (t 'value))))
1004 (org-babel-get-header params :var 'other))))
1006 ;; row and column names
1007 (defun org-babel-del-hlines (table)
1008 "Remove all 'hlines from TABLE."
1009 (remove 'hline table))
1011 (defun org-babel-get-colnames (table)
1012 "Return the column names of TABLE.
1013 Return a cons cell, the `car' of which contains the TABLE less
1014 colnames, and the `cdr' of which contains a list of the column
1015 names."
1016 (if (equal 'hline (nth 1 table))
1017 (cons (cddr table) (car table))
1018 (cons (cdr table) (car table))))
1020 (defun org-babel-get-rownames (table)
1021 "Return the row names of TABLE.
1022 Return a cons cell, the `car' of which contains the TABLE less
1023 colnames, and the `cdr' of which contains a list of the column
1024 names. Note: this function removes any hlines in TABLE."
1025 (flet ((trans (table) (apply #'mapcar* #'list table)))
1026 (let* ((width (apply 'max
1027 (mapcar (lambda (el) (if (listp el) (length el) 0)) table)))
1028 (table (trans (mapcar (lambda (row)
1029 (if (not (equal row 'hline))
1031 (setq row '())
1032 (dotimes (n width)
1033 (setq row (cons 'hline row)))
1034 row))
1035 table))))
1036 (cons (mapcar (lambda (row) (if (equal (car row) 'hline) 'hline row))
1037 (trans (cdr table)))
1038 (remove 'hline (car table))))))
1040 (defun org-babel-put-colnames (table colnames)
1041 "Add COLNAMES to TABLE if they exist."
1042 (if colnames (apply 'list colnames 'hline table) table))
1044 (defun org-babel-put-rownames (table rownames)
1045 "Add ROWNAMES to TABLE if they exist."
1046 (if rownames
1047 (mapcar (lambda (row)
1048 (if (listp row)
1049 (cons (or (pop rownames) "") row)
1050 row)) table)
1051 table))
1053 (defun org-babel-pick-name (names selector)
1054 "Select one out of an alist of row or column names.
1055 SELECTOR can be either a list of names in which case those names
1056 will be returned directly, or an index into the list NAMES in
1057 which case the indexed names will be return."
1058 (if (listp selector)
1059 selector
1060 (when names
1061 (if (and selector (symbolp selector) (not (equal t selector)))
1062 (cdr (assoc selector names))
1063 (if (integerp selector)
1064 (nth (- selector 1) names)
1065 (cdr (car (last names))))))))
1067 (defun org-babel-disassemble-tables (vars hlines colnames rownames)
1068 "Parse tables for further processing.
1069 Process the variables in VARS according to the HLINES,
1070 ROWNAMES and COLNAMES header arguments. Return a list consisting
1071 of the vars, cnames and rnames."
1072 (let (cnames rnames)
1073 (list
1074 (mapcar
1075 (lambda (var)
1076 (when (listp (cdr var))
1077 (when (and (not (equal colnames "no"))
1078 (or colnames (and (equal (nth 1 (cdr var)) 'hline)
1079 (not (member 'hline (cddr (cdr var)))))))
1080 (let ((both (org-babel-get-colnames (cdr var))))
1081 (setq cnames (cons (cons (car var) (cdr both))
1082 cnames))
1083 (setq var (cons (car var) (car both)))))
1084 (when (and rownames (not (equal rownames "no")))
1085 (let ((both (org-babel-get-rownames (cdr var))))
1086 (setq rnames (cons (cons (car var) (cdr both))
1087 rnames))
1088 (setq var (cons (car var) (car both)))))
1089 (when (and hlines (not (equal hlines "yes")))
1090 (setq var (cons (car var) (org-babel-del-hlines (cdr var))))))
1091 var)
1092 vars)
1093 cnames rnames)))
1095 (defun org-babel-reassemble-table (table colnames rownames)
1096 "Add column and row names to a table.
1097 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1098 to the table for reinsertion to org-mode."
1099 (if (listp table)
1100 ((lambda (table)
1101 (if (and colnames (listp (car table)) (= (length (car table))
1102 (length colnames)))
1103 (org-babel-put-colnames table colnames) table))
1104 (if (and rownames (= (length table) (length rownames)))
1105 (org-babel-put-rownames table rownames) table))
1106 table))
1108 (defun org-babel-where-is-src-block-head ()
1109 "Find where the current source block begins.
1110 Return the point at the beginning of the current source
1111 block. Specifically at the beginning of the #+BEGIN_SRC line.
1112 If the point is not on a source block then return nil."
1113 (let ((initial (point)) top bottom)
1115 (save-excursion ;; on a source name line or a #+header line
1116 (beginning-of-line 1)
1117 (and (or (looking-at org-babel-src-name-regexp)
1118 (looking-at org-babel-multi-line-header-regexp))
1119 (progn
1120 (while (and (forward-line 1)
1121 (looking-at org-babel-multi-line-header-regexp)))
1122 (looking-at org-babel-src-block-regexp))
1123 (point)))
1124 (save-excursion ;; on a #+begin_src line
1125 (beginning-of-line 1)
1126 (and (looking-at org-babel-src-block-regexp)
1127 (point)))
1128 (save-excursion ;; inside a src block
1129 (and
1130 (re-search-backward "^[ \t]*#\\+begin_src" nil t) (setq top (point))
1131 (re-search-forward "^[ \t]*#\\+end_src" nil t) (setq bottom (point))
1132 (< top initial) (< initial bottom)
1133 (progn (goto-char top) (beginning-of-line 1)
1134 (looking-at org-babel-src-block-regexp))
1135 (point))))))
1137 ;;;###autoload
1138 (defun org-babel-goto-src-block-head ()
1139 "Go to the beginning of the current code block."
1140 (interactive)
1141 ((lambda (head)
1142 (if head (goto-char head) (error "not currently in a code block")))
1143 (org-babel-where-is-src-block-head)))
1145 ;;;###autoload
1146 (defun org-babel-goto-named-src-block (name)
1147 "Go to a named source-code block."
1148 (interactive
1149 (let ((completion-ignore-case t))
1150 (list (org-icompleting-read "source-block name: "
1151 (org-babel-src-block-names) nil t))))
1152 (let ((point (org-babel-find-named-block name)))
1153 (if point
1154 ;; taken from `org-open-at-point'
1155 (progn (goto-char point) (org-show-context))
1156 (message "source-code block '%s' not found in this buffer" name))))
1158 (defun org-babel-find-named-block (name)
1159 "Find a named source-code block.
1160 Return the location of the source block identified by source
1161 NAME, or nil if no such block exists. Set match data according to
1162 org-babel-named-src-block-regexp."
1163 (save-excursion
1164 (let ((case-fold-search t)
1165 (regexp (org-babel-named-src-block-regexp-for-name name)) msg)
1166 (goto-char (point-min))
1167 (when (or (re-search-forward regexp nil t)
1168 (re-search-backward regexp nil t))
1169 (match-beginning 0)))))
1171 (defun org-babel-src-block-names (&optional file)
1172 "Returns the names of source blocks in FILE or the current buffer."
1173 (save-excursion
1174 (when file (find-file file)) (goto-char (point-min))
1175 (let (names)
1176 (while (re-search-forward org-babel-src-name-w-name-regexp nil t)
1177 (setq names (cons (match-string 4) names)))
1178 names)))
1180 ;;;###autoload
1181 (defun org-babel-goto-named-result (name)
1182 "Go to a named result."
1183 (interactive
1184 (let ((completion-ignore-case t))
1185 (list (org-icompleting-read "source-block name: "
1186 (org-babel-result-names) nil t))))
1187 (let ((point (org-babel-find-named-result name)))
1188 (if point
1189 ;; taken from `org-open-at-point'
1190 (progn (goto-char point) (org-show-context))
1191 (message "result '%s' not found in this buffer" name))))
1193 (defun org-babel-find-named-result (name)
1194 "Find a named result.
1195 Return the location of the result named NAME in the current
1196 buffer or nil if no such result exists."
1197 (save-excursion
1198 (goto-char (point-min))
1199 (when (re-search-forward
1200 (concat org-babel-result-regexp
1201 "[ \t]" (regexp-quote name) "[ \t\n\f\v\r]") nil t)
1202 (beginning-of-line 0) (point))))
1204 (defun org-babel-result-names (&optional file)
1205 "Returns the names of results in FILE or the current buffer."
1206 (save-excursion
1207 (when file (find-file file)) (goto-char (point-min))
1208 (let (names)
1209 (while (re-search-forward org-babel-result-w-name-regexp nil t)
1210 (setq names (cons (match-string 4) names)))
1211 names)))
1213 ;;;###autoload
1214 (defun org-babel-next-src-block (&optional arg)
1215 "Jump to the next source block.
1216 With optional prefix argument ARG, jump forward ARG many source blocks."
1217 (interactive "P")
1218 (when (looking-at org-babel-src-block-regexp) (forward-char 1))
1219 (condition-case nil
1220 (re-search-forward org-babel-src-block-regexp nil nil (or arg 1))
1221 (error (error "No further code blocks")))
1222 (goto-char (match-beginning 0)) (org-show-context))
1224 ;;;###autoload
1225 (defun org-babel-previous-src-block (&optional arg)
1226 "Jump to the previous source block.
1227 With optional prefix argument ARG, jump backward ARG many source blocks."
1228 (interactive "P")
1229 (condition-case nil
1230 (re-search-backward org-babel-src-block-regexp nil nil (or arg 1))
1231 (error (error "No previous code blocks")))
1232 (goto-char (match-beginning 0)) (org-show-context))
1234 (defvar org-babel-load-languages)
1236 ;;;###autoload
1237 (defun org-babel-mark-block ()
1238 "Mark current src block"
1239 (interactive)
1240 ((lambda (head)
1241 (when head
1242 (save-excursion
1243 (goto-char head)
1244 (looking-at org-babel-src-block-regexp))
1245 (push-mark (match-end 5) nil t)
1246 (goto-char (match-beginning 5))))
1247 (org-babel-where-is-src-block-head)))
1249 (defun org-babel-demarcate-block (&optional arg)
1250 "Wrap or split the code in the region or on the point.
1251 When called from inside of a code block the current block is
1252 split. When called from outside of a code block a new code block
1253 is created. In both cases if the region is demarcated and if the
1254 region is not active then the point is demarcated."
1255 (interactive "P")
1256 (let ((info (org-babel-get-src-block-info 'light))
1257 (stars (concat (make-string (or (org-current-level) 1) ?*) " ")))
1258 (if info
1259 (mapc
1260 (lambda (place)
1261 (save-excursion
1262 (goto-char place)
1263 (let ((lang (nth 0 info))
1264 (indent (make-string (nth 5 info) ? )))
1265 (when (string-match "^[[:space:]]*$"
1266 (buffer-substring (point-at-bol)
1267 (point-at-eol)))
1268 (delete-region (point-at-bol) (point-at-eol)))
1269 (insert (concat (if (looking-at "^") "" "\n")
1270 indent "#+end_src\n"
1271 (if arg stars indent) "\n"
1272 indent "#+begin_src " lang
1273 (if (looking-at "[\n\r]") "" "\n")))))
1274 (move-end-of-line 2))
1275 (sort (if (region-active-p) (list (mark) (point)) (list (point))) #'>))
1276 (let ((start (point))
1277 (lang (org-icompleting-read "Lang: "
1278 (mapcar (lambda (el) (symbol-name (car el)))
1279 org-babel-load-languages)))
1280 (body (delete-and-extract-region
1281 (if (region-active-p) (mark) (point)) (point))))
1282 (insert (concat (if (looking-at "^") "" "\n")
1283 (if arg (concat stars "\n") "")
1284 "#+begin_src " lang "\n"
1285 body
1286 (if (or (= (length body) 0)
1287 (string-match "[\r\n]$" body)) "" "\n")
1288 "#+end_src\n"))
1289 (goto-char start) (move-end-of-line 1)))))
1291 (defvar org-babel-lob-one-liner-regexp)
1292 (defun org-babel-where-is-src-block-result (&optional insert info hash indent)
1293 "Find where the current source block results begin.
1294 Return the point at the beginning of the result of the current
1295 source block. Specifically at the beginning of the results line.
1296 If no result exists for this block then create a results line
1297 following the source block."
1298 (save-excursion
1299 (let* ((on-lob-line (save-excursion
1300 (beginning-of-line 1)
1301 (looking-at org-babel-lob-one-liner-regexp)))
1302 (inlinep (save-excursion
1303 (re-search-backward "[ \f\t\n\r\v]" nil t)
1304 (when (looking-at org-babel-inline-src-block-regexp)
1305 (match-end 0))))
1306 (name (if on-lob-line
1307 (nth 0 (org-babel-lob-get-info))
1308 (nth 4 (or info (org-babel-get-src-block-info)))))
1309 (head (unless on-lob-line (org-babel-where-is-src-block-head)))
1310 found beg end)
1311 (when head (goto-char head))
1312 (setq
1313 found ;; was there a result (before we potentially insert one)
1315 inlinep
1316 (and
1317 ;; named results:
1318 ;; - return t if it is found, else return nil
1319 ;; - if it does not need to be rebuilt, then don't set end
1320 ;; - if it does need to be rebuilt then do set end
1321 name (setq beg (org-babel-find-named-result name))
1322 (prog1 beg
1323 (when (and hash (not (string= hash (match-string 3))))
1324 (goto-char beg) (setq end beg) ;; beginning of result
1325 (forward-line 1)
1326 (delete-region end (org-babel-result-end)) nil)))
1327 (and
1328 ;; unnamed results:
1329 ;; - return t if it is found, else return nil
1330 ;; - if it is found, and the hash doesn't match, delete and set end
1331 (or on-lob-line (re-search-forward "^[ \t]*#\\+end_src" nil t))
1332 (progn (end-of-line 1)
1333 (if (eobp) (insert "\n") (forward-char 1))
1334 (setq end (point))
1335 (or (and (not name)
1336 (progn ;; unnamed results line already exists
1337 (re-search-forward "[^ \f\t\n\r\v]" nil t)
1338 (beginning-of-line 1)
1339 (looking-at
1340 (concat org-babel-result-regexp "\n")))
1341 (prog1 (point)
1342 ;; must remove and rebuild if hash!=old-hash
1343 (if (and hash (not (string= hash (match-string 3))))
1344 (prog1 nil
1345 (forward-line 1)
1346 (delete-region
1347 end (org-babel-result-end)))
1348 (setq end nil)))))))))
1349 (if (and insert end)
1350 (progn
1351 (goto-char end)
1352 (unless beg
1353 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1354 (insert (concat
1355 (if indent
1356 (mapconcat
1357 (lambda (el) " ")
1358 (org-number-sequence 1 indent) "")
1360 "#+results"
1361 (when hash (concat "["hash"]"))
1363 (when name (concat " " name)) "\n"))
1364 (unless beg (insert "\n") (backward-char))
1365 (beginning-of-line 0)
1366 (if hash (org-babel-hide-hash))
1367 (point))
1368 found))))
1370 (defvar org-block-regexp)
1371 (defun org-babel-read-result ()
1372 "Read the result at `point' into emacs-lisp."
1373 (let ((case-fold-search t) result-string)
1374 (cond
1375 ((org-at-table-p) (org-babel-read-table))
1376 ((org-at-item-p) (org-babel-read-list))
1377 ((looking-at org-bracket-link-regexp) (org-babel-read-link))
1378 ((looking-at org-block-regexp) (org-babel-trim (match-string 4)))
1379 ((looking-at "^[ \t]*: ")
1380 (setq result-string
1381 (org-babel-trim
1382 (mapconcat (lambda (line)
1383 (if (and (> (length line) 1)
1384 (string-match "^[ \t]*: \\(.+\\)" line))
1385 (match-string 1 line)
1386 line))
1387 (split-string
1388 (buffer-substring
1389 (point) (org-babel-result-end)) "[\r\n]+")
1390 "\n")))
1391 (or (org-babel-number-p result-string) result-string))
1392 ((looking-at org-babel-result-regexp)
1393 (save-excursion (forward-line 1) (org-babel-read-result))))))
1395 (defun org-babel-read-table ()
1396 "Read the table at `point' into emacs-lisp."
1397 (mapcar (lambda (row)
1398 (if (and (symbolp row) (equal row 'hline)) row
1399 (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval)) row)))
1400 (org-table-to-lisp)))
1402 (defun org-babel-read-list ()
1403 "Read the list at `point' into emacs-lisp."
1404 (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval))
1405 (mapcar #'cadr (cdr (org-list-parse-list)))))
1407 (defvar org-link-types-re)
1408 (defun org-babel-read-link ()
1409 "Read the link at `point' into emacs-lisp.
1410 If the path of the link is a file path it is expanded using
1411 `expand-file-name'."
1412 (let* ((case-fold-search t)
1413 (raw (and (looking-at org-bracket-link-regexp)
1414 (org-babel-clean-text-properties (match-string 1))))
1415 (type (and (string-match org-link-types-re raw)
1416 (match-string 1 raw))))
1417 (cond
1418 ((not type) (expand-file-name raw))
1419 ((string= type "file")
1420 (and (string-match "file\\(.*\\):\\(.+\\)" raw)
1421 (expand-file-name (match-string 2 raw))))
1422 (t raw))))
1424 (defun org-babel-format-result (result &optional sep)
1425 "Format RESULT for writing to file."
1426 (flet ((echo-res (result)
1427 (if (stringp result) result (format "%S" result))))
1428 (if (listp result)
1429 ;; table result
1430 (orgtbl-to-generic
1431 result
1432 (list
1433 :sep (or sep "\t")
1434 :fmt 'echo-res))
1435 ;; scalar result
1436 (echo-res result))))
1438 (defun org-babel-insert-result
1439 (result &optional result-params info hash indent lang)
1440 "Insert RESULT into the current buffer.
1441 By default RESULT is inserted after the end of the
1442 current source block. With optional argument RESULT-PARAMS
1443 controls insertion of results in the org-mode file.
1444 RESULT-PARAMS can take the following values...
1446 replace - (default option) insert results after the source block
1447 replacing any previously inserted results
1449 silent -- no results are inserted
1451 file ---- the results are interpreted as a file path, and are
1452 inserted into the buffer using the Org-mode file syntax
1454 list ---- the results are interpreted as an Org-mode list.
1456 raw ----- results are added directly to the Org-mode file. This
1457 is a good option if you code block will output org-mode
1458 formatted text.
1460 org ----- similar in effect to raw, only the results are wrapped
1461 in an org code block. Similar to the raw option, on
1462 export the results will be interpreted as org-formatted
1463 text, however by wrapping the results in an org code
1464 block they can be replaced upon re-execution of the
1465 code block.
1467 html ---- results are added inside of a #+BEGIN_HTML block. This
1468 is a good option if you code block will output html
1469 formatted text.
1471 latex --- results are added inside of a #+BEGIN_LATEX block.
1472 This is a good option if you code block will output
1473 latex formatted text.
1475 code ---- the results are extracted in the syntax of the source
1476 code of the language being evaluated and are added
1477 inside of a #+BEGIN_SRC block with the source-code
1478 language set appropriately. Note this relies on the
1479 optional LANG argument."
1480 (if (stringp result)
1481 (progn
1482 (setq result (org-babel-clean-text-properties result))
1483 (when (member "file" result-params)
1484 (setq result (org-babel-result-to-file result))))
1485 (unless (listp result) (setq result (format "%S" result))))
1486 (if (and result-params (member "silent" result-params))
1487 (progn
1488 (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
1489 result)
1490 (save-excursion
1491 (let* ((inlinep (save-excursion
1492 (re-search-backward "[ \f\t\n\r\v]" nil t)
1493 (when (looking-at org-babel-inline-src-block-regexp)
1494 (goto-char (match-end 0))
1495 (insert (if (listp result) "\n" " "))
1496 (point))))
1497 (existing-result (unless inlinep
1498 (org-babel-where-is-src-block-result
1499 t info hash indent)))
1500 (results-switches
1501 (cdr (assoc :results_switches (nth 2 info))))
1502 beg end)
1503 (when (and (stringp result) ; ensure results end in a newline
1504 (not inlinep)
1505 (> (length result) 0)
1506 (not (or (string-equal (substring result -1) "\n")
1507 (string-equal (substring result -1) "\r"))))
1508 (setq result (concat result "\n")))
1509 (if (not existing-result)
1510 (setq beg (or inlinep (point)))
1511 (goto-char existing-result)
1512 (save-excursion
1513 (re-search-forward "#" nil t)
1514 (setq indent (- (current-column) 1)))
1515 (forward-line 1)
1516 (setq beg (point))
1517 (cond
1518 ((member "replace" result-params)
1519 (delete-region (point) (org-babel-result-end)))
1520 ((member "append" result-params)
1521 (goto-char (org-babel-result-end)) (setq beg (point-marker)))
1522 ((member "prepend" result-params)))) ; already there
1523 (setq results-switches
1524 (if results-switches (concat " " results-switches) ""))
1525 ;; insert results based on type
1526 (cond
1527 ;; do nothing for an empty result
1528 ((= (length result) 0))
1529 ;; insert a list if preferred
1530 ((member "list" result-params)
1531 (insert
1532 (org-babel-trim
1533 (org-list-to-generic
1534 (cons 'unordered
1535 (mapcar
1536 (lambda (el) (list nil (if (stringp el) el (format "%S" el))))
1537 (if (listp result) result (list result))))
1538 '(:splicep nil :istart "- " :iend "\n")))
1539 "\n"))
1540 ;; assume the result is a table if it's not a string
1541 ((not (stringp result))
1542 (goto-char beg)
1543 (insert (concat (orgtbl-to-orgtbl
1544 (if (or (eq 'hline (car result))
1545 (and (listp (car result))
1546 (listp (cdr (car result)))))
1547 result (list result))
1548 '(:fmt (lambda (cell) (format "%s" cell)))) "\n"))
1549 (goto-char beg) (when (org-at-table-p) (org-table-align)))
1550 ((member "file" result-params)
1551 (insert result))
1552 (t (goto-char beg) (insert result)))
1553 (when (listp result) (goto-char (org-table-end)))
1554 (setq end (point-marker))
1555 ;; possibly wrap result
1556 (flet ((wrap (start finish)
1557 (goto-char beg) (insert (concat start "\n"))
1558 (goto-char end) (insert (concat finish "\n"))
1559 (setq end (point-marker))))
1560 (cond
1561 ((member "html" result-params)
1562 (wrap "#+BEGIN_HTML" "#+END_HTML"))
1563 ((member "latex" result-params)
1564 (wrap "#+BEGIN_LaTeX" "#+END_LaTeX"))
1565 ((member "code" result-params)
1566 (wrap (format "#+BEGIN_SRC %s%s" (or lang "none") results-switches)
1567 "#+END_SRC"))
1568 ((member "org" result-params)
1569 (wrap "#+BEGIN_ORG" "#+END_ORG"))
1570 ((member "raw" result-params)
1571 (goto-char beg) (if (org-at-table-p) (org-cycle)))
1572 ((member "wrap" result-params)
1573 (when (and (stringp result) (not (member "file" result-params)))
1574 (org-babel-examplize-region beg end results-switches))
1575 (wrap "#+BEGIN_RESULT" "#+END_RESULT"))
1576 ((and (stringp result) (not (member "file" result-params)))
1577 (org-babel-examplize-region beg end results-switches)
1578 (setq end (point)))))
1579 ;; possibly indent the results to match the #+results line
1580 (when (and (not inlinep) (numberp indent) indent (> indent 0)
1581 ;; in this case `table-align' does the work for us
1582 (not (and (listp result)
1583 (member "append" result-params))))
1584 (indent-rigidly beg end indent))))
1585 (if (= (length result) 0)
1586 (if (member "value" result-params)
1587 (message "Code block returned no value.")
1588 (message "Code block produced no output."))
1589 (message "Code block evaluation complete."))))
1591 (defun org-babel-remove-result (&optional info)
1592 "Remove the result of the current source block."
1593 (interactive)
1594 (let ((location (org-babel-where-is-src-block-result nil info)) start)
1595 (when location
1596 (save-excursion
1597 (goto-char location) (setq start (point)) (forward-line 1)
1598 (delete-region start (org-babel-result-end))))))
1600 (defun org-babel-result-end ()
1601 "Return the point at the end of the current set of results"
1602 (save-excursion
1603 (cond
1604 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
1605 ((org-at-item-p) (let* ((struct (org-list-struct))
1606 (prvs (org-list-prevs-alist struct)))
1607 (org-list-get-list-end (point-at-bol) struct prvs)))
1609 (let ((case-fold-search t)
1610 (blocks-re (regexp-opt
1611 (list "latex" "html" "example" "src" "result" "org"))))
1612 (if (looking-at (concat "[ \t]*#\\+begin_" blocks-re))
1613 (progn (re-search-forward (concat "[ \t]*#\\+end_" blocks-re) nil t)
1614 (forward-char 1))
1615 (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
1616 (forward-line 1))))
1617 (point)))))
1619 (defun org-babel-result-to-file (result)
1620 "Convert RESULT into an `org-mode' link.
1621 If the `default-directory' is different from the containing
1622 file's directory then expand relative links."
1623 (flet ((cond-exp (file)
1624 (if (and default-directory
1625 buffer-file-name
1626 (not (string= (expand-file-name default-directory)
1627 (expand-file-name
1628 (file-name-directory buffer-file-name)))))
1629 (expand-file-name file default-directory)
1630 file)))
1631 (if (stringp result)
1632 (format "[[file:%s]]" (cond-exp result))
1633 (when (and (listp result) (= 2 (length result))
1634 (stringp (car result)) (stringp (cadr result)))
1635 (format "[[file:%s][%s]]" (car result) (cadr result))))))
1637 (defun org-babel-examplize-region (beg end &optional results-switches)
1638 "Comment out region using the inline '==' or ': ' org example quote."
1639 (interactive "*r")
1640 (flet ((chars-between (b e) (string-match "[\\S]" (buffer-substring b e))))
1641 (if (or (chars-between (save-excursion (goto-char beg) (point-at-bol)) beg)
1642 (chars-between end (save-excursion (goto-char end) (point-at-eol))))
1643 (save-excursion
1644 (goto-char beg)
1645 (insert (format "=%s=" (prog1 (buffer-substring beg end)
1646 (delete-region beg end)))))
1647 (let ((size (count-lines beg end)))
1648 (save-excursion
1649 (cond ((= size 0)) ; do nothing for an empty result
1650 ((< size org-babel-min-lines-for-block-output)
1651 (goto-char beg)
1652 (dotimes (n size)
1653 (beginning-of-line 1) (insert ": ") (forward-line 1)))
1655 (goto-char beg)
1656 (insert (if results-switches
1657 (format "#+begin_example%s\n" results-switches)
1658 "#+begin_example\n"))
1659 (if (markerp end) (goto-char end) (forward-char (- end beg)))
1660 (insert "#+end_example\n"))))))))
1662 (defun org-babel-update-block-body (new-body)
1663 "Update the body of the current code block to NEW-BODY."
1664 (if (not (org-babel-where-is-src-block-head))
1665 (error "not in source block")
1666 (save-match-data
1667 (replace-match (concat (org-babel-trim new-body) "\n") nil t nil 5))
1668 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
1670 (defun org-babel-merge-params (&rest plists)
1671 "Combine all parameter association lists in PLISTS.
1672 Later elements of PLISTS override the values of previous elements.
1673 This takes into account some special considerations for certain
1674 parameters when merging lists."
1675 (let ((results-exclusive-groups
1676 '(("file" "list" "vector" "table" "scalar" "raw" "org"
1677 "html" "latex" "code" "pp" "wrap")
1678 ("replace" "silent" "append" "prepend")
1679 ("output" "value")))
1680 (exports-exclusive-groups
1681 '(("code" "results" "both" "none")))
1682 params results exports tangle noweb cache vars shebang comments)
1683 (flet ((e-merge (exclusive-groups &rest result-params)
1684 ;; maintain exclusivity of mutually exclusive parameters
1685 (let (output)
1686 (mapc (lambda (new-params)
1687 (mapc (lambda (new-param)
1688 (mapc (lambda (exclusive-group)
1689 (when (member new-param exclusive-group)
1690 (mapcar (lambda (excluded-param)
1691 (setq output
1692 (delete
1693 excluded-param
1694 output)))
1695 exclusive-group)))
1696 exclusive-groups)
1697 (setq output (org-uniquify
1698 (cons new-param output))))
1699 new-params))
1700 result-params)
1701 output)))
1702 (mapc
1703 (lambda (plist)
1704 (mapc
1705 (lambda (pair)
1706 (case (car pair)
1707 (:var
1708 (let ((name (if (listp (cdr pair))
1709 (cadr pair)
1710 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
1711 (cdr pair))
1712 (intern (match-string 1 (cdr pair)))))))
1713 (when name
1714 (setq vars
1715 (cons (cons name pair)
1716 (if (member name (mapcar #'car vars))
1717 (delq nil
1718 (mapcar
1719 (lambda (p) (unless (equal (car p) name) p))
1720 vars))
1721 vars))))))
1722 (:results
1723 (setq results (e-merge results-exclusive-groups
1724 results
1725 (split-string
1726 (let ((r (cdr pair)))
1727 (if (stringp r) r (eval r)))))))
1728 (:file
1729 (when (cdr pair)
1730 (setq results (e-merge results-exclusive-groups
1731 results '("file")))
1732 (unless (or (member "both" exports)
1733 (member "none" exports)
1734 (member "code" exports))
1735 (setq exports (e-merge exports-exclusive-groups
1736 exports '("results"))))
1737 (setq params (cons pair (assq-delete-all (car pair) params)))))
1738 (:exports
1739 (setq exports (e-merge exports-exclusive-groups
1740 exports (split-string (cdr pair)))))
1741 (:tangle ;; take the latest -- always overwrite
1742 (setq tangle (or (list (cdr pair)) tangle)))
1743 (:noweb
1744 (setq noweb (e-merge '(("yes" "no" "tangle")) noweb
1745 (split-string (or (cdr pair) "")))))
1746 (:cache
1747 (setq cache (e-merge '(("yes" "no")) cache
1748 (split-string (or (cdr pair) "")))))
1749 (:shebang ;; take the latest -- always overwrite
1750 (setq shebang (or (list (cdr pair)) shebang)))
1751 (:comments
1752 (setq comments (e-merge '(("yes" "no")) comments
1753 (split-string (or (cdr pair) "")))))
1754 (t ;; replace: this covers e.g. :session
1755 (setq params (cons pair (assq-delete-all (car pair) params))))))
1756 plist))
1757 plists))
1758 (while vars (setq params (cons (cons :var (cddr (pop vars))) params)))
1759 (cons (cons :comments (mapconcat 'identity comments " "))
1760 (cons (cons :shebang (mapconcat 'identity shebang " "))
1761 (cons (cons :cache (mapconcat 'identity cache " "))
1762 (cons (cons :noweb (mapconcat 'identity noweb " "))
1763 (cons (cons :tangle (mapconcat 'identity tangle " "))
1764 (cons (cons :exports
1765 (mapconcat 'identity exports " "))
1766 (cons
1767 (cons :results
1768 (mapconcat 'identity results " "))
1769 params)))))))))
1771 (defun org-babel-expand-noweb-references (&optional info parent-buffer)
1772 "Expand Noweb references in the body of the current source code block.
1774 For example the following reference would be replaced with the
1775 body of the source-code block named 'example-block'.
1777 <<example-block>>
1779 Note that any text preceding the <<foo>> construct on a line will
1780 be interposed between the lines of the replacement text. So for
1781 example if <<foo>> is placed behind a comment, then the entire
1782 replacement text will also be commented.
1784 This function must be called from inside of the buffer containing
1785 the source-code block which holds BODY.
1787 In addition the following syntax can be used to insert the
1788 results of evaluating the source-code block named 'example-block'.
1790 <<example-block()>>
1792 Any optional arguments can be passed to example-block by placing
1793 the arguments inside the parenthesis following the convention
1794 defined by `org-babel-lob'. For example
1796 <<example-block(a=9)>>
1798 would set the value of argument \"a\" equal to \"9\". Note that
1799 these arguments are not evaluated in the current source-code
1800 block but are passed literally to the \"example-block\"."
1801 (let* ((parent-buffer (or parent-buffer (current-buffer)))
1802 (info (or info (org-babel-get-src-block-info)))
1803 (lang (nth 0 info))
1804 (body (nth 1 info))
1805 (comment (string= "noweb" (cdr (assoc :comments (nth 2 info)))))
1806 (new-body "") index source-name evaluate prefix)
1807 (flet ((nb-add (text) (setq new-body (concat new-body text)))
1808 (c-wrap (text)
1809 (with-temp-buffer
1810 (funcall (intern (concat lang "-mode")))
1811 (comment-region (point) (progn (insert text) (point)))
1812 (org-babel-trim (buffer-string)))))
1813 (with-temp-buffer
1814 (insert body) (goto-char (point-min))
1815 (setq index (point))
1816 (while (and (re-search-forward "<<\\(.+?\\)>>" nil t))
1817 (save-match-data (setf source-name (match-string 1)))
1818 (save-match-data (setq evaluate (string-match "\(.*\)" source-name)))
1819 (save-match-data
1820 (setq prefix
1821 (buffer-substring (match-beginning 0)
1822 (save-excursion
1823 (beginning-of-line 1) (point)))))
1824 ;; add interval to new-body (removing noweb reference)
1825 (goto-char (match-beginning 0))
1826 (nb-add (buffer-substring index (point)))
1827 (goto-char (match-end 0))
1828 (setq index (point))
1829 (nb-add
1830 (with-current-buffer parent-buffer
1831 (mapconcat ;; interpose PREFIX between every line
1832 #'identity
1833 (split-string
1834 (if evaluate
1835 (let ((raw (org-babel-ref-resolve source-name)))
1836 (if (stringp raw) raw (format "%S" raw)))
1837 (or (nth 2 (assoc (intern source-name)
1838 org-babel-library-of-babel))
1839 (save-restriction
1840 (widen)
1841 (let ((point (org-babel-find-named-block
1842 source-name)))
1843 (if point
1844 (save-excursion
1845 (goto-char point)
1846 ;; possibly wrap body in comments
1847 (let* ((i (org-babel-get-src-block-info 'light))
1848 (body (org-babel-trim
1849 (org-babel-expand-noweb-references
1850 i))))
1851 (if comment
1852 ((lambda (cs) (concat (c-wrap (car cs)) "\n"
1853 body
1854 "\n" (c-wrap (cadr cs))))
1855 (org-babel-tangle-comment-links i))
1856 body)))
1857 ;; optionally raise an error if named
1858 ;; source-block doesn't exist
1859 (if (member lang org-babel-noweb-error-langs)
1860 (error "%s"
1861 (concat
1862 "<<" source-name ">> "
1863 "could not be resolved (see "
1864 "`org-babel-noweb-error-langs')"))
1865 ""))))))
1866 "[\n\r]") (concat "\n" prefix)))))
1867 (nb-add (buffer-substring index (point-max)))))
1868 new-body))
1870 (defun org-babel-clean-text-properties (text)
1871 "Strip all properties from text return."
1872 (when text
1873 (set-text-properties 0 (length text) nil text) text))
1875 (defun org-babel-strip-protective-commas (body)
1876 "Strip protective commas from bodies of source blocks."
1877 (replace-regexp-in-string "^,#" "#" body))
1879 (defun org-babel-script-escape (str)
1880 "Safely convert tables into elisp lists."
1881 (let (in-single in-double out)
1882 ((lambda (escaped) (condition-case nil (org-babel-read escaped) (error escaped)))
1883 (if (and (stringp str)
1884 (> (length str) 2)
1885 (string-equal "[" (substring str 0 1))
1886 (string-equal "]" (substring str -1)))
1887 (org-babel-read
1888 (concat
1890 (progn
1891 (mapc
1892 (lambda (ch)
1893 (setq
1895 (case ch
1896 (91 (if (or in-double in-single) ; [
1897 (cons 91 out)
1898 (cons 40 out)))
1899 (93 (if (or in-double in-single) ; ]
1900 (cons 93 out)
1901 (cons 41 out)))
1902 (44 (if (or in-double in-single) ; ,
1903 (cons 44 out) (cons 32 out)))
1904 (39 (if in-double ; '
1905 (cons 39 out)
1906 (setq in-single (not in-single)) (cons 34 out)))
1907 (34 (if in-single ; "
1908 (append (list 34 32) out)
1909 (setq in-double (not in-double)) (cons 34 out)))
1910 (t (cons ch out)))))
1911 (string-to-list str))
1912 (apply #'string (reverse out)))))
1913 str))))
1915 (defun org-babel-read (cell &optional inhibit-lisp-eval)
1916 "Convert the string value of CELL to a number if appropriate.
1917 Otherwise if cell looks like lisp (meaning it starts with a
1918 \"(\", \"'\", \"`\" or a \"[\") then read it as lisp, otherwise
1919 return it unmodified as a string. Optional argument NO-LISP-EVAL
1920 inhibits lisp evaluation for situations in which is it not
1921 appropriate."
1922 (if (and (stringp cell) (not (equal cell "")))
1923 (or (org-babel-number-p cell)
1924 (if (and (not inhibit-lisp-eval)
1925 (member (substring cell 0 1) '("(" "'" "`" "[")))
1926 (eval (read cell))
1927 (if (string= (substring cell 0 1) "\"")
1928 (read cell)
1929 (progn (set-text-properties 0 (length cell) nil cell) cell))))
1930 cell))
1932 (defun org-babel-number-p (string)
1933 "If STRING represents a number return it's value."
1934 (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string)
1935 (= (length (substring string (match-beginning 0)
1936 (match-end 0)))
1937 (length string)))
1938 (string-to-number string)))
1940 (defun org-babel-import-elisp-from-file (file-name &optional separator)
1941 "Read the results located at FILE-NAME into an elisp table.
1942 If the table is trivial, then return it as a scalar."
1943 (let (result)
1944 (save-window-excursion
1945 (with-temp-buffer
1946 (condition-case nil
1947 (progn
1948 (org-table-import file-name separator)
1949 (delete-file file-name)
1950 (setq result (mapcar (lambda (row)
1951 (mapcar #'org-babel-string-read row))
1952 (org-table-to-lisp))))
1953 (error nil)))
1954 (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
1955 (if (consp (car result))
1956 (if (null (cdr (car result)))
1957 (caar result)
1958 result)
1959 (car result))
1960 result))))
1962 (defun org-babel-string-read (cell)
1963 "Strip nested \"s from around strings."
1964 (org-babel-read (or (and (stringp cell)
1965 (string-match "\\\"\\(.+\\)\\\"" cell)
1966 (match-string 1 cell))
1967 cell)))
1969 (defun org-babel-reverse-string (string)
1970 "Return the reverse of STRING."
1971 (apply 'string (reverse (string-to-list string))))
1973 (defun org-babel-chomp (string &optional regexp)
1974 "Strip trailing spaces and carriage returns from STRING.
1975 Default regexp used is \"[ \f\t\n\r\v]\" but can be
1976 overwritten by specifying a regexp as a second argument."
1977 (let ((regexp (or regexp "[ \f\t\n\r\v]")))
1978 (while (and (> (length string) 0)
1979 (string-match regexp (substring string -1)))
1980 (setq string (substring string 0 -1)))
1981 string))
1983 (defun org-babel-trim (string &optional regexp)
1984 "Strip leading and trailing spaces and carriage returns from STRING.
1985 Like `org-babel-chomp' only it runs on both the front and back
1986 of the string."
1987 (org-babel-chomp (org-babel-reverse-string
1988 (org-babel-chomp (org-babel-reverse-string string) regexp))
1989 regexp))
1991 (defvar org-babel-org-babel-call-process-region-original nil)
1992 (defun org-babel-tramp-handle-call-process-region
1993 (start end program &optional delete buffer display &rest args)
1994 "Use tramp to handle call-process-region.
1995 Fixes a bug in `tramp-handle-call-process-region'."
1996 (if (and (featurep 'tramp) (file-remote-p default-directory))
1997 (let ((tmpfile (tramp-compat-make-temp-file "")))
1998 (write-region start end tmpfile)
1999 (when delete (delete-region start end))
2000 (unwind-protect
2001 ;; (apply 'call-process program tmpfile buffer display args)
2002 ;; bug in tramp
2003 (apply 'process-file program tmpfile buffer display args)
2004 (delete-file tmpfile)))
2005 ;; org-babel-call-process-region-original is the original emacs
2006 ;; definition. It is in scope from the let binding in
2007 ;; org-babel-execute-src-block
2008 (apply org-babel-call-process-region-original
2009 start end program delete buffer display args)))
2011 (defun org-babel-local-file-name (file)
2012 "Return the local name component of FILE."
2013 (if (file-remote-p file)
2014 (let (localname)
2015 (with-parsed-tramp-file-name file nil
2016 localname))
2017 file))
2019 (defun org-babel-process-file-name (name &optional no-quote-p)
2020 "Prepare NAME to be used in an external process.
2021 If NAME specifies a remote location, the remote portion of the
2022 name is removed, since in that case the process will be executing
2023 remotely. The file name is then processed by
2024 `expand-file-name'. Unless second argument NO-QUOTE-P is non-nil,
2025 the file name is additionally processed by
2026 `shell-quote-argument'"
2027 ((lambda (f) (if no-quote-p f (shell-quote-argument f)))
2028 (expand-file-name (org-babel-local-file-name name))))
2030 (defvar org-babel-temporary-directory)
2031 (unless (or noninteractive (boundp 'org-babel-temporary-directory))
2032 (defvar org-babel-temporary-directory
2033 (or (and (boundp 'org-babel-temporary-directory)
2034 (file-exists-p org-babel-temporary-directory)
2035 org-babel-temporary-directory)
2036 (make-temp-file "babel-" t))
2037 "Directory to hold temporary files created to execute code blocks.
2038 Used by `org-babel-temp-file'. This directory will be removed on
2039 Emacs shutdown."))
2041 (defun org-babel-temp-file (prefix &optional suffix)
2042 "Create a temporary file in the `org-babel-temporary-directory'.
2043 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2044 value of `temporary-file-directory' temporarily set to the value
2045 of `org-babel-temporary-directory'."
2046 (if (file-remote-p default-directory)
2047 (make-temp-file
2048 (concat (file-remote-p default-directory)
2049 (expand-file-name
2050 prefix temporary-file-directory)
2051 nil suffix))
2052 (let ((temporary-file-directory
2053 (or (and (boundp 'org-babel-temporary-directory)
2054 (file-exists-p org-babel-temporary-directory)
2055 org-babel-temporary-directory)
2056 temporary-file-directory)))
2057 (make-temp-file prefix nil suffix))))
2059 (defun org-babel-remove-temporary-directory ()
2060 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2061 (when (and (boundp 'org-babel-temporary-directory)
2062 (file-exists-p org-babel-temporary-directory))
2063 ;; taken from `delete-directory' in files.el
2064 (condition-case nil
2065 (progn
2066 (mapc (lambda (file)
2067 ;; This test is equivalent to
2068 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2069 ;; but more efficient
2070 (if (eq t (car (file-attributes file)))
2071 (delete-directory file)
2072 (delete-file file)))
2073 ;; We do not want to delete "." and "..".
2074 (directory-files org-babel-temporary-directory 'full
2075 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2076 (delete-directory org-babel-temporary-directory))
2077 (error
2078 (message "Failed to remove temporary Org-babel directory %s"
2079 (if (boundp 'org-babel-temporary-directory)
2080 org-babel-temporary-directory
2081 "[directory not defined]"))))))
2083 (add-hook 'kill-emacs-hook 'org-babel-remove-temporary-directory)
2085 (provide 'ob)
2087 ;; arch-tag: 01a7ebee-06c5-4ee4-a709-e660d28c0af1
2089 ;;; ob.el ends here