Keep byte compiler happy
[org-mode.git] / lisp / ob.el
blob6b4a766b4846bc2a1c2fba63a117dedd64bbf2bc
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 shebang padline)
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 (:padnewline . "yes"))
303 "Default arguments to use when evaluating a source block.")
305 (defvar org-babel-default-inline-header-args
306 '((:session . "none") (:results . "replace") (:exports . "results"))
307 "Default arguments to use when evaluating an inline source block.")
309 (defvar org-babel-current-buffer-properties nil
310 "Local cache for buffer properties.")
311 (make-variable-buffer-local 'org-babel-current-buffer-properties)
313 (defvar org-babel-result-regexp
314 "^[ \t]*#\\+res\\(ults\\|name\\)\\(\\[\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*"
315 "Regular expression used to match result lines.
316 If the results are associated with a hash key then the hash will
317 be saved in the second match data.")
319 (defvar org-babel-result-w-name-regexp
320 (concat org-babel-result-regexp
321 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
323 (defvar org-babel-min-lines-for-block-output 10
324 "The minimum number of lines for block output.
325 If number of lines of output is equal to or exceeds this
326 value, the output is placed in a #+begin_example...#+end_example
327 block. Otherwise the output is marked as literal by inserting
328 colons at the starts of the lines. This variable only takes
329 effect if the :results output option is in effect.")
331 (defvar org-babel-noweb-error-langs nil
332 "Languages for which Babel will raise literate programming errors.
333 List of languages for which errors should be raised when the
334 source code block satisfying a noweb reference in this language
335 can not be resolved.")
337 (defvar org-babel-hash-show 4
338 "Number of initial characters to show of a hidden results hash.")
340 (defvar org-babel-after-execute-hook nil
341 "Hook for functions to be called after `org-babel-execute-src-block'")
342 (defun org-babel-named-src-block-regexp-for-name (name)
343 "This generates a regexp used to match a src block named NAME."
344 (concat org-babel-src-name-regexp (regexp-quote name) "[ \t\n]*"
345 (substring org-babel-src-block-regexp 1)))
347 ;;; functions
348 (defvar call-process-region)
349 ;;;###autoload
351 (defun org-babel-execute-src-block (&optional arg info params)
352 "Execute the current source code block.
353 Insert the results of execution into the buffer. Source code
354 execution and the collection and formatting of results can be
355 controlled through a variety of header arguments.
357 With prefix argument ARG, force re-execution even if a an
358 existing result cached in the buffer would otherwise have been
359 returned.
361 Optionally supply a value for INFO in the form returned by
362 `org-babel-get-src-block-info'.
364 Optionally supply a value for PARAMS which will be merged with
365 the header arguments specified at the front of the source code
366 block."
367 (interactive)
368 (let ((info (or info (org-babel-get-src-block-info))))
369 (when (org-babel-confirm-evaluate info)
370 (let* ((lang (nth 0 info))
371 (params (if params
372 (org-babel-process-params
373 (org-babel-merge-params (nth 2 info) params))
374 (nth 2 info)))
375 (cache? (and (not arg) (cdr (assoc :cache params))
376 (string= "yes" (cdr (assoc :cache params)))))
377 (result-params (cdr (assoc :result-params params)))
378 (new-hash (when cache? (org-babel-sha1-hash info)))
379 (old-hash (when cache? (org-babel-result-hash info)))
380 (body (setf (nth 1 info)
381 (let ((noweb (cdr (assoc :noweb params))))
382 (if (and noweb
383 (or (string= "yes" noweb)
384 (string= "tangle" noweb)))
385 (org-babel-expand-noweb-references info)
386 (nth 1 info)))))
387 (dir (cdr (assoc :dir params)))
388 (default-directory
389 (or (and dir (file-name-as-directory dir)) default-directory))
390 (org-babel-call-process-region-original
391 (if (boundp 'org-babel-call-process-region-original)
392 org-babel-call-process-region-original
393 (symbol-function 'call-process-region)))
394 (indent (car (last info)))
395 result cmd)
396 (unwind-protect
397 (flet ((call-process-region (&rest args)
398 (apply 'org-babel-tramp-handle-call-process-region args)))
399 (flet ((lang-check (f)
400 (let ((f (intern (concat "org-babel-execute:" f))))
401 (when (fboundp f) f))))
402 (setq cmd
403 (or (lang-check lang)
404 (lang-check (symbol-name
405 (cdr (assoc lang org-src-lang-modes))))
406 (error "No org-babel-execute function for %s!" lang))))
407 (if (and (not arg) new-hash (equal new-hash old-hash))
408 (save-excursion ;; return cached result
409 (goto-char (org-babel-where-is-src-block-result nil info))
410 (end-of-line 1) (forward-char 1)
411 (setq result (org-babel-read-result))
412 (message (replace-regexp-in-string
413 "%" "%%" (format "%S" result))) result)
414 (message "executing %s code block%s..."
415 (capitalize lang)
416 (if (nth 4 info) (format " (%s)" (nth 4 info)) ""))
417 (setq result
418 ((lambda (result)
419 (if (and (eq (cdr (assoc :result-type params)) 'value)
420 (or (member "vector" result-params)
421 (member "table" result-params))
422 (not (listp result)))
423 (list (list result)) result))
424 (funcall cmd body params)))
425 ;; if non-empty result and :file then write to :file
426 (when (cdr (assoc :file params))
427 (when result
428 (with-temp-file (cdr (assoc :file params))
429 (insert
430 (org-babel-format-result
431 result (cdr (assoc :sep (nth 2 info)))))))
432 (setq result (cdr (assoc :file params))))
433 (org-babel-insert-result
434 result result-params info new-hash indent lang)
435 (run-hooks 'org-babel-after-execute-hook)
436 result))
437 (setq call-process-region 'org-babel-call-process-region-original))))))
439 (defun org-babel-expand-body:generic (body params &optional var-lines)
440 "Expand BODY with PARAMS.
441 Expand a block of code with org-babel according to it's header
442 arguments. This generic implementation of body expansion is
443 called for languages which have not defined their own specific
444 org-babel-expand-body:lang function."
445 (mapconcat #'identity (append var-lines (list body)) "\n"))
447 ;;;###autoload
448 (defun org-babel-expand-src-block (&optional arg info params)
449 "Expand the current source code block.
450 Expand according to the source code block's header
451 arguments and pop open the results in a preview buffer."
452 (interactive)
453 (let* ((info (or info (org-babel-get-src-block-info)))
454 (lang (nth 0 info))
455 (params (setf (nth 2 info)
456 (sort (org-babel-merge-params (nth 2 info) params)
457 (lambda (el1 el2) (string< (symbol-name (car el1))
458 (symbol-name (car el2)))))))
459 (body (setf (nth 1 info)
460 (if (and (cdr (assoc :noweb params))
461 (string= "yes" (cdr (assoc :noweb params))))
462 (org-babel-expand-noweb-references info) (nth 1 info))))
463 (expand-cmd (intern (concat "org-babel-expand-body:" lang)))
464 (assignments-cmd (intern (concat "org-babel-variable-assignments:" lang)))
465 (expanded
466 (if (fboundp expand-cmd) (funcall expand-cmd body params)
467 (org-babel-expand-body:generic
468 body params (and (fboundp assignments-cmd) (funcall assignments-cmd params))))))
469 (org-edit-src-code
470 nil expanded (concat "*Org-Babel Preview " (buffer-name) "[ " lang " ]*"))))
472 ;;;###autoload
473 (defun org-babel-load-in-session (&optional arg info)
474 "Load the body of the current source-code block.
475 Evaluate the header arguments for the source block before
476 entering the session. After loading the body this pops open the
477 session."
478 (interactive)
479 (let* ((info (or info (org-babel-get-src-block-info)))
480 (lang (nth 0 info))
481 (params (nth 2 info))
482 (body (setf (nth 1 info)
483 (if (and (cdr (assoc :noweb params))
484 (string= "yes" (cdr (assoc :noweb params))))
485 (org-babel-expand-noweb-references info)
486 (nth 1 info))))
487 (session (cdr (assoc :session params)))
488 (dir (cdr (assoc :dir params)))
489 (default-directory
490 (or (and dir (file-name-as-directory dir)) default-directory))
491 (cmd (intern (concat "org-babel-load-session:" lang))))
492 (unless (fboundp cmd)
493 (error "No org-babel-load-session function for %s!" lang))
494 (pop-to-buffer (funcall cmd session body params))
495 (end-of-line 1)))
497 ;;;###autoload
498 (defun org-babel-initiate-session (&optional arg info)
499 "Initiate session for current code block.
500 If called with a prefix argument then resolve any variable
501 references in the header arguments and assign these variables in
502 the session. Copy the body of the code block to the kill ring."
503 (interactive "P")
504 (let* ((info (or info (org-babel-get-src-block-info (not arg))))
505 (lang (nth 0 info))
506 (body (nth 1 info))
507 (params (nth 2 info))
508 (session (cdr (assoc :session params)))
509 (dir (cdr (assoc :dir params)))
510 (default-directory
511 (or (and dir (file-name-as-directory dir)) default-directory))
512 (init-cmd (intern (format "org-babel-%s-initiate-session" lang)))
513 (prep-cmd (intern (concat "org-babel-prep-session:" lang))))
514 (if (and (stringp session) (string= session "none"))
515 (error "This block is not using a session!"))
516 (unless (fboundp init-cmd)
517 (error "No org-babel-initiate-session function for %s!" lang))
518 (with-temp-buffer (insert (org-babel-trim body))
519 (copy-region-as-kill (point-min) (point-max)))
520 (when arg
521 (unless (fboundp prep-cmd)
522 (error "No org-babel-prep-session function for %s!" lang))
523 (funcall prep-cmd session params))
524 (funcall init-cmd session params)))
526 ;;;###autoload
527 (defun org-babel-switch-to-session (&optional arg info)
528 "Switch to the session of the current code block.
529 Uses `org-babel-initiate-session' to start the session. If called
530 with a prefix argument then this is passed on to
531 `org-babel-initiate-session'."
532 (interactive "P")
533 (pop-to-buffer (org-babel-initiate-session arg info))
534 (end-of-line 1))
536 (defalias 'org-babel-pop-to-session 'org-babel-switch-to-session)
538 ;;;###autoload
539 (defun org-babel-switch-to-session-with-code (&optional arg info)
540 "Switch to code buffer and display session."
541 (interactive "P")
542 (flet ((swap-windows
544 (let ((other-window-buffer (window-buffer (next-window))))
545 (set-window-buffer (next-window) (current-buffer))
546 (set-window-buffer (selected-window) other-window-buffer))
547 (other-window 1)))
548 (let ((info (org-babel-get-src-block-info))
549 (org-src-window-setup 'reorganize-frame))
550 (save-excursion
551 (org-babel-switch-to-session arg info))
552 (org-edit-src-code))
553 (swap-windows)))
555 (defmacro org-babel-do-in-edit-buffer (&rest body)
556 "Evaluate BODY in edit buffer if there is a code block at point.
557 Return t if a code block was found at point, nil otherwise."
558 `(let ((org-src-window-setup 'switch-invisibly))
559 (when (and (org-babel-where-is-src-block-head)
560 (org-edit-src-code nil nil nil))
561 (unwind-protect (progn ,@body)
562 (if (org-bound-and-true-p org-edit-src-from-org-mode)
563 (org-edit-src-exit)))
564 t)))
566 (defun org-babel-do-key-sequence-in-edit-buffer (key)
567 "Read key sequence and execute the command in edit buffer.
568 Enter a key sequence to be executed in the language major-mode
569 edit buffer. For example, TAB will alter the contents of the
570 Org-mode code block according to the effect of TAB in the
571 language major-mode buffer. For languages that support
572 interactive sessions, this can be used to send code from the Org
573 buffer to the session for evaluation using the native major-mode
574 evaluation mechanisms."
575 (interactive "kEnter key-sequence to execute in edit buffer: ")
576 (org-babel-do-in-edit-buffer
577 (call-interactively
578 (key-binding (or key (read-key-sequence nil))))))
580 (defvar org-bracket-link-regexp)
581 ;;;###autoload
582 (defun org-babel-open-src-block-result (&optional re-run)
583 "If `point' is on a src block then open the results of the
584 source code block, otherwise return nil. With optional prefix
585 argument RE-RUN the source-code block is evaluated even if
586 results already exist."
587 (interactive "P")
588 (let ((info (org-babel-get-src-block-info)))
589 (when info
590 (save-excursion
591 ;; go to the results, if there aren't any then run the block
592 (goto-char (or (and (not re-run) (org-babel-where-is-src-block-result))
593 (progn (org-babel-execute-src-block)
594 (org-babel-where-is-src-block-result))))
595 (end-of-line 1)
596 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
597 ;; open the results
598 (if (looking-at org-bracket-link-regexp)
599 ;; file results
600 (org-open-at-point)
601 (let ((r (org-babel-format-result
602 (org-babel-read-result) (cdr (assoc :sep (nth 2 info))))))
603 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
604 (delete-region (point-min) (point-max))
605 (insert r)))
606 t))))
608 ;;;###autoload
609 (defmacro org-babel-map-src-blocks (file &rest body)
610 "Evaluate BODY forms on each source-block in FILE.
611 If FILE is nil evaluate BODY forms on source blocks in current
612 buffer. During evaluation of BODY the following local variables
613 are set relative to the currently matched code block.
615 full-block ------- string holding the entirety of the code block
616 beg-block -------- point at the beginning of the code block
617 end-block -------- point at the end of the matched code block
618 lang ------------- string holding the language of the code block
619 beg-lang --------- point at the beginning of the lang
620 end-lang --------- point at the end of the lang
621 switches --------- string holding the switches
622 beg-switches ----- point at the beginning of the switches
623 end-switches ----- point at the end of the switches
624 header-args ------ string holding the header-args
625 beg-header-args -- point at the beginning of the header-args
626 end-header-args -- point at the end of the header-args
627 body ------------- string holding the body of the code block
628 beg-body --------- point at the beginning of the body
629 end-body --------- point at the end of the body"
630 (declare (indent 1))
631 (let ((tempvar (make-symbol "file")))
632 `(let* ((,tempvar ,file)
633 (visited-p (or (null ,tempvar)
634 (get-file-buffer (expand-file-name ,tempvar))))
635 (point (point)) to-be-removed)
636 (save-window-excursion
637 (when ,tempvar (find-file ,tempvar))
638 (setq to-be-removed (current-buffer))
639 (goto-char (point-min))
640 (while (re-search-forward org-babel-src-block-regexp nil t)
641 (goto-char (match-beginning 0))
642 (let ((full-block (match-string 0))
643 (beg-block (match-beginning 0))
644 (end-block (match-end 0))
645 (lang (match-string 2))
646 (beg-lang (match-beginning 2))
647 (end-lang (match-end 2))
648 (switches (match-string 3))
649 (beg-switches (match-beginning 3))
650 (end-switches (match-end 3))
651 (header-args (match-string 4))
652 (beg-header-args (match-beginning 4))
653 (end-header-args (match-end 4))
654 (body (match-string 5))
655 (beg-body (match-beginning 5))
656 (end-body (match-end 5)))
657 ,@body
658 (goto-char end-block))))
659 (unless visited-p (kill-buffer to-be-removed))
660 (goto-char point))))
662 ;;;###autoload
663 (defmacro org-babel-map-inline-src-blocks (file &rest body)
664 "Evaluate BODY forms on each inline source-block in FILE.
665 If FILE is nil evaluate BODY forms on source blocks in current
666 buffer."
667 (declare (indent 1))
668 (let ((tempvar (make-symbol "file")))
669 `(let* ((,tempvar ,file)
670 (visited-p (or (null ,tempvar)
671 (get-file-buffer (expand-file-name ,tempvar))))
672 (point (point)) to-be-removed)
673 (save-window-excursion
674 (when ,tempvar (find-file ,tempvar))
675 (setq to-be-removed (current-buffer))
676 (goto-char (point-min))
677 (while (re-search-forward org-babel-inline-src-block-regexp nil t)
678 (goto-char (match-beginning 1))
679 (save-match-data ,@body)
680 (goto-char (match-end 0))))
681 (unless visited-p (kill-buffer to-be-removed))
682 (goto-char point))))
684 ;;;###autoload
685 (defun org-babel-execute-buffer (&optional arg)
686 "Execute source code blocks in a buffer.
687 Call `org-babel-execute-src-block' on every source block in
688 the current buffer."
689 (interactive "P")
690 (org-babel-eval-wipe-error-buffer)
691 (org-save-outline-visibility t
692 (org-babel-map-src-blocks nil
693 (org-babel-execute-src-block arg))
694 (org-babel-map-inline-src-blocks nil
695 (org-babel-execute-src-block arg))))
697 ;;;###autoload
698 (defun org-babel-execute-subtree (&optional arg)
699 "Execute source code blocks in a subtree.
700 Call `org-babel-execute-src-block' on every source block in
701 the current subtree."
702 (interactive "P")
703 (save-restriction
704 (save-excursion
705 (org-narrow-to-subtree)
706 (org-babel-execute-buffer arg)
707 (widen))))
709 ;;;###autoload
710 (defun org-babel-sha1-hash (&optional info)
711 "Generate an sha1 hash based on the value of info."
712 (interactive)
713 (let ((print-level nil)
714 (info (or info (org-babel-get-src-block-info))))
715 (setf (nth 2 info)
716 (sort (copy-sequence (nth 2 info))
717 (lambda (a b) (string< (car a) (car b)))))
718 ((lambda (hash) (when (interactive-p) (message hash)) hash)
719 (sha1 (format "%s-%s"
720 (mapconcat
721 #'identity
722 (delq nil
723 (mapcar
724 (lambda (arg)
725 (let ((v (cdr arg)))
726 (when (and v (not (and (sequencep v)
727 (not (consp v))
728 (= (length v) 0))))
729 ((lambda (el) (format "%S" el))
730 (cond
731 ((and (listp v) ; lists are sorted
732 (member (car arg) '(:result-params)))
733 (sort v #'string<))
734 ((and (stringp v) ; strings are sorted
735 (member (car arg) '(:results :exports)))
736 (mapconcat #'identity (sort (split-string v)
737 #'string<) " "))
738 (t v)))))) ; atomic are left untouched
739 (nth 2 info))) ":")
740 (nth 1 info))))))
742 (defun org-babel-result-hash (&optional info)
743 "Return the in-buffer hash associated with INFO."
744 (org-babel-where-is-src-block-result nil info)
745 (org-babel-clean-text-properties (match-string 3)))
747 (defun org-babel-hide-hash ()
748 "Hide the hash in the current results line.
749 Only the initial `org-babel-hash-show' characters of the hash
750 will remain visible."
751 (add-to-invisibility-spec '(org-babel-hide-hash . t))
752 (save-excursion
753 (when (and (re-search-forward org-babel-result-regexp nil t)
754 (match-string 3))
755 (let* ((start (match-beginning 3))
756 (hide-start (+ org-babel-hash-show start))
757 (end (match-end 3))
758 (hash (match-string 3))
759 ov1 ov2)
760 (setq ov1 (make-overlay start hide-start))
761 (setq ov2 (make-overlay hide-start end))
762 (overlay-put ov2 'invisible 'org-babel-hide-hash)
763 (overlay-put ov1 'babel-hash hash)))))
765 (defun org-babel-hide-all-hashes ()
766 "Hide the hash in the current buffer.
767 Only the initial `org-babel-hash-show' characters of each hash
768 will remain visible. This function should be called as part of
769 the `org-mode-hook'."
770 (save-excursion
771 (while (re-search-forward org-babel-result-regexp nil t)
772 (goto-char (match-beginning 0))
773 (org-babel-hide-hash)
774 (goto-char (match-end 0)))))
775 (add-hook 'org-mode-hook 'org-babel-hide-all-hashes)
777 (defun org-babel-hash-at-point (&optional point)
778 "Return the value of the hash at POINT.
779 The hash is also added as the last element of the kill ring.
780 This can be called with C-c C-c."
781 (interactive)
782 (let ((hash (car (delq nil (mapcar
783 (lambda (ol) (overlay-get ol 'babel-hash))
784 (overlays-at (or point (point))))))))
785 (when hash (kill-new hash) (message hash))))
786 (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-hash-at-point)
788 (defun org-babel-result-hide-spec ()
789 "Hide portions of results lines.
790 Add `org-babel-hide-result' as an invisibility spec for hiding
791 portions of results lines."
792 (add-to-invisibility-spec '(org-babel-hide-result . t)))
793 (add-hook 'org-mode-hook 'org-babel-result-hide-spec)
795 (defvar org-babel-hide-result-overlays nil
796 "Overlays hiding results.")
798 (defun org-babel-result-hide-all ()
799 "Fold all results in the current buffer."
800 (interactive)
801 (org-babel-show-result-all)
802 (save-excursion
803 (while (re-search-forward org-babel-result-regexp nil t)
804 (save-excursion (goto-char (match-beginning 0))
805 (org-babel-hide-result-toggle-maybe)))))
807 (defun org-babel-show-result-all ()
808 "Unfold all results in the current buffer."
809 (mapc 'delete-overlay org-babel-hide-result-overlays)
810 (setq org-babel-hide-result-overlays nil))
812 ;;;###autoload
813 (defun org-babel-hide-result-toggle-maybe ()
814 "Toggle visibility of result at point."
815 (interactive)
816 (let ((case-fold-search t))
817 (if (save-excursion
818 (beginning-of-line 1)
819 (looking-at org-babel-result-regexp))
820 (progn (org-babel-hide-result-toggle)
821 t) ;; to signal that we took action
822 nil))) ;; to signal that we did not
824 (defun org-babel-hide-result-toggle (&optional force)
825 "Toggle the visibility of the current result."
826 (interactive)
827 (save-excursion
828 (beginning-of-line)
829 (if (re-search-forward org-babel-result-regexp nil t)
830 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
831 (end (progn (goto-char (- (org-babel-result-end) 1)) (point)))
833 (if (memq t (mapcar (lambda (overlay)
834 (eq (overlay-get overlay 'invisible)
835 'org-babel-hide-result))
836 (overlays-at start)))
837 (if (or (not force) (eq force 'off))
838 (mapc (lambda (ov)
839 (when (member ov org-babel-hide-result-overlays)
840 (setq org-babel-hide-result-overlays
841 (delq ov org-babel-hide-result-overlays)))
842 (when (eq (overlay-get ov 'invisible)
843 'org-babel-hide-result)
844 (delete-overlay ov)))
845 (overlays-at start)))
846 (setq ov (make-overlay start end))
847 (overlay-put ov 'invisible 'org-babel-hide-result)
848 ;; make the block accessible to isearch
849 (overlay-put
850 ov 'isearch-open-invisible
851 (lambda (ov)
852 (when (member ov org-babel-hide-result-overlays)
853 (setq org-babel-hide-result-overlays
854 (delq ov org-babel-hide-result-overlays)))
855 (when (eq (overlay-get ov 'invisible)
856 'org-babel-hide-result)
857 (delete-overlay ov))))
858 (push ov org-babel-hide-result-overlays)))
859 (error "Not looking at a result line"))))
861 ;; org-tab-after-check-for-cycling-hook
862 (add-hook 'org-tab-first-hook 'org-babel-hide-result-toggle-maybe)
863 ;; Remove overlays when changing major mode
864 (add-hook 'org-mode-hook
865 (lambda () (org-add-hook 'change-major-mode-hook
866 'org-babel-show-result-all 'append 'local)))
868 (defvar org-file-properties)
869 (defun org-babel-params-from-properties (&optional lang)
870 "Retrieve parameters specified as properties.
871 Return an association list of any source block params which
872 may be specified in the properties of the current outline entry."
873 (save-match-data
874 (let (val sym)
875 (delq nil
876 (mapcar
877 (lambda (header-arg)
878 (and (setq val
879 (or (org-entry-get (point) header-arg t)
880 (org-entry-get (point) (concat ":" header-arg) t)))
881 (cons (intern (concat ":" header-arg))
882 (org-babel-read val))))
883 (mapcar
884 'symbol-name
885 (append
886 org-babel-header-arg-names
887 (progn
888 (setq sym (intern (concat "org-babel-header-arg-names:" lang)))
889 (and (boundp sym) (eval sym))))))))))
891 (defun org-babel-params-from-buffer ()
892 "Retrieve per-buffer parameters.
893 Return an association list of any source block params which
894 may be specified in the current buffer."
895 (or org-babel-current-buffer-properties
896 (save-match-data
897 (save-excursion
898 (save-restriction
899 (widen)
900 (goto-char (point-min))
901 (while (re-search-forward
902 (org-make-options-regexp (list "BABEL")) nil t)
903 (setq org-babel-current-buffer-properties
904 (org-babel-merge-params
905 org-babel-current-buffer-properties
906 (org-babel-parse-header-arguments
907 (org-match-string-no-properties 2)))))
908 org-babel-current-buffer-properties)))))
910 (defvar org-src-preserve-indentation)
911 (defun org-babel-parse-src-block-match ()
912 "Parse the results from a match of the `org-babel-src-block-regexp'."
913 (let* ((block-indentation (length (match-string 1)))
914 (lang (org-babel-clean-text-properties (match-string 2)))
915 (lang-headers (intern (concat "org-babel-default-header-args:" lang)))
916 (switches (match-string 3))
917 (body (org-babel-clean-text-properties (match-string 5)))
918 (preserve-indentation (or org-src-preserve-indentation
919 (string-match "-i\\>" switches))))
920 (list lang
921 ;; get block body less properties, protective commas, and indentation
922 (with-temp-buffer
923 (save-match-data
924 (insert (org-babel-strip-protective-commas body))
925 (unless preserve-indentation (org-do-remove-indentation))
926 (buffer-string)))
927 (org-babel-merge-params
928 org-babel-default-header-args
929 (org-babel-params-from-buffer)
930 (org-babel-params-from-properties lang)
931 (if (boundp lang-headers) (eval lang-headers) nil)
932 (org-babel-parse-header-arguments
933 (org-babel-clean-text-properties (or (match-string 4) ""))))
934 switches
935 block-indentation)))
937 (defun org-babel-parse-inline-src-block-match ()
938 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
939 (let* ((lang (org-babel-clean-text-properties (match-string 2)))
940 (lang-headers (intern (concat "org-babel-default-header-args:" lang))))
941 (list lang
942 (org-babel-strip-protective-commas
943 (org-babel-clean-text-properties (match-string 5)))
944 (org-babel-merge-params
945 org-babel-default-inline-header-args
946 (org-babel-params-from-buffer)
947 (org-babel-params-from-properties lang)
948 (if (boundp lang-headers) (eval lang-headers) nil)
949 (org-babel-parse-header-arguments
950 (org-babel-clean-text-properties (or (match-string 4) "")))))))
952 (defun org-babel-parse-header-arguments (arg-string)
953 "Parse a string of header arguments returning an alist."
954 (when (> (length arg-string) 0)
955 (delq nil
956 (mapcar
957 (lambda (arg)
958 (if (string-match
959 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
960 arg)
961 (cons (intern (match-string 1 arg))
962 (org-babel-read (org-babel-chomp (match-string 2 arg))))
963 (cons (intern (org-babel-chomp arg)) nil)))
964 (let ((balance 0) (partial nil) (lst nil) (last 0))
965 (mapc (lambda (ch) ; split on [] balanced instances of [ \t]:
966 (setq balance (+ balance
967 (cond ((equal 91 ch) 1)
968 ((equal 93 ch) -1)
969 (t 0))))
970 (setq partial (cons ch partial))
971 (when (and (= ch 58) (= balance 0)
972 (or (= last 32) (= last 9)))
973 (setq lst (cons (apply #'string (nreverse (cddr partial)))
974 lst))
975 (setq partial (list ch)))
976 (setq last ch))
977 (string-to-list arg-string))
978 (nreverse (cons (apply #'string (nreverse partial)) lst)))))))
980 (defun org-babel-process-params (params)
981 "Expand variables in PARAMS and add summary parameters."
982 (let* ((vars-and-names (org-babel-disassemble-tables
983 (mapcar (lambda (el)
984 (if (consp (cdr el))
985 (cdr el) (org-babel-ref-parse (cdr el))))
986 (org-babel-get-header params :var))
987 (cdr (assoc :hlines params))
988 (cdr (assoc :colnames params))
989 (cdr (assoc :rownames params))))
990 (raw-result (or (cdr (assoc :results params)) ""))
991 (result-params (append
992 (split-string (if (stringp raw-result)
993 raw-result
994 (eval raw-result)))
995 (cdr (assoc :result-params params)))))
996 (append
997 (mapcar (lambda (var) (cons :var var)) (car vars-and-names))
998 (list
999 (cons :colname-names (cadr vars-and-names))
1000 (cons :rowname-names (caddr vars-and-names))
1001 (cons :result-params result-params)
1002 (cons :result-type (cond ((member "output" result-params) 'output)
1003 ((member "value" result-params) 'value)
1004 (t 'value))))
1005 (org-babel-get-header params :var 'other))))
1007 ;; row and column names
1008 (defun org-babel-del-hlines (table)
1009 "Remove all 'hlines from TABLE."
1010 (remove 'hline table))
1012 (defun org-babel-get-colnames (table)
1013 "Return the column names of TABLE.
1014 Return a cons cell, the `car' of which contains the TABLE less
1015 colnames, and the `cdr' of which contains a list of the column
1016 names."
1017 (if (equal 'hline (nth 1 table))
1018 (cons (cddr table) (car table))
1019 (cons (cdr table) (car table))))
1021 (defun org-babel-get-rownames (table)
1022 "Return the row names of TABLE.
1023 Return a cons cell, the `car' of which contains the TABLE less
1024 colnames, and the `cdr' of which contains a list of the column
1025 names. Note: this function removes any hlines in TABLE."
1026 (flet ((trans (table) (apply #'mapcar* #'list table)))
1027 (let* ((width (apply 'max
1028 (mapcar (lambda (el) (if (listp el) (length el) 0)) table)))
1029 (table (trans (mapcar (lambda (row)
1030 (if (not (equal row 'hline))
1032 (setq row '())
1033 (dotimes (n width)
1034 (setq row (cons 'hline row)))
1035 row))
1036 table))))
1037 (cons (mapcar (lambda (row) (if (equal (car row) 'hline) 'hline row))
1038 (trans (cdr table)))
1039 (remove 'hline (car table))))))
1041 (defun org-babel-put-colnames (table colnames)
1042 "Add COLNAMES to TABLE if they exist."
1043 (if colnames (apply 'list colnames 'hline table) table))
1045 (defun org-babel-put-rownames (table rownames)
1046 "Add ROWNAMES to TABLE if they exist."
1047 (if rownames
1048 (mapcar (lambda (row)
1049 (if (listp row)
1050 (cons (or (pop rownames) "") row)
1051 row)) table)
1052 table))
1054 (defun org-babel-pick-name (names selector)
1055 "Select one out of an alist of row or column names.
1056 SELECTOR can be either a list of names in which case those names
1057 will be returned directly, or an index into the list NAMES in
1058 which case the indexed names will be return."
1059 (if (listp selector)
1060 selector
1061 (when names
1062 (if (and selector (symbolp selector) (not (equal t selector)))
1063 (cdr (assoc selector names))
1064 (if (integerp selector)
1065 (nth (- selector 1) names)
1066 (cdr (car (last names))))))))
1068 (defun org-babel-disassemble-tables (vars hlines colnames rownames)
1069 "Parse tables for further processing.
1070 Process the variables in VARS according to the HLINES,
1071 ROWNAMES and COLNAMES header arguments. Return a list consisting
1072 of the vars, cnames and rnames."
1073 (let (cnames rnames)
1074 (list
1075 (mapcar
1076 (lambda (var)
1077 (when (listp (cdr var))
1078 (when (and (not (equal colnames "no"))
1079 (or colnames (and (equal (nth 1 (cdr var)) 'hline)
1080 (not (member 'hline (cddr (cdr var)))))))
1081 (let ((both (org-babel-get-colnames (cdr var))))
1082 (setq cnames (cons (cons (car var) (cdr both))
1083 cnames))
1084 (setq var (cons (car var) (car both)))))
1085 (when (and rownames (not (equal rownames "no")))
1086 (let ((both (org-babel-get-rownames (cdr var))))
1087 (setq rnames (cons (cons (car var) (cdr both))
1088 rnames))
1089 (setq var (cons (car var) (car both)))))
1090 (when (and hlines (not (equal hlines "yes")))
1091 (setq var (cons (car var) (org-babel-del-hlines (cdr var))))))
1092 var)
1093 vars)
1094 cnames rnames)))
1096 (defun org-babel-reassemble-table (table colnames rownames)
1097 "Add column and row names to a table.
1098 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1099 to the table for reinsertion to org-mode."
1100 (if (listp table)
1101 ((lambda (table)
1102 (if (and colnames (listp (car table)) (= (length (car table))
1103 (length colnames)))
1104 (org-babel-put-colnames table colnames) table))
1105 (if (and rownames (= (length table) (length rownames)))
1106 (org-babel-put-rownames table rownames) table))
1107 table))
1109 (defun org-babel-where-is-src-block-head ()
1110 "Find where the current source block begins.
1111 Return the point at the beginning of the current source
1112 block. Specifically at the beginning of the #+BEGIN_SRC line.
1113 If the point is not on a source block then return nil."
1114 (let ((initial (point)) top bottom)
1116 (save-excursion ;; on a source name line or a #+header line
1117 (beginning-of-line 1)
1118 (and (or (looking-at org-babel-src-name-regexp)
1119 (looking-at org-babel-multi-line-header-regexp))
1120 (progn
1121 (while (and (forward-line 1)
1122 (looking-at org-babel-multi-line-header-regexp)))
1123 (looking-at org-babel-src-block-regexp))
1124 (point)))
1125 (save-excursion ;; on a #+begin_src line
1126 (beginning-of-line 1)
1127 (and (looking-at org-babel-src-block-regexp)
1128 (point)))
1129 (save-excursion ;; inside a src block
1130 (and
1131 (re-search-backward "^[ \t]*#\\+begin_src" nil t) (setq top (point))
1132 (re-search-forward "^[ \t]*#\\+end_src" nil t) (setq bottom (point))
1133 (< top initial) (< initial bottom)
1134 (progn (goto-char top) (beginning-of-line 1)
1135 (looking-at org-babel-src-block-regexp))
1136 (point))))))
1138 ;;;###autoload
1139 (defun org-babel-goto-src-block-head ()
1140 "Go to the beginning of the current code block."
1141 (interactive)
1142 ((lambda (head)
1143 (if head (goto-char head) (error "not currently in a code block")))
1144 (org-babel-where-is-src-block-head)))
1146 ;;;###autoload
1147 (defun org-babel-goto-named-src-block (name)
1148 "Go to a named source-code block."
1149 (interactive
1150 (let ((completion-ignore-case t))
1151 (list (org-icompleting-read "source-block name: "
1152 (org-babel-src-block-names) nil t))))
1153 (let ((point (org-babel-find-named-block name)))
1154 (if point
1155 ;; taken from `org-open-at-point'
1156 (progn (goto-char point) (org-show-context))
1157 (message "source-code block '%s' not found in this buffer" name))))
1159 (defun org-babel-find-named-block (name)
1160 "Find a named source-code block.
1161 Return the location of the source block identified by source
1162 NAME, or nil if no such block exists. Set match data according to
1163 org-babel-named-src-block-regexp."
1164 (save-excursion
1165 (let ((case-fold-search t)
1166 (regexp (org-babel-named-src-block-regexp-for-name name)) msg)
1167 (goto-char (point-min))
1168 (when (or (re-search-forward regexp nil t)
1169 (re-search-backward regexp nil t))
1170 (match-beginning 0)))))
1172 (defun org-babel-src-block-names (&optional file)
1173 "Returns the names of source blocks in FILE or the current buffer."
1174 (save-excursion
1175 (when file (find-file file)) (goto-char (point-min))
1176 (let (names)
1177 (while (re-search-forward org-babel-src-name-w-name-regexp nil t)
1178 (setq names (cons (match-string 4) names)))
1179 names)))
1181 ;;;###autoload
1182 (defun org-babel-goto-named-result (name)
1183 "Go to a named result."
1184 (interactive
1185 (let ((completion-ignore-case t))
1186 (list (org-icompleting-read "source-block name: "
1187 (org-babel-result-names) nil t))))
1188 (let ((point (org-babel-find-named-result name)))
1189 (if point
1190 ;; taken from `org-open-at-point'
1191 (progn (goto-char point) (org-show-context))
1192 (message "result '%s' not found in this buffer" name))))
1194 (defun org-babel-find-named-result (name)
1195 "Find a named result.
1196 Return the location of the result named NAME in the current
1197 buffer or nil if no such result exists."
1198 (save-excursion
1199 (goto-char (point-min))
1200 (when (re-search-forward
1201 (concat org-babel-result-regexp
1202 "[ \t]" (regexp-quote name) "[ \t\n\f\v\r]") nil t)
1203 (beginning-of-line 0) (point))))
1205 (defun org-babel-result-names (&optional file)
1206 "Returns the names of results in FILE or the current buffer."
1207 (save-excursion
1208 (when file (find-file file)) (goto-char (point-min))
1209 (let (names)
1210 (while (re-search-forward org-babel-result-w-name-regexp nil t)
1211 (setq names (cons (match-string 4) names)))
1212 names)))
1214 ;;;###autoload
1215 (defun org-babel-next-src-block (&optional arg)
1216 "Jump to the next source block.
1217 With optional prefix argument ARG, jump forward ARG many source blocks."
1218 (interactive "P")
1219 (when (looking-at org-babel-src-block-regexp) (forward-char 1))
1220 (condition-case nil
1221 (re-search-forward org-babel-src-block-regexp nil nil (or arg 1))
1222 (error (error "No further code blocks")))
1223 (goto-char (match-beginning 0)) (org-show-context))
1225 ;;;###autoload
1226 (defun org-babel-previous-src-block (&optional arg)
1227 "Jump to the previous source block.
1228 With optional prefix argument ARG, jump backward ARG many source blocks."
1229 (interactive "P")
1230 (condition-case nil
1231 (re-search-backward org-babel-src-block-regexp nil nil (or arg 1))
1232 (error (error "No previous code blocks")))
1233 (goto-char (match-beginning 0)) (org-show-context))
1235 (defvar org-babel-load-languages)
1237 ;;;###autoload
1238 (defun org-babel-mark-block ()
1239 "Mark current src block"
1240 (interactive)
1241 ((lambda (head)
1242 (when head
1243 (save-excursion
1244 (goto-char head)
1245 (looking-at org-babel-src-block-regexp))
1246 (push-mark (match-end 5) nil t)
1247 (goto-char (match-beginning 5))))
1248 (org-babel-where-is-src-block-head)))
1250 (defun org-babel-demarcate-block (&optional arg)
1251 "Wrap or split the code in the region or on the point.
1252 When called from inside of a code block the current block is
1253 split. When called from outside of a code block a new code block
1254 is created. In both cases if the region is demarcated and if the
1255 region is not active then the point is demarcated."
1256 (interactive "P")
1257 (let ((info (org-babel-get-src-block-info 'light))
1258 (stars (concat (make-string (or (org-current-level) 1) ?*) " ")))
1259 (if info
1260 (mapc
1261 (lambda (place)
1262 (save-excursion
1263 (goto-char place)
1264 (let ((lang (nth 0 info))
1265 (indent (make-string (nth 5 info) ? )))
1266 (when (string-match "^[[:space:]]*$"
1267 (buffer-substring (point-at-bol)
1268 (point-at-eol)))
1269 (delete-region (point-at-bol) (point-at-eol)))
1270 (insert (concat (if (looking-at "^") "" "\n")
1271 indent "#+end_src\n"
1272 (if arg stars indent) "\n"
1273 indent "#+begin_src " lang
1274 (if (looking-at "[\n\r]") "" "\n")))))
1275 (move-end-of-line 2))
1276 (sort (if (region-active-p) (list (mark) (point)) (list (point))) #'>))
1277 (let ((start (point))
1278 (lang (org-icompleting-read "Lang: "
1279 (mapcar (lambda (el) (symbol-name (car el)))
1280 org-babel-load-languages)))
1281 (body (delete-and-extract-region
1282 (if (region-active-p) (mark) (point)) (point))))
1283 (insert (concat (if (looking-at "^") "" "\n")
1284 (if arg (concat stars "\n") "")
1285 "#+begin_src " lang "\n"
1286 body
1287 (if (or (= (length body) 0)
1288 (string-match "[\r\n]$" body)) "" "\n")
1289 "#+end_src\n"))
1290 (goto-char start) (move-end-of-line 1)))))
1292 (defvar org-babel-lob-one-liner-regexp)
1293 (defun org-babel-where-is-src-block-result (&optional insert info hash indent)
1294 "Find where the current source block results begin.
1295 Return the point at the beginning of the result of the current
1296 source block. Specifically at the beginning of the results line.
1297 If no result exists for this block then create a results line
1298 following the source block."
1299 (save-excursion
1300 (let* ((on-lob-line (save-excursion
1301 (beginning-of-line 1)
1302 (looking-at org-babel-lob-one-liner-regexp)))
1303 (inlinep (save-excursion
1304 (re-search-backward "[ \f\t\n\r\v]" nil t)
1305 (when (looking-at org-babel-inline-src-block-regexp)
1306 (match-end 0))))
1307 (name (if on-lob-line
1308 (nth 0 (org-babel-lob-get-info))
1309 (nth 4 (or info (org-babel-get-src-block-info)))))
1310 (head (unless on-lob-line (org-babel-where-is-src-block-head)))
1311 found beg end)
1312 (when head (goto-char head))
1313 (setq
1314 found ;; was there a result (before we potentially insert one)
1316 inlinep
1317 (and
1318 ;; named results:
1319 ;; - return t if it is found, else return nil
1320 ;; - if it does not need to be rebuilt, then don't set end
1321 ;; - if it does need to be rebuilt then do set end
1322 name (setq beg (org-babel-find-named-result name))
1323 (prog1 beg
1324 (when (and hash (not (string= hash (match-string 3))))
1325 (goto-char beg) (setq end beg) ;; beginning of result
1326 (forward-line 1)
1327 (delete-region end (org-babel-result-end)) nil)))
1328 (and
1329 ;; unnamed results:
1330 ;; - return t if it is found, else return nil
1331 ;; - if it is found, and the hash doesn't match, delete and set end
1332 (or on-lob-line (re-search-forward "^[ \t]*#\\+end_src" nil t))
1333 (progn (end-of-line 1)
1334 (if (eobp) (insert "\n") (forward-char 1))
1335 (setq end (point))
1336 (or (and (not name)
1337 (progn ;; unnamed results line already exists
1338 (re-search-forward "[^ \f\t\n\r\v]" nil t)
1339 (beginning-of-line 1)
1340 (looking-at
1341 (concat org-babel-result-regexp "\n")))
1342 (prog1 (point)
1343 ;; must remove and rebuild if hash!=old-hash
1344 (if (and hash (not (string= hash (match-string 3))))
1345 (prog1 nil
1346 (forward-line 1)
1347 (delete-region
1348 end (org-babel-result-end)))
1349 (setq end nil)))))))))
1350 (if (and insert end)
1351 (progn
1352 (goto-char end)
1353 (unless beg
1354 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1355 (insert (concat
1356 (if indent
1357 (mapconcat
1358 (lambda (el) " ")
1359 (org-number-sequence 1 indent) "")
1361 "#+results"
1362 (when hash (concat "["hash"]"))
1364 (when name (concat " " name)) "\n"))
1365 (unless beg (insert "\n") (backward-char))
1366 (beginning-of-line 0)
1367 (if hash (org-babel-hide-hash))
1368 (point))
1369 found))))
1371 (defvar org-block-regexp)
1372 (defun org-babel-read-result ()
1373 "Read the result at `point' into emacs-lisp."
1374 (let ((case-fold-search t) result-string)
1375 (cond
1376 ((org-at-table-p) (org-babel-read-table))
1377 ((org-at-item-p) (org-babel-read-list))
1378 ((looking-at org-bracket-link-regexp) (org-babel-read-link))
1379 ((looking-at org-block-regexp) (org-babel-trim (match-string 4)))
1380 ((looking-at "^[ \t]*: ")
1381 (setq result-string
1382 (org-babel-trim
1383 (mapconcat (lambda (line)
1384 (if (and (> (length line) 1)
1385 (string-match "^[ \t]*: \\(.+\\)" line))
1386 (match-string 1 line)
1387 line))
1388 (split-string
1389 (buffer-substring
1390 (point) (org-babel-result-end)) "[\r\n]+")
1391 "\n")))
1392 (or (org-babel-number-p result-string) result-string))
1393 ((looking-at org-babel-result-regexp)
1394 (save-excursion (forward-line 1) (org-babel-read-result))))))
1396 (defun org-babel-read-table ()
1397 "Read the table at `point' into emacs-lisp."
1398 (mapcar (lambda (row)
1399 (if (and (symbolp row) (equal row 'hline)) row
1400 (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval)) row)))
1401 (org-table-to-lisp)))
1403 (defun org-babel-read-list ()
1404 "Read the list at `point' into emacs-lisp."
1405 (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval))
1406 (mapcar #'cadr (cdr (org-list-parse-list)))))
1408 (defvar org-link-types-re)
1409 (defun org-babel-read-link ()
1410 "Read the link at `point' into emacs-lisp.
1411 If the path of the link is a file path it is expanded using
1412 `expand-file-name'."
1413 (let* ((case-fold-search t)
1414 (raw (and (looking-at org-bracket-link-regexp)
1415 (org-babel-clean-text-properties (match-string 1))))
1416 (type (and (string-match org-link-types-re raw)
1417 (match-string 1 raw))))
1418 (cond
1419 ((not type) (expand-file-name raw))
1420 ((string= type "file")
1421 (and (string-match "file\\(.*\\):\\(.+\\)" raw)
1422 (expand-file-name (match-string 2 raw))))
1423 (t raw))))
1425 (defun org-babel-format-result (result &optional sep)
1426 "Format RESULT for writing to file."
1427 (flet ((echo-res (result)
1428 (if (stringp result) result (format "%S" result))))
1429 (if (listp result)
1430 ;; table result
1431 (orgtbl-to-generic
1432 result
1433 (list
1434 :sep (or sep "\t")
1435 :fmt 'echo-res))
1436 ;; scalar result
1437 (echo-res result))))
1439 (defun org-babel-insert-result
1440 (result &optional result-params info hash indent lang)
1441 "Insert RESULT into the current buffer.
1442 By default RESULT is inserted after the end of the
1443 current source block. With optional argument RESULT-PARAMS
1444 controls insertion of results in the org-mode file.
1445 RESULT-PARAMS can take the following values...
1447 replace - (default option) insert results after the source block
1448 replacing any previously inserted results
1450 silent -- no results are inserted
1452 file ---- the results are interpreted as a file path, and are
1453 inserted into the buffer using the Org-mode file syntax
1455 list ---- the results are interpreted as an Org-mode list.
1457 raw ----- results are added directly to the Org-mode file. This
1458 is a good option if you code block will output org-mode
1459 formatted text.
1461 org ----- similar in effect to raw, only the results are wrapped
1462 in an org code block. Similar to the raw option, on
1463 export the results will be interpreted as org-formatted
1464 text, however by wrapping the results in an org code
1465 block they can be replaced upon re-execution of the
1466 code block.
1468 html ---- results are added inside of a #+BEGIN_HTML block. This
1469 is a good option if you code block will output html
1470 formatted text.
1472 latex --- results are added inside of a #+BEGIN_LATEX block.
1473 This is a good option if you code block will output
1474 latex formatted text.
1476 code ---- the results are extracted in the syntax of the source
1477 code of the language being evaluated and are added
1478 inside of a #+BEGIN_SRC block with the source-code
1479 language set appropriately. Note this relies on the
1480 optional LANG argument."
1481 (if (stringp result)
1482 (progn
1483 (setq result (org-babel-clean-text-properties result))
1484 (when (member "file" result-params)
1485 (setq result (org-babel-result-to-file result))))
1486 (unless (listp result) (setq result (format "%S" result))))
1487 (if (and result-params (member "silent" result-params))
1488 (progn
1489 (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
1490 result)
1491 (save-excursion
1492 (let* ((inlinep (save-excursion
1493 (re-search-backward "[ \f\t\n\r\v]" nil t)
1494 (when (looking-at org-babel-inline-src-block-regexp)
1495 (goto-char (match-end 0))
1496 (insert (if (listp result) "\n" " "))
1497 (point))))
1498 (existing-result (unless inlinep
1499 (org-babel-where-is-src-block-result
1500 t info hash indent)))
1501 (results-switches
1502 (cdr (assoc :results_switches (nth 2 info))))
1503 beg end)
1504 (when (and (stringp result) ; ensure results end in a newline
1505 (not inlinep)
1506 (> (length result) 0)
1507 (not (or (string-equal (substring result -1) "\n")
1508 (string-equal (substring result -1) "\r"))))
1509 (setq result (concat result "\n")))
1510 (if (not existing-result)
1511 (setq beg (or inlinep (point)))
1512 (goto-char existing-result)
1513 (save-excursion
1514 (re-search-forward "#" nil t)
1515 (setq indent (- (current-column) 1)))
1516 (forward-line 1)
1517 (setq beg (point))
1518 (cond
1519 ((member "replace" result-params)
1520 (delete-region (point) (org-babel-result-end)))
1521 ((member "append" result-params)
1522 (goto-char (org-babel-result-end)) (setq beg (point-marker)))
1523 ((member "prepend" result-params)))) ; already there
1524 (setq results-switches
1525 (if results-switches (concat " " results-switches) ""))
1526 ;; insert results based on type
1527 (cond
1528 ;; do nothing for an empty result
1529 ((= (length result) 0))
1530 ;; insert a list if preferred
1531 ((member "list" result-params)
1532 (insert
1533 (org-babel-trim
1534 (org-list-to-generic
1535 (cons 'unordered
1536 (mapcar
1537 (lambda (el) (list nil (if (stringp el) el (format "%S" el))))
1538 (if (listp result) result (list result))))
1539 '(:splicep nil :istart "- " :iend "\n")))
1540 "\n"))
1541 ;; assume the result is a table if it's not a string
1542 ((not (stringp result))
1543 (goto-char beg)
1544 (insert (concat (orgtbl-to-orgtbl
1545 (if (or (eq 'hline (car result))
1546 (and (listp (car result))
1547 (listp (cdr (car result)))))
1548 result (list result))
1549 '(:fmt (lambda (cell) (format "%s" cell)))) "\n"))
1550 (goto-char beg) (when (org-at-table-p) (org-table-align)))
1551 ((member "file" result-params)
1552 (insert result))
1553 (t (goto-char beg) (insert result)))
1554 (when (listp result) (goto-char (org-table-end)))
1555 (setq end (point-marker))
1556 ;; possibly wrap result
1557 (flet ((wrap (start finish)
1558 (goto-char beg) (insert (concat start "\n"))
1559 (goto-char end) (insert (concat finish "\n"))
1560 (setq end (point-marker))))
1561 (cond
1562 ((member "html" result-params)
1563 (wrap "#+BEGIN_HTML" "#+END_HTML"))
1564 ((member "latex" result-params)
1565 (wrap "#+BEGIN_LaTeX" "#+END_LaTeX"))
1566 ((member "code" result-params)
1567 (wrap (format "#+BEGIN_SRC %s%s" (or lang "none") results-switches)
1568 "#+END_SRC"))
1569 ((member "org" result-params)
1570 (wrap "#+BEGIN_ORG" "#+END_ORG"))
1571 ((member "raw" result-params)
1572 (goto-char beg) (if (org-at-table-p) (org-cycle)))
1573 ((member "wrap" result-params)
1574 (when (and (stringp result) (not (member "file" result-params)))
1575 (org-babel-examplize-region beg end results-switches))
1576 (wrap "#+BEGIN_RESULT" "#+END_RESULT"))
1577 ((and (stringp result) (not (member "file" result-params)))
1578 (org-babel-examplize-region beg end results-switches)
1579 (setq end (point)))))
1580 ;; possibly indent the results to match the #+results line
1581 (when (and (not inlinep) (numberp indent) indent (> indent 0)
1582 ;; in this case `table-align' does the work for us
1583 (not (and (listp result)
1584 (member "append" result-params))))
1585 (indent-rigidly beg end indent))))
1586 (if (= (length result) 0)
1587 (if (member "value" result-params)
1588 (message "Code block returned no value.")
1589 (message "Code block produced no output."))
1590 (message "Code block evaluation complete."))))
1592 (defun org-babel-remove-result (&optional info)
1593 "Remove the result of the current source block."
1594 (interactive)
1595 (let ((location (org-babel-where-is-src-block-result nil info)) start)
1596 (when location
1597 (save-excursion
1598 (goto-char location) (setq start (point)) (forward-line 1)
1599 (delete-region start (org-babel-result-end))))))
1601 (defun org-babel-result-end ()
1602 "Return the point at the end of the current set of results"
1603 (save-excursion
1604 (cond
1605 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
1606 ((org-at-item-p) (let* ((struct (org-list-struct))
1607 (prvs (org-list-prevs-alist struct)))
1608 (org-list-get-list-end (point-at-bol) struct prvs)))
1610 (let ((case-fold-search t)
1611 (blocks-re (regexp-opt
1612 (list "latex" "html" "example" "src" "result" "org"))))
1613 (if (looking-at (concat "[ \t]*#\\+begin_" blocks-re))
1614 (progn (re-search-forward (concat "[ \t]*#\\+end_" blocks-re) nil t)
1615 (forward-char 1))
1616 (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
1617 (forward-line 1))))
1618 (point)))))
1620 (defun org-babel-result-to-file (result)
1621 "Convert RESULT into an `org-mode' link.
1622 If the `default-directory' is different from the containing
1623 file's directory then expand relative links."
1624 (flet ((cond-exp (file)
1625 (if (and default-directory
1626 buffer-file-name
1627 (not (string= (expand-file-name default-directory)
1628 (expand-file-name
1629 (file-name-directory buffer-file-name)))))
1630 (expand-file-name file default-directory)
1631 file)))
1632 (if (stringp result)
1633 (format "[[file:%s]]" (cond-exp result))
1634 (when (and (listp result) (= 2 (length result))
1635 (stringp (car result)) (stringp (cadr result)))
1636 (format "[[file:%s][%s]]" (car result) (cadr result))))))
1638 (defun org-babel-examplize-region (beg end &optional results-switches)
1639 "Comment out region using the inline '==' or ': ' org example quote."
1640 (interactive "*r")
1641 (flet ((chars-between (b e) (string-match "[\\S]" (buffer-substring b e))))
1642 (if (or (chars-between (save-excursion (goto-char beg) (point-at-bol)) beg)
1643 (chars-between end (save-excursion (goto-char end) (point-at-eol))))
1644 (save-excursion
1645 (goto-char beg)
1646 (insert (format "=%s=" (prog1 (buffer-substring beg end)
1647 (delete-region beg end)))))
1648 (let ((size (count-lines beg end)))
1649 (save-excursion
1650 (cond ((= size 0)) ; do nothing for an empty result
1651 ((< size org-babel-min-lines-for-block-output)
1652 (goto-char beg)
1653 (dotimes (n size)
1654 (beginning-of-line 1) (insert ": ") (forward-line 1)))
1656 (goto-char beg)
1657 (insert (if results-switches
1658 (format "#+begin_example%s\n" results-switches)
1659 "#+begin_example\n"))
1660 (if (markerp end) (goto-char end) (forward-char (- end beg)))
1661 (insert "#+end_example\n"))))))))
1663 (defun org-babel-update-block-body (new-body)
1664 "Update the body of the current code block to NEW-BODY."
1665 (if (not (org-babel-where-is-src-block-head))
1666 (error "not in source block")
1667 (save-match-data
1668 (replace-match (concat (org-babel-trim new-body) "\n") nil t nil 5))
1669 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
1671 (defun org-babel-merge-params (&rest plists)
1672 "Combine all parameter association lists in PLISTS.
1673 Later elements of PLISTS override the values of previous elements.
1674 This takes into account some special considerations for certain
1675 parameters when merging lists."
1676 (let ((results-exclusive-groups
1677 '(("file" "list" "vector" "table" "scalar" "raw" "org"
1678 "html" "latex" "code" "pp" "wrap")
1679 ("replace" "silent" "append" "prepend")
1680 ("output" "value")))
1681 (exports-exclusive-groups
1682 '(("code" "results" "both" "none")))
1683 params results exports tangle noweb cache vars shebang comments padline)
1684 (flet ((e-merge (exclusive-groups &rest result-params)
1685 ;; maintain exclusivity of mutually exclusive parameters
1686 (let (output)
1687 (mapc (lambda (new-params)
1688 (mapc (lambda (new-param)
1689 (mapc (lambda (exclusive-group)
1690 (when (member new-param exclusive-group)
1691 (mapcar (lambda (excluded-param)
1692 (setq output
1693 (delete
1694 excluded-param
1695 output)))
1696 exclusive-group)))
1697 exclusive-groups)
1698 (setq output (org-uniquify
1699 (cons new-param output))))
1700 new-params))
1701 result-params)
1702 output)))
1703 (mapc
1704 (lambda (plist)
1705 (mapc
1706 (lambda (pair)
1707 (case (car pair)
1708 (:var
1709 (let ((name (if (listp (cdr pair))
1710 (cadr pair)
1711 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
1712 (cdr pair))
1713 (intern (match-string 1 (cdr pair)))))))
1714 (when name
1715 (setq vars
1716 (cons (cons name pair)
1717 (if (member name (mapcar #'car vars))
1718 (delq nil
1719 (mapcar
1720 (lambda (p) (unless (equal (car p) name) p))
1721 vars))
1722 vars))))))
1723 (:results
1724 (setq results (e-merge results-exclusive-groups
1725 results
1726 (split-string
1727 (let ((r (cdr pair)))
1728 (if (stringp r) r (eval r)))))))
1729 (:file
1730 (when (cdr pair)
1731 (setq results (e-merge results-exclusive-groups
1732 results '("file")))
1733 (unless (or (member "both" exports)
1734 (member "none" exports)
1735 (member "code" exports))
1736 (setq exports (e-merge exports-exclusive-groups
1737 exports '("results"))))
1738 (setq params (cons pair (assq-delete-all (car pair) params)))))
1739 (:exports
1740 (setq exports (e-merge exports-exclusive-groups
1741 exports (split-string (cdr pair)))))
1742 (:tangle ;; take the latest -- always overwrite
1743 (setq tangle (or (list (cdr pair)) tangle)))
1744 (:noweb
1745 (setq noweb (e-merge '(("yes" "no" "tangle")) noweb
1746 (split-string (or (cdr pair) "")))))
1747 (:cache
1748 (setq cache (e-merge '(("yes" "no")) cache
1749 (split-string (or (cdr pair) "")))))
1750 (:padline
1751 (setq padline (e-merge '(("yes" "no")) padline
1752 (split-string (or (cdr pair) "")))))
1753 (:shebang ;; take the latest -- always overwrite
1754 (setq shebang (or (list (cdr pair)) shebang)))
1755 (:comments
1756 (setq comments (e-merge '(("yes" "no")) comments
1757 (split-string (or (cdr pair) "")))))
1758 (t ;; replace: this covers e.g. :session
1759 (setq params (cons pair (assq-delete-all (car pair) params))))))
1760 plist))
1761 plists))
1762 (while vars (setq params (cons (cons :var (cddr (pop vars))) params)))
1763 (mapc
1764 (lambda (hd)
1765 (let ((key (intern (concat ":" (symbol-name hd))))
1766 (val (eval hd)))
1767 (setf params (cons (cons key (mapconcat 'identity val " ")) params))))
1768 '(results exports tangle noweb padline cache shebang comments))
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