1 ;;; ob.el --- working with code blocks in org-mode
3 ;; Copyright (C) 2009-2011 Free Software Foundation, Inc.
5 ;; Author: Eric Schulte
7 ;; Keywords: literate programming, reproducible research
8 ;; Homepage: http://orgmode.org
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/>.
31 (defvar org-babel-call-process-region-original
)
32 (defvar org-src-lang-modes
)
33 (defvar org-babel-library-of-babel
)
34 (declare-function show-all
"outline" ())
35 (declare-function tramp-compat-make-temp-file
"tramp-compat"
36 (filename &optional dir-flag
))
37 (declare-function tramp-dissect-file-name
"tramp" (name &optional nodefault
))
38 (declare-function tramp-file-name-user
"tramp" (vec))
39 (declare-function tramp-file-name-host
"tramp" (vec))
40 (declare-function with-parsed-tramp-file-name
"tramp" (filename var
&rest body
))
41 (declare-function org-icompleting-read
"org" (&rest args
))
42 (declare-function org-edit-src-code
"org-src"
43 (&optional context code edit-buffer-name quietp
))
44 (declare-function org-edit-src-exit
"org-src" (&optional context
))
45 (declare-function org-open-at-point
"org" (&optional in-emacs reference-buffer
))
46 (declare-function org-save-outline-visibility
"org" (use-markers &rest body
))
47 (declare-function org-outline-overlay-data
"org" (&optional use-markers
))
48 (declare-function org-set-outline-overlay-data
"org" (data))
49 (declare-function org-narrow-to-subtree
"org" ())
50 (declare-function org-entry-get
"org"
51 (pom property
&optional inherit literal-nil
))
52 (declare-function org-make-options-regexp
"org" (kwds &optional extra
))
53 (declare-function org-do-remove-indentation
"org" (&optional n
))
54 (declare-function org-show-context
"org" (&optional key
))
55 (declare-function org-at-table-p
"org" (&optional table-type
))
56 (declare-function org-cycle
"org" (&optional arg
))
57 (declare-function org-uniquify
"org" (list))
58 (declare-function org-current-level
"org" ())
59 (declare-function org-table-import
"org-table" (file arg
))
60 (declare-function org-add-hook
"org-compat"
61 (hook function
&optional append local
))
62 (declare-function org-table-align
"org-table" ())
63 (declare-function org-table-end
"org-table" (&optional table-type
))
64 (declare-function orgtbl-to-generic
"org-table" (table params
))
65 (declare-function orgtbl-to-orgtbl
"org-table" (table params
))
66 (declare-function org-babel-tangle-comment-links
"ob-tangle" (&optional info
))
67 (declare-function org-babel-lob-get-info
"ob-lob" nil
)
68 (declare-function org-babel-ref-split-args
"ob-ref" (arg-string))
69 (declare-function org-babel-ref-parse
"ob-ref" (assignment))
70 (declare-function org-babel-ref-resolve
"ob-ref" (ref))
71 (declare-function org-babel-ref-goto-headline-id
"ob-ref" (id))
72 (declare-function org-babel-ref-headline-body
"ob-ref" ())
73 (declare-function org-babel-lob-execute-maybe
"ob-lob" ())
74 (declare-function org-number-sequence
"org-compat" (from &optional to inc
))
75 (declare-function org-at-item-p
"org-list" ())
76 (declare-function org-list-parse-list
"org-list" (&optional delete
))
77 (declare-function org-list-to-generic
"org-list" (LIST PARAMS
))
78 (declare-function org-list-struct
"org-list" ())
79 (declare-function org-list-prevs-alist
"org-list" (struct))
80 (declare-function org-list-get-list-end
"org-list" (item struct prevs
))
82 (defgroup org-babel nil
83 "Code block evaluation and management in `org-mode' documents."
87 (defcustom org-confirm-babel-evaluate t
88 "Confirm before evaluation.
89 Require confirmation before interactively evaluating code
90 blocks in Org-mode buffers. The default value of this variable
91 is t, meaning confirmation is required for any code block
92 evaluation. This variable can be set to nil to inhibit any
93 future confirmation requests. This variable can also be set to a
94 function which takes two arguments the language of the code block
95 and the body of the code block. Such a function should then
96 return a non-nil value if the user should be prompted for
97 execution or nil if no prompt is required.
99 Warning: Disabling confirmation may result in accidental
100 evaluation of potentially harmful code. It may be advisable
101 remove code block execution from C-c C-c as further protection
102 against accidental code block evaluation. The
103 `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
104 remove code block execution from the C-c C-c keybinding."
106 :type
'(choice boolean function
))
107 ;; don't allow this variable to be changed through file settings
108 (put 'org-confirm-babel-evaluate
'safe-local-variable
(lambda (x) (eq x t
)))
110 (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
111 "Remove code block evaluation from the C-c C-c key binding."
115 (defvar org-babel-src-name-regexp
116 "^[ \t]*#\\+\\(srcname\\|source\\|function\\):[ \t]*"
117 "Regular expression used to match a source name line.")
119 (defvar org-babel-multi-line-header-regexp
120 "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
121 "Regular expression used to match multi-line header arguments.")
123 (defvar org-babel-src-name-w-name-regexp
124 (concat org-babel-src-name-regexp
126 org-babel-multi-line-header-regexp
128 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)")
129 "Regular expression matching source name lines with a name.")
131 (defvar org-babel-src-block-regexp
133 ;; (1) indentation (2) lang
134 "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
136 "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
137 ;; (4) header arguments
140 "\\([^\000]*?\n\\)?[ \t]*#\\+end_src")
141 "Regexp used to identify code blocks.")
143 (defvar org-babel-inline-src-block-regexp
145 ;; (1) replacement target (2) lang
146 "\\(?:^\\|[^-[:alnum:]]\\)\\(src_\\([^ \f\t\n\r\v]+\\)"
147 ;; (3,4) (unused, headers)
148 "\\(\\|\\[\\(.*?\\)\\]\\)"
150 "{\\([^\f\n\r\v]+?\\)}\\)")
151 "Regexp used to identify inline src-blocks.")
153 (defun org-babel-get-header (params key
&optional others
)
154 "Select only header argument of type KEY from a list.
155 Optional argument OTHERS indicates that only the header that do
156 not match KEY should be returned."
159 (lambda (p) (when (funcall (if others
#'not
#'identity
) (eq (car p
) key
)) p
))
162 (defun org-babel-get-inline-src-block-matches()
163 "Set match data if within body of an inline source block.
164 Returns non-nil if match-data set"
165 (let ((src-at-0-p (save-excursion
166 (beginning-of-line 1)
167 (string= "src" (thing-at-point 'word
))))
168 (first-line-p (= 1 (line-number-at-pos)))
170 (let ((search-for (cond ((and src-at-0-p first-line-p
"src_"))
171 (first-line-p "[ \t]src_")
172 (t "[ \f\t\n\r\v]src_")))
173 (lower-limit (if first-line-p
175 (- (point-at-bol) 1))))
177 (when (or (and src-at-0-p
(bobp))
178 (and (re-search-forward "}" (point-at-eol) t
)
179 (re-search-backward search-for lower-limit t
)
181 (when (looking-at org-babel-inline-src-block-regexp
)
184 (defun org-babel-get-lob-one-liner-matches()
185 "Set match data if on line of an lob one liner.
186 Returns non-nil if match-data set"
189 (unless (= (point) (point-at-bol)) ;; move before inline block
190 (re-search-backward "[ \f\t\n\r\v]" nil t
))
191 (if (looking-at org-babel-inline-lob-one-liner-regexp
)
195 (defun org-babel-get-src-block-info (&optional light
)
196 "Get information on the current source block.
198 Optional argument LIGHT does not resolve remote variable
199 references; a process which could likely result in the execution
200 of other code blocks.
203 (language body header-arguments-alist switches name indent)."
204 (let ((case-fold-search t
) head info name indent
)
206 (if (setq head
(org-babel-where-is-src-block-head))
209 (setq info
(org-babel-parse-src-block-match))
210 (setq indent
(car (last info
)))
211 (setq info
(butlast info
))
212 (while (and (forward-line -
1)
213 (looking-at org-babel-multi-line-header-regexp
))
215 (org-babel-merge-params
217 (org-babel-parse-header-arguments (match-string 1)))))
218 (when (looking-at org-babel-src-name-w-name-regexp
)
219 (setq name
(org-babel-clean-text-properties (match-string 4)))
220 (when (match-string 6)
221 (setf (nth 2 info
) ;; merge functional-syntax vars and header-args
222 (org-babel-merge-params
224 (lambda (ref) (cons :var ref
))
226 (lambda (var) ;; check that each variable is initialized
227 (if (string-match ".+=.+" var
)
230 "variable \"%s\"%s must be assigned a default value"
231 var
(if name
(format " in block \"%s\"" name
) ""))))
232 (org-babel-ref-split-args (match-string 6))))
234 ;; inline source block
235 (when (org-babel-get-inline-src-block-matches)
236 (setq info
(org-babel-parse-inline-src-block-match))))
237 ;; resolve variable references and add summary parameters
238 (when (and info
(not light
))
239 (setf (nth 2 info
) (org-babel-process-params (nth 2 info
))))
240 (when info
(append info
(list name indent
)))))
242 (defun org-babel-confirm-evaluate (info)
243 "Confirm evaluation of the code block INFO.
244 This behavior can be suppressed by setting the value of
245 `org-confirm-babel-evaluate' to nil, in which case all future
246 interactive code block evaluations will proceed without any
247 confirmation from the user.
249 Note disabling confirmation may result in accidental evaluation
250 of potentially harmful code."
251 (let* ((eval (or (cdr (assoc :eval
(nth 2 info
)))
252 (when (assoc :noeval
(nth 2 info
)) "no")))
253 (query (cond ((equal eval
"query") t
)
254 ((functionp org-confirm-babel-evaluate
)
255 (funcall org-confirm-babel-evaluate
256 (nth 0 info
) (nth 1 info
)))
257 (t org-confirm-babel-evaluate
))))
258 (if (or (equal eval
"never") (equal eval
"no")
261 (format "Evaluate this%scode block%son your system? "
262 (if info
(format " %s " (nth 0 info
)) " ")
264 (format " (%s) " (nth 4 info
)) " "))))))
265 (prog1 nil
(message "Evaluation %s"
266 (if (or (equal eval
"never") (equal eval
"no"))
267 "Disabled" "Aborted")))
271 (defun org-babel-execute-safely-maybe ()
272 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
273 (org-babel-execute-maybe)))
275 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-execute-safely-maybe
)
278 (defun org-babel-execute-maybe ()
280 (or (org-babel-execute-src-block-maybe)
281 (org-babel-lob-execute-maybe)))
283 (defun org-babel-execute-src-block-maybe ()
284 "Conditionally execute a source block.
285 Detect if this is context for a Babel src-block and if so
286 then run `org-babel-execute-src-block'."
288 (let ((info (org-babel-get-src-block-info)))
290 (progn (org-babel-eval-wipe-error-buffer)
291 (org-babel-execute-src-block current-prefix-arg info
) t
) nil
)))
294 (defun org-babel-view-src-block-info ()
295 "Display information on the current source block.
296 This includes header arguments, language and name, and is largely
297 a window into the `org-babel-get-src-block-info' function."
299 (let ((info (org-babel-get-src-block-info 'light
)))
300 (flet ((full (it) (> (length it
) 0))
301 (printf (fmt &rest args
) (princ (apply #'format fmt args
))))
303 (with-help-window (help-buffer)
304 (let ((name (nth 4 info
))
306 (switches (nth 3 info
))
307 (header-args (nth 2 info
)))
308 (when name
(printf "Name: %s\n" name
))
309 (when lang
(printf "Lang: %s\n" lang
))
310 (when (full switches
) (printf "Switches: %s\n" switches
))
311 (printf "Header Arguments:\n")
312 (dolist (pair (sort header-args
313 (lambda (a b
) (string< (symbol-name (car a
))
314 (symbol-name (car b
))))))
315 (when (full (cdr pair
))
316 (printf "\t%S%s\t%s\n"
318 (if (> (length (format "%S" (car pair
))) 7) "" "\t")
322 (defun org-babel-expand-src-block-maybe ()
323 "Conditionally expand a source block.
324 Detect if this is context for a org-babel src-block and if so
325 then run `org-babel-expand-src-block'."
327 (let ((info (org-babel-get-src-block-info)))
329 (progn (org-babel-expand-src-block current-prefix-arg info
) t
)
333 (defun org-babel-load-in-session-maybe ()
334 "Conditionally load a source block in a session.
335 Detect if this is context for a org-babel src-block and if so
336 then run `org-babel-load-in-session'."
338 (let ((info (org-babel-get-src-block-info)))
340 (progn (org-babel-load-in-session current-prefix-arg info
) t
)
343 (add-hook 'org-metaup-hook
'org-babel-load-in-session-maybe
)
346 (defun org-babel-pop-to-session-maybe ()
347 "Conditionally pop to a session.
348 Detect if this is context for a org-babel src-block and if so
349 then run `org-babel-pop-to-session'."
351 (let ((info (org-babel-get-src-block-info)))
352 (if info
(progn (org-babel-pop-to-session current-prefix-arg info
) t
) nil
)))
354 (add-hook 'org-metadown-hook
'org-babel-pop-to-session-maybe
)
356 (defconst org-babel-common-header-args-w-values
357 '((cache .
((no yes
)))
359 (colnames .
((nil no yes
)))
360 (comments .
((no link yes org both noweb
)))
362 (eval .
((never query
)))
363 (exports .
((code results both none
)))
365 (hlines .
((no yes
)))
366 (mkdirp .
((yes no
)))
369 (noweb .
((yes no tangle
)))
371 (padline .
((yes no
)))
372 (results .
((file list vector table scalar verbatim
)
373 (raw org html latex code pp wrap
)
374 (replace silent append prepend
)
376 (rownames .
((no yes
)))
380 (tangle .
((tangle yes no
:any
)))
383 (defconst org-babel-header-arg-names
384 (mapcar #'car org-babel-common-header-args-w-values
)
385 "Common header arguments used by org-babel.
386 Note that individual languages may define their own language
387 specific header arguments as well.")
389 (defvar org-babel-default-header-args
390 '((:session .
"none") (:results .
"replace") (:exports .
"code")
391 (:cache .
"no") (:noweb .
"no") (:hlines .
"no") (:tangle .
"no")
392 (:padnewline .
"yes"))
393 "Default arguments to use when evaluating a source block.")
395 (defvar org-babel-default-inline-header-args
396 '((:session .
"none") (:results .
"replace") (:exports .
"results"))
397 "Default arguments to use when evaluating an inline source block.")
399 (defvar org-babel-data-names
'("TBLNAME" "RESNAME" "RESULTS" "DATA"))
401 (defvar org-babel-result-regexp
402 (concat "^[ \t]*#\\+"
403 (regexp-opt org-babel-data-names t
)
404 "\\(\\[\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*")
405 "Regular expression used to match result lines.
406 If the results are associated with a hash key then the hash will
407 be saved in the second match data.")
409 (defvar org-babel-result-w-name-regexp
410 (concat org-babel-result-regexp
411 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
413 (defvar org-babel-min-lines-for-block-output
10
414 "The minimum number of lines for block output.
415 If number of lines of output is equal to or exceeds this
416 value, the output is placed in a #+begin_example...#+end_example
417 block. Otherwise the output is marked as literal by inserting
418 colons at the starts of the lines. This variable only takes
419 effect if the :results output option is in effect.")
421 (defvar org-babel-noweb-error-langs nil
422 "Languages for which Babel will raise literate programming errors.
423 List of languages for which errors should be raised when the
424 source code block satisfying a noweb reference in this language
425 can not be resolved.")
427 (defvar org-babel-hash-show
4
428 "Number of initial characters to show of a hidden results hash.")
430 (defvar org-babel-after-execute-hook nil
431 "Hook for functions to be called after `org-babel-execute-src-block'")
432 (defun org-babel-named-src-block-regexp-for-name (name)
433 "This generates a regexp used to match a src block named NAME."
434 (concat org-babel-src-name-regexp
(regexp-quote name
) "[ \t\n]*"
435 (substring org-babel-src-block-regexp
1)))
438 (defvar call-process-region
)
441 (defun org-babel-execute-src-block (&optional arg info params
)
442 "Execute the current source code block.
443 Insert the results of execution into the buffer. Source code
444 execution and the collection and formatting of results can be
445 controlled through a variety of header arguments.
447 With prefix argument ARG, force re-execution even if a an
448 existing result cached in the buffer would otherwise have been
451 Optionally supply a value for INFO in the form returned by
452 `org-babel-get-src-block-info'.
454 Optionally supply a value for PARAMS which will be merged with
455 the header arguments specified at the front of the source code
458 (let ((info (or info
(org-babel-get-src-block-info))))
459 (when (org-babel-confirm-evaluate info
)
460 (let* ((lang (nth 0 info
))
462 (org-babel-process-params
463 (org-babel-merge-params (nth 2 info
) params
))
465 (cache?
(and (not arg
) (cdr (assoc :cache params
))
466 (string= "yes" (cdr (assoc :cache params
)))))
467 (result-params (cdr (assoc :result-params params
)))
468 (new-hash (when cache?
(org-babel-sha1-hash info
)))
469 (old-hash (when cache?
(org-babel-current-result-hash)))
470 (body (setf (nth 1 info
)
471 (let ((noweb (cdr (assoc :noweb params
))))
473 (or (string= "yes" noweb
)
474 (string= "tangle" noweb
)))
475 (org-babel-expand-noweb-references info
)
477 (dir (cdr (assoc :dir params
)))
479 (or (and dir
(file-name-as-directory dir
)) default-directory
))
480 (org-babel-call-process-region-original
481 (if (boundp 'org-babel-call-process-region-original
)
482 org-babel-call-process-region-original
483 (symbol-function 'call-process-region
)))
484 (indent (car (last info
)))
487 (flet ((call-process-region (&rest args
)
488 (apply 'org-babel-tramp-handle-call-process-region args
)))
489 (flet ((lang-check (f)
490 (let ((f (intern (concat "org-babel-execute:" f
))))
491 (when (fboundp f
) f
))))
493 (or (lang-check lang
)
494 (lang-check (symbol-name
495 (cdr (assoc lang org-src-lang-modes
))))
496 (error "No org-babel-execute function for %s!" lang
))))
497 (if (and (not arg
) new-hash
(equal new-hash old-hash
))
498 (save-excursion ;; return cached result
499 (goto-char (org-babel-where-is-src-block-result nil info
))
500 (end-of-line 1) (forward-char 1)
501 (setq result
(org-babel-read-result))
502 (message (replace-regexp-in-string
503 "%" "%%" (format "%S" result
))) result
)
504 (message "executing %s code block%s..."
506 (if (nth 4 info
) (format " (%s)" (nth 4 info
)) ""))
509 (if (and (eq (cdr (assoc :result-type params
)) 'value
)
510 (or (member "vector" result-params
)
511 (member "table" result-params
))
512 (not (listp result
)))
513 (list (list result
)) result
))
514 (funcall cmd body params
)))
515 ;; if non-empty result and :file then write to :file
516 (when (cdr (assoc :file params
))
518 (with-temp-file (cdr (assoc :file params
))
520 (org-babel-format-result
521 result
(cdr (assoc :sep
(nth 2 info
)))))))
522 (setq result
(cdr (assoc :file params
))))
523 (org-babel-insert-result
524 result result-params info new-hash indent lang
)
525 (run-hooks 'org-babel-after-execute-hook
)
527 (setq call-process-region
'org-babel-call-process-region-original
))))))
529 (defun org-babel-expand-body:generic
(body params
&optional var-lines
)
530 "Expand BODY with PARAMS.
531 Expand a block of code with org-babel according to it's header
532 arguments. This generic implementation of body expansion is
533 called for languages which have not defined their own specific
534 org-babel-expand-body:lang function."
535 (mapconcat #'identity
(append var-lines
(list body
)) "\n"))
538 (defun org-babel-expand-src-block (&optional arg info params
)
539 "Expand the current source code block.
540 Expand according to the source code block's header
541 arguments and pop open the results in a preview buffer."
543 (let* ((info (or info
(org-babel-get-src-block-info)))
545 (params (setf (nth 2 info
)
546 (sort (org-babel-merge-params (nth 2 info
) params
)
547 (lambda (el1 el2
) (string< (symbol-name (car el1
))
548 (symbol-name (car el2
)))))))
549 (body (setf (nth 1 info
)
550 (if (and (cdr (assoc :noweb params
))
551 (string= "yes" (cdr (assoc :noweb params
))))
552 (org-babel-expand-noweb-references info
) (nth 1 info
))))
553 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
554 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
557 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
558 (org-babel-expand-body:generic
559 body params
(and (fboundp assignments-cmd
)
560 (funcall assignments-cmd params
))))))
562 nil expanded
(concat "*Org-Babel Preview " (buffer-name) "[ " lang
" ]*"))))
564 (defun org-babel-edit-distance (s1 s2
)
565 "Return the edit (levenshtein) distance between strings S1 S2."
566 (let* ((l1 (length s1
))
568 (dist (map 'vector
(lambda (_) (make-vector (1+ l2
) nil
))
569 (number-sequence 1 (1+ l1
)))))
570 (flet ((in (i j
) (aref (aref dist i
) j
))
571 (mmin (&rest lst
) (apply #'min
(remove nil lst
))))
572 (setf (aref (aref dist
0) 0) 0)
573 (dolist (i (number-sequence 1 l1
))
574 (dolist (j (number-sequence 1 l2
))
575 (setf (aref (aref dist i
) j
)
576 (+ (if (equal (aref s1
(1- i
)) (aref s2
(1- j
))) 0 1)
577 (mmin (in (1- i
) j
) (in i
(1- j
)) (in (1- i
) (1- j
)))))))
581 (defun org-babel-check-src-block ()
582 "Check for misspelled header arguments in the current code block."
584 ;; TODO: report malformed code block
585 ;; TODO: report incompatible combinations of header arguments
586 ;; TODO: report uninitialized variables
587 (let ((too-close 2)) ;; <- control closeness to report potential match
588 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg
)) 1))
589 (and (org-babel-where-is-src-block-head)
590 (org-babel-parse-header-arguments
591 (org-babel-clean-text-properties
592 (match-string 4))))))
593 (dolist (name (mapcar #'symbol-name org-babel-header-arg-names
))
594 (when (and (not (string= header name
))
595 (<= (org-babel-edit-distance header name
) too-close
))
596 (error "supplied header \"%S\" is suspiciously close to \"%S\""
598 (message "No suspicious header arguments found.")))
601 (defun org-babel-insert-header-arg ()
602 "Insert a header argument selecting from lists of common args and values."
604 (let* ((lang (car (org-babel-get-src-block-info 'light
)))
605 (lang-headers (intern (concat "org-babel-header-arg-names:" lang
)))
606 (headers (append (if (boundp lang-headers
)
607 (mapcar (lambda (h) (cons h
:any
))
610 org-babel-common-header-args-w-values
))
611 (arg (org-icompleting-read
614 (lambda (header-spec) (symbol-name (car header-spec
)))
617 (let ((vals (cdr (assoc (intern arg
) headers
))))
623 (read-from-minibuffer "value: "))
627 (let ((arg (org-icompleting-read
629 (cons "default" (mapcar #'symbol-name group
)))))
630 (if (and arg
(not (string= "default" arg
)))
636 (defun org-babel-load-in-session (&optional arg info
)
637 "Load the body of the current source-code block.
638 Evaluate the header arguments for the source block before
639 entering the session. After loading the body this pops open the
642 (let* ((info (or info
(org-babel-get-src-block-info)))
644 (params (nth 2 info
))
645 (body (setf (nth 1 info
)
646 (if (and (cdr (assoc :noweb params
))
647 (string= "yes" (cdr (assoc :noweb params
))))
648 (org-babel-expand-noweb-references info
)
650 (session (cdr (assoc :session params
)))
651 (dir (cdr (assoc :dir params
)))
653 (or (and dir
(file-name-as-directory dir
)) default-directory
))
654 (cmd (intern (concat "org-babel-load-session:" lang
))))
655 (unless (fboundp cmd
)
656 (error "No org-babel-load-session function for %s!" lang
))
657 (pop-to-buffer (funcall cmd session body params
))
661 (defun org-babel-initiate-session (&optional arg info
)
662 "Initiate session for current code block.
663 If called with a prefix argument then resolve any variable
664 references in the header arguments and assign these variables in
665 the session. Copy the body of the code block to the kill ring."
667 (let* ((info (or info
(org-babel-get-src-block-info (not arg
))))
670 (params (nth 2 info
))
671 (session (cdr (assoc :session params
)))
672 (dir (cdr (assoc :dir params
)))
674 (or (and dir
(file-name-as-directory dir
)) default-directory
))
675 (init-cmd (intern (format "org-babel-%s-initiate-session" lang
)))
676 (prep-cmd (intern (concat "org-babel-prep-session:" lang
))))
677 (if (and (stringp session
) (string= session
"none"))
678 (error "This block is not using a session!"))
679 (unless (fboundp init-cmd
)
680 (error "No org-babel-initiate-session function for %s!" lang
))
681 (with-temp-buffer (insert (org-babel-trim body
))
682 (copy-region-as-kill (point-min) (point-max)))
684 (unless (fboundp prep-cmd
)
685 (error "No org-babel-prep-session function for %s!" lang
))
686 (funcall prep-cmd session params
))
687 (funcall init-cmd session params
)))
690 (defun org-babel-switch-to-session (&optional arg info
)
691 "Switch to the session of the current code block.
692 Uses `org-babel-initiate-session' to start the session. If called
693 with a prefix argument then this is passed on to
694 `org-babel-initiate-session'."
696 (pop-to-buffer (org-babel-initiate-session arg info
))
699 (defalias 'org-babel-pop-to-session
'org-babel-switch-to-session
)
702 (defun org-babel-switch-to-session-with-code (&optional arg info
)
703 "Switch to code buffer and display session."
707 (let ((other-window-buffer (window-buffer (next-window))))
708 (set-window-buffer (next-window) (current-buffer))
709 (set-window-buffer (selected-window) other-window-buffer
))
711 (let ((info (org-babel-get-src-block-info))
712 (org-src-window-setup 'reorganize-frame
))
714 (org-babel-switch-to-session arg info
))
718 (defmacro org-babel-do-in-edit-buffer
(&rest body
)
719 "Evaluate BODY in edit buffer if there is a code block at point.
720 Return t if a code block was found at point, nil otherwise."
721 `(let ((org-src-window-setup 'switch-invisibly
))
722 (when (and (org-babel-where-is-src-block-head)
723 (org-edit-src-code nil nil nil
))
724 (unwind-protect (progn ,@body
)
725 (if (org-bound-and-true-p org-edit-src-from-org-mode
)
726 (org-edit-src-exit)))
728 (def-edebug-spec org-babel-do-in-edit-buffer
(body))
730 (defun org-babel-do-key-sequence-in-edit-buffer (key)
731 "Read key sequence and execute the command in edit buffer.
732 Enter a key sequence to be executed in the language major-mode
733 edit buffer. For example, TAB will alter the contents of the
734 Org-mode code block according to the effect of TAB in the
735 language major-mode buffer. For languages that support
736 interactive sessions, this can be used to send code from the Org
737 buffer to the session for evaluation using the native major-mode
738 evaluation mechanisms."
739 (interactive "kEnter key-sequence to execute in edit buffer: ")
740 (org-babel-do-in-edit-buffer
742 (key-binding (or key
(read-key-sequence nil
))))))
744 (defvar org-bracket-link-regexp
)
746 (defun org-babel-open-src-block-result (&optional re-run
)
747 "If `point' is on a src block then open the results of the
748 source code block, otherwise return nil. With optional prefix
749 argument RE-RUN the source-code block is evaluated even if
750 results already exist."
752 (let ((info (org-babel-get-src-block-info)))
755 ;; go to the results, if there aren't any then run the block
756 (goto-char (or (and (not re-run
) (org-babel-where-is-src-block-result))
757 (progn (org-babel-execute-src-block)
758 (org-babel-where-is-src-block-result))))
760 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
762 (if (looking-at org-bracket-link-regexp
)
765 (let ((r (org-babel-format-result
766 (org-babel-read-result) (cdr (assoc :sep
(nth 2 info
))))))
767 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
768 (delete-region (point-min) (point-max))
773 (defmacro org-babel-map-src-blocks
(file &rest body
)
774 "Evaluate BODY forms on each source-block in FILE.
775 If FILE is nil evaluate BODY forms on source blocks in current
776 buffer. During evaluation of BODY the following local variables
777 are set relative to the currently matched code block.
779 full-block ------- string holding the entirety of the code block
780 beg-block -------- point at the beginning of the code block
781 end-block -------- point at the end of the matched code block
782 lang ------------- string holding the language of the code block
783 beg-lang --------- point at the beginning of the lang
784 end-lang --------- point at the end of the lang
785 switches --------- string holding the switches
786 beg-switches ----- point at the beginning of the switches
787 end-switches ----- point at the end of the switches
788 header-args ------ string holding the header-args
789 beg-header-args -- point at the beginning of the header-args
790 end-header-args -- point at the end of the header-args
791 body ------------- string holding the body of the code block
792 beg-body --------- point at the beginning of the body
793 end-body --------- point at the end of the body"
795 (let ((tempvar (make-symbol "file")))
796 `(let* ((,tempvar
,file
)
797 (visited-p (or (null ,tempvar
)
798 (get-file-buffer (expand-file-name ,tempvar
))))
799 (point (point)) to-be-removed
)
800 (save-window-excursion
801 (when ,tempvar
(find-file ,tempvar
))
802 (setq to-be-removed
(current-buffer))
803 (goto-char (point-min))
804 (while (re-search-forward org-babel-src-block-regexp nil t
)
805 (goto-char (match-beginning 0))
806 (let ((full-block (match-string 0))
807 (beg-block (match-beginning 0))
808 (end-block (match-end 0))
809 (lang (match-string 2))
810 (beg-lang (match-beginning 2))
811 (end-lang (match-end 2))
812 (switches (match-string 3))
813 (beg-switches (match-beginning 3))
814 (end-switches (match-end 3))
815 (header-args (match-string 4))
816 (beg-header-args (match-beginning 4))
817 (end-header-args (match-end 4))
818 (body (match-string 5))
819 (beg-body (match-beginning 5))
820 (end-body (match-end 5)))
822 (goto-char end-block
))))
823 (unless visited-p
(kill-buffer to-be-removed
))
825 (def-edebug-spec org-babel-map-src-blocks
(form body
))
828 (defmacro org-babel-map-inline-src-blocks
(file &rest body
)
829 "Evaluate BODY forms on each inline source-block in FILE.
830 If FILE is nil evaluate BODY forms on source blocks in current
833 (let ((tempvar (make-symbol "file")))
834 `(let* ((,tempvar
,file
)
835 (visited-p (or (null ,tempvar
)
836 (get-file-buffer (expand-file-name ,tempvar
))))
837 (point (point)) to-be-removed
)
838 (save-window-excursion
839 (when ,tempvar
(find-file ,tempvar
))
840 (setq to-be-removed
(current-buffer))
841 (goto-char (point-min))
842 (while (re-search-forward org-babel-inline-src-block-regexp nil t
)
843 (goto-char (match-beginning 1))
844 (save-match-data ,@body
)
845 (goto-char (match-end 0))))
846 (unless visited-p
(kill-buffer to-be-removed
))
848 (def-edebug-spec org-babel-map-inline-src-blocks
(form body
))
851 (defun org-babel-execute-buffer (&optional arg
)
852 "Execute source code blocks in a buffer.
853 Call `org-babel-execute-src-block' on every source block in
856 (org-babel-eval-wipe-error-buffer)
857 (org-save-outline-visibility t
858 (org-babel-map-src-blocks nil
859 (org-babel-execute-src-block arg
))
860 (org-babel-map-inline-src-blocks nil
861 (org-babel-execute-src-block arg
))))
864 (defun org-babel-execute-subtree (&optional arg
)
865 "Execute source code blocks in a subtree.
866 Call `org-babel-execute-src-block' on every source block in
867 the current subtree."
871 (org-narrow-to-subtree)
872 (org-babel-execute-buffer arg
)
876 (defun org-babel-sha1-hash (&optional info
)
877 "Generate an sha1 hash based on the value of info."
879 (let ((print-level nil
)
880 (info (or info
(org-babel-get-src-block-info))))
882 (sort (copy-sequence (nth 2 info
))
883 (lambda (a b
) (string< (car a
) (car b
)))))
885 (dolist (p '("replace" "silent" "append" "prepend"))
886 (setq lst
(remove p lst
)))
889 (let ((v (if (and (listp (cdr arg
)) (null (cddr arg
)))
890 (copy-sequence (cdr arg
))
892 (when (and v
(not (and (sequencep v
)
896 ((and (listp v
) ; lists are sorted
897 (member (car arg
) '(:result-params
)))
898 (sort (rm v
) #'string
<))
899 ((and (stringp v
) ; strings are sorted
900 (member (car arg
) '(:results
:exports
)))
901 (mapconcat #'identity
(sort (rm (split-string v
))
905 (when (org-called-interactively-p 'interactive
) (message hash
)) hash
)
906 (let ((it (format "%s-%s"
909 (delq nil
(mapcar (lambda (arg)
910 (let ((normalized (norm arg
)))
912 (format "%S" normalized
))))
917 (defun org-babel-current-result-hash ()
918 "Return the in-buffer hash associated with INFO."
919 (org-babel-where-is-src-block-result)
920 (org-babel-clean-text-properties (match-string 3)))
922 (defun org-babel-hide-hash ()
923 "Hide the hash in the current results line.
924 Only the initial `org-babel-hash-show' characters of the hash
925 will remain visible."
926 (add-to-invisibility-spec '(org-babel-hide-hash . t
))
928 (when (and (re-search-forward org-babel-result-regexp nil t
)
930 (let* ((start (match-beginning 3))
931 (hide-start (+ org-babel-hash-show start
))
933 (hash (match-string 3))
935 (setq ov1
(make-overlay start hide-start
))
936 (setq ov2
(make-overlay hide-start end
))
937 (overlay-put ov2
'invisible
'org-babel-hide-hash
)
938 (overlay-put ov1
'babel-hash hash
)))))
940 (defun org-babel-hide-all-hashes ()
941 "Hide the hash in the current buffer.
942 Only the initial `org-babel-hash-show' characters of each hash
943 will remain visible. This function should be called as part of
944 the `org-mode-hook'."
946 (while (re-search-forward org-babel-result-regexp nil t
)
947 (goto-char (match-beginning 0))
948 (org-babel-hide-hash)
949 (goto-char (match-end 0)))))
950 (add-hook 'org-mode-hook
'org-babel-hide-all-hashes
)
952 (defun org-babel-hash-at-point (&optional point
)
953 "Return the value of the hash at POINT.
954 The hash is also added as the last element of the kill ring.
955 This can be called with C-c C-c."
957 (let ((hash (car (delq nil
(mapcar
958 (lambda (ol) (overlay-get ol
'babel-hash
))
959 (overlays-at (or point
(point))))))))
960 (when hash
(kill-new hash
) (message hash
))))
961 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-hash-at-point
)
963 (defun org-babel-result-hide-spec ()
964 "Hide portions of results lines.
965 Add `org-babel-hide-result' as an invisibility spec for hiding
966 portions of results lines."
967 (add-to-invisibility-spec '(org-babel-hide-result . t
)))
968 (add-hook 'org-mode-hook
'org-babel-result-hide-spec
)
970 (defvar org-babel-hide-result-overlays nil
971 "Overlays hiding results.")
973 (defun org-babel-result-hide-all ()
974 "Fold all results in the current buffer."
976 (org-babel-show-result-all)
978 (while (re-search-forward org-babel-result-regexp nil t
)
979 (save-excursion (goto-char (match-beginning 0))
980 (org-babel-hide-result-toggle-maybe)))))
982 (defun org-babel-show-result-all ()
983 "Unfold all results in the current buffer."
984 (mapc 'delete-overlay org-babel-hide-result-overlays
)
985 (setq org-babel-hide-result-overlays nil
))
988 (defun org-babel-hide-result-toggle-maybe ()
989 "Toggle visibility of result at point."
991 (let ((case-fold-search t
))
993 (beginning-of-line 1)
994 (looking-at org-babel-result-regexp
))
995 (progn (org-babel-hide-result-toggle)
996 t
) ;; to signal that we took action
997 nil
))) ;; to signal that we did not
999 (defun org-babel-hide-result-toggle (&optional force
)
1000 "Toggle the visibility of the current result."
1004 (if (re-search-forward org-babel-result-regexp nil t
)
1005 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
1006 (end (progn (goto-char (- (org-babel-result-end) 1)) (point)))
1008 (if (memq t
(mapcar (lambda (overlay)
1009 (eq (overlay-get overlay
'invisible
)
1010 'org-babel-hide-result
))
1011 (overlays-at start
)))
1012 (if (or (not force
) (eq force
'off
))
1014 (when (member ov org-babel-hide-result-overlays
)
1015 (setq org-babel-hide-result-overlays
1016 (delq ov org-babel-hide-result-overlays
)))
1017 (when (eq (overlay-get ov
'invisible
)
1018 'org-babel-hide-result
)
1019 (delete-overlay ov
)))
1020 (overlays-at start
)))
1021 (setq ov
(make-overlay start end
))
1022 (overlay-put ov
'invisible
'org-babel-hide-result
)
1023 ;; make the block accessible to isearch
1025 ov
'isearch-open-invisible
1027 (when (member ov org-babel-hide-result-overlays
)
1028 (setq org-babel-hide-result-overlays
1029 (delq ov org-babel-hide-result-overlays
)))
1030 (when (eq (overlay-get ov
'invisible
)
1031 'org-babel-hide-result
)
1032 (delete-overlay ov
))))
1033 (push ov org-babel-hide-result-overlays
)))
1034 (error "Not looking at a result line"))))
1036 ;; org-tab-after-check-for-cycling-hook
1037 (add-hook 'org-tab-first-hook
'org-babel-hide-result-toggle-maybe
)
1038 ;; Remove overlays when changing major mode
1039 (add-hook 'org-mode-hook
1040 (lambda () (org-add-hook 'change-major-mode-hook
1041 'org-babel-show-result-all
'append
'local
)))
1043 (defvar org-file-properties
)
1044 (defun org-babel-params-from-properties (&optional lang
)
1045 "Retrieve parameters specified as properties.
1046 Return an association list of any source block params which
1047 may be specified in the properties of the current outline entry."
1052 (lambda (header-arg)
1053 (and (setq val
(org-entry-get (point) header-arg t
))
1054 (cons (intern (concat ":" header-arg
))
1055 (org-babel-read val
))))
1059 org-babel-header-arg-names
1061 (setq sym
(intern (concat "org-babel-header-arg-names:" lang
)))
1062 (and (boundp sym
) (eval sym
))))))))))
1064 (defun org-babel-params-from-buffer ()
1065 "Retrieve per-buffer parameters.
1066 Return an association list of any source block params which
1067 may be specified in the current buffer."
1068 (let (local-properties)
1073 (goto-char (point-min))
1074 (while (re-search-forward
1075 (org-make-options-regexp (list "BABEL" "PROPERTIES")) nil t
)
1076 (setq local-properties
1077 (org-babel-merge-params
1079 (org-babel-parse-header-arguments
1080 (org-match-string-no-properties 2)))))
1081 local-properties
)))))
1083 (defvar org-src-preserve-indentation
)
1084 (defun org-babel-parse-src-block-match ()
1085 "Parse the results from a match of the `org-babel-src-block-regexp'."
1086 (let* ((block-indentation (length (match-string 1)))
1087 (lang (org-babel-clean-text-properties (match-string 2)))
1088 (lang-headers (intern (concat "org-babel-default-header-args:" lang
)))
1089 (switches (match-string 3))
1090 (body (org-babel-clean-text-properties
1091 (let* ((body (match-string 5))
1092 (sub-length (- (length body
) 1)))
1093 (if (and (> sub-length
0)
1094 (string= "\n" (substring body sub-length
)))
1095 (substring body
0 sub-length
)
1097 (preserve-indentation (or org-src-preserve-indentation
1098 (string-match "-i\\>" switches
))))
1100 ;; get block body less properties, protective commas, and indentation
1103 (insert (org-babel-strip-protective-commas body
))
1104 (unless preserve-indentation
(org-do-remove-indentation))
1106 (org-babel-merge-params
1107 org-babel-default-header-args
1108 (org-babel-params-from-buffer)
1109 (org-babel-params-from-properties lang
)
1110 (if (boundp lang-headers
) (eval lang-headers
) nil
)
1111 (org-babel-parse-header-arguments
1112 (org-babel-clean-text-properties (or (match-string 4) ""))))
1114 block-indentation
)))
1116 (defun org-babel-parse-inline-src-block-match ()
1117 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
1118 (let* ((lang (org-babel-clean-text-properties (match-string 2)))
1119 (lang-headers (intern (concat "org-babel-default-header-args:" lang
))))
1121 (org-babel-strip-protective-commas
1122 (org-babel-clean-text-properties (match-string 5)))
1123 (org-babel-merge-params
1124 org-babel-default-inline-header-args
1125 (org-babel-params-from-buffer)
1126 (org-babel-params-from-properties lang
)
1127 (if (boundp lang-headers
) (eval lang-headers
) nil
)
1128 (org-babel-parse-header-arguments
1129 (org-babel-clean-text-properties (or (match-string 4) "")))))))
1131 (defun org-babel-parse-header-arguments (arg-string)
1132 "Parse a string of header arguments returning an alist."
1133 (when (> (length arg-string
) 0)
1138 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1140 (cons (intern (match-string 1 arg
))
1141 (org-babel-read (org-babel-chomp (match-string 2 arg
))))
1142 (cons (intern (org-babel-chomp arg
)) nil
)))
1143 (let ((balance 0) (partial nil
) (lst nil
) (last 0))
1144 (mapc (lambda (ch) ; split on [] balanced instances of [ \t]:
1145 (setq balance
(+ balance
1146 (cond ((equal 91 ch
) 1)
1149 (setq partial
(cons ch partial
))
1150 (when (and (= ch
58) (= balance
0)
1151 (or (= last
32) (= last
9)))
1152 (setq lst
(cons (apply #'string
(nreverse (cddr partial
)))
1154 (setq partial
(list ch
)))
1156 (string-to-list arg-string
))
1157 (nreverse (cons (apply #'string
(nreverse partial
)) lst
)))))))
1159 (defun org-babel-process-params (params)
1160 "Expand variables in PARAMS and add summary parameters."
1161 (let* ((vars-and-names (org-babel-disassemble-tables
1162 (mapcar (lambda (el)
1163 (if (consp (cdr el
))
1164 (cdr el
) (org-babel-ref-parse (cdr el
))))
1165 (org-babel-get-header params
:var
))
1166 (cdr (assoc :hlines params
))
1167 (cdr (assoc :colnames params
))
1168 (cdr (assoc :rownames params
))))
1169 (raw-result (or (cdr (assoc :results params
)) ""))
1170 (result-params (append
1171 (split-string (if (stringp raw-result
)
1174 (cdr (assoc :result-params params
)))))
1176 (mapcar (lambda (var) (cons :var var
)) (car vars-and-names
))
1178 (cons :colname-names
(or (cdr (assoc :colname-names params
))
1179 (cadr vars-and-names
)))
1180 (cons :rowname-names
(or (cdr (assoc :rowname-names params
))
1181 (caddr vars-and-names
)))
1182 (cons :result-params result-params
)
1183 (cons :result-type
(cond ((member "output" result-params
) 'output
)
1184 ((member "value" result-params
) 'value
)
1186 (org-babel-get-header params
:var
'other
))))
1188 ;; row and column names
1189 (defun org-babel-del-hlines (table)
1190 "Remove all 'hlines from TABLE."
1191 (remove 'hline table
))
1193 (defun org-babel-get-colnames (table)
1194 "Return the column names of TABLE.
1195 Return a cons cell, the `car' of which contains the TABLE less
1196 colnames, and the `cdr' of which contains a list of the column
1198 (if (equal 'hline
(nth 1 table
))
1199 (cons (cddr table
) (car table
))
1200 (cons (cdr table
) (car table
))))
1202 (defun org-babel-get-rownames (table)
1203 "Return the row names of TABLE.
1204 Return a cons cell, the `car' of which contains the TABLE less
1205 colnames, and the `cdr' of which contains a list of the column
1206 names. Note: this function removes any hlines in TABLE."
1207 (flet ((trans (table) (apply #'mapcar
* #'list table
)))
1208 (let* ((width (apply 'max
1209 (mapcar (lambda (el) (if (listp el
) (length el
) 0)) table
)))
1210 (table (trans (mapcar (lambda (row)
1211 (if (not (equal row
'hline
))
1215 (setq row
(cons 'hline row
)))
1218 (cons (mapcar (lambda (row) (if (equal (car row
) 'hline
) 'hline row
))
1219 (trans (cdr table
)))
1220 (remove 'hline
(car table
))))))
1222 (defun org-babel-put-colnames (table colnames
)
1223 "Add COLNAMES to TABLE if they exist."
1224 (if colnames
(apply 'list colnames
'hline table
) table
))
1226 (defun org-babel-put-rownames (table rownames
)
1227 "Add ROWNAMES to TABLE if they exist."
1229 (mapcar (lambda (row)
1231 (cons (or (pop rownames
) "") row
)
1235 (defun org-babel-pick-name (names selector
)
1236 "Select one out of an alist of row or column names.
1237 SELECTOR can be either a list of names in which case those names
1238 will be returned directly, or an index into the list NAMES in
1239 which case the indexed names will be return."
1240 (if (listp selector
)
1243 (if (and selector
(symbolp selector
) (not (equal t selector
)))
1244 (cdr (assoc selector names
))
1245 (if (integerp selector
)
1246 (nth (- selector
1) names
)
1247 (cdr (car (last names
))))))))
1249 (defun org-babel-disassemble-tables (vars hlines colnames rownames
)
1250 "Parse tables for further processing.
1251 Process the variables in VARS according to the HLINES,
1252 ROWNAMES and COLNAMES header arguments. Return a list consisting
1253 of the vars, cnames and rnames."
1254 (let (cnames rnames
)
1258 (when (listp (cdr var
))
1259 (when (and (not (equal colnames
"no"))
1260 (or colnames
(and (equal (nth 1 (cdr var
)) 'hline
)
1261 (not (member 'hline
(cddr (cdr var
)))))))
1262 (let ((both (org-babel-get-colnames (cdr var
))))
1263 (setq cnames
(cons (cons (car var
) (cdr both
))
1265 (setq var
(cons (car var
) (car both
)))))
1266 (when (and rownames
(not (equal rownames
"no")))
1267 (let ((both (org-babel-get-rownames (cdr var
))))
1268 (setq rnames
(cons (cons (car var
) (cdr both
))
1270 (setq var
(cons (car var
) (car both
)))))
1271 (when (and hlines
(not (equal hlines
"yes")))
1272 (setq var
(cons (car var
) (org-babel-del-hlines (cdr var
))))))
1277 (defun org-babel-reassemble-table (table colnames rownames
)
1278 "Add column and row names to a table.
1279 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1280 to the table for reinsertion to org-mode."
1283 (if (and colnames
(listp (car table
)) (= (length (car table
))
1285 (org-babel-put-colnames table colnames
) table
))
1286 (if (and rownames
(= (length table
) (length rownames
)))
1287 (org-babel-put-rownames table rownames
) table
))
1290 (defun org-babel-where-is-src-block-head ()
1291 "Find where the current source block begins.
1292 Return the point at the beginning of the current source
1293 block. Specifically at the beginning of the #+BEGIN_SRC line.
1294 If the point is not on a source block then return nil."
1295 (let ((initial (point)) top bottom
)
1297 (save-excursion ;; on a source name line or a #+header line
1298 (beginning-of-line 1)
1299 (and (or (looking-at org-babel-src-name-regexp
)
1300 (looking-at org-babel-multi-line-header-regexp
))
1302 (while (and (forward-line 1)
1303 (looking-at org-babel-multi-line-header-regexp
)))
1304 (looking-at org-babel-src-block-regexp
))
1306 (save-excursion ;; on a #+begin_src line
1307 (beginning-of-line 1)
1308 (and (looking-at org-babel-src-block-regexp
)
1310 (save-excursion ;; inside a src block
1312 (re-search-backward "^[ \t]*#\\+begin_src" nil t
) (setq top
(point))
1313 (re-search-forward "^[ \t]*#\\+end_src" nil t
) (setq bottom
(point))
1314 (< top initial
) (< initial bottom
)
1315 (progn (goto-char top
) (beginning-of-line 1)
1316 (looking-at org-babel-src-block-regexp
))
1320 (defun org-babel-goto-src-block-head ()
1321 "Go to the beginning of the current code block."
1324 (if head
(goto-char head
) (error "not currently in a code block")))
1325 (org-babel-where-is-src-block-head)))
1328 (defun org-babel-goto-named-src-block (name)
1329 "Go to a named source-code block."
1331 (let ((completion-ignore-case t
))
1332 (list (org-icompleting-read "source-block name: "
1333 (org-babel-src-block-names) nil t
))))
1334 (let ((point (org-babel-find-named-block name
)))
1336 ;; taken from `org-open-at-point'
1337 (progn (goto-char point
) (org-show-context))
1338 (message "source-code block '%s' not found in this buffer" name
))))
1340 (defun org-babel-find-named-block (name)
1341 "Find a named source-code block.
1342 Return the location of the source block identified by source
1343 NAME, or nil if no such block exists. Set match data according to
1344 org-babel-named-src-block-regexp."
1346 (let ((case-fold-search t
)
1347 (regexp (org-babel-named-src-block-regexp-for-name name
)) msg
)
1348 (goto-char (point-min))
1349 (when (or (re-search-forward regexp nil t
)
1350 (re-search-backward regexp nil t
))
1351 (match-beginning 0)))))
1353 (defun org-babel-src-block-names (&optional file
)
1354 "Returns the names of source blocks in FILE or the current buffer."
1356 (when file
(find-file file
)) (goto-char (point-min))
1358 (while (re-search-forward org-babel-src-name-w-name-regexp nil t
)
1359 (setq names
(cons (match-string 4) names
)))
1363 (defun org-babel-goto-named-result (name)
1364 "Go to a named result."
1366 (let ((completion-ignore-case t
))
1367 (list (org-icompleting-read "source-block name: "
1368 (org-babel-result-names) nil t
))))
1369 (let ((point (org-babel-find-named-result name
)))
1371 ;; taken from `org-open-at-point'
1372 (progn (goto-char point
) (org-show-context))
1373 (message "result '%s' not found in this buffer" name
))))
1375 (defun org-babel-find-named-result (name)
1376 "Find a named result.
1377 Return the location of the result named NAME in the current
1378 buffer or nil if no such result exists."
1380 (goto-char (point-min))
1381 (when (re-search-forward
1382 (concat org-babel-result-regexp
1383 "[ \t]" (regexp-quote name
) "[ \t\n\f\v\r]") nil t
)
1384 (beginning-of-line 0) (point))))
1386 (defun org-babel-result-names (&optional file
)
1387 "Returns the names of results in FILE or the current buffer."
1389 (when file
(find-file file
)) (goto-char (point-min))
1391 (while (re-search-forward org-babel-result-w-name-regexp nil t
)
1392 (setq names
(cons (match-string 4) names
)))
1396 (defun org-babel-next-src-block (&optional arg
)
1397 "Jump to the next source block.
1398 With optional prefix argument ARG, jump forward ARG many source blocks."
1400 (when (looking-at org-babel-src-block-regexp
) (forward-char 1))
1402 (re-search-forward org-babel-src-block-regexp nil nil
(or arg
1))
1403 (error (error "No further code blocks")))
1404 (goto-char (match-beginning 0)) (org-show-context))
1407 (defun org-babel-previous-src-block (&optional arg
)
1408 "Jump to the previous source block.
1409 With optional prefix argument ARG, jump backward ARG many source blocks."
1412 (re-search-backward org-babel-src-block-regexp nil nil
(or arg
1))
1413 (error (error "No previous code blocks")))
1414 (goto-char (match-beginning 0)) (org-show-context))
1416 (defvar org-babel-load-languages
)
1419 (defun org-babel-mark-block ()
1420 "Mark current src block"
1426 (looking-at org-babel-src-block-regexp
))
1427 (push-mark (match-end 5) nil t
)
1428 (goto-char (match-beginning 5))))
1429 (org-babel-where-is-src-block-head)))
1431 (defun org-babel-demarcate-block (&optional arg
)
1432 "Wrap or split the code in the region or on the point.
1433 When called from inside of a code block the current block is
1434 split. When called from outside of a code block a new code block
1435 is created. In both cases if the region is demarcated and if the
1436 region is not active then the point is demarcated."
1438 (let ((info (org-babel-get-src-block-info 'light
))
1439 (headers (progn (org-babel-where-is-src-block-head)
1441 (stars (concat (make-string (or (org-current-level) 1) ?
*) " ")))
1447 (let ((lang (nth 0 info
))
1448 (indent (make-string (nth 5 info
) ?
)))
1449 (when (string-match "^[[:space:]]*$"
1450 (buffer-substring (point-at-bol)
1452 (delete-region (point-at-bol) (point-at-eol)))
1454 (if (looking-at "^") "" "\n")
1455 indent
"#+end_src\n"
1456 (if arg stars indent
) "\n"
1457 indent
"#+begin_src " lang
1458 (if (> (length headers
) 1)
1459 (concat " " headers
) headers
)
1460 (if (looking-at "[\n\r]")
1462 (concat "\n" (make-string (current-column) ?
)))))))
1463 (move-end-of-line 2))
1464 (sort (if (region-active-p) (list (mark) (point)) (list (point))) #'>))
1465 (let ((start (point))
1466 (lang (org-icompleting-read "Lang: "
1467 (mapcar (lambda (el) (symbol-name (car el
)))
1468 org-babel-load-languages
)))
1469 (body (delete-and-extract-region
1470 (if (region-active-p) (mark) (point)) (point))))
1471 (insert (concat (if (looking-at "^") "" "\n")
1472 (if arg
(concat stars
"\n") "")
1473 "#+begin_src " lang
"\n"
1475 (if (or (= (length body
) 0)
1476 (string-match "[\r\n]$" body
)) "" "\n")
1478 (goto-char start
) (move-end-of-line 1)))))
1480 (defvar org-babel-lob-one-liner-regexp
)
1481 (defvar org-babel-inline-lob-one-liner-regexp
)
1482 (defun org-babel-where-is-src-block-result (&optional insert info hash indent
)
1483 "Find where the current source block results begin.
1484 Return the point at the beginning of the result of the current
1485 source block. Specifically at the beginning of the results line.
1486 If no result exists for this block then create a results line
1487 following the source block."
1489 (let* ((on-lob-line (save-excursion
1490 (beginning-of-line 1)
1491 (looking-at org-babel-lob-one-liner-regexp
)))
1492 (inlinep (when (org-babel-get-inline-src-block-matches)
1494 (name (if on-lob-line
1495 (nth 0 (org-babel-lob-get-info))
1496 (nth 4 (or info
(org-babel-get-src-block-info 'light
)))))
1497 (head (unless on-lob-line
(org-babel-where-is-src-block-head)))
1499 (when head
(goto-char head
))
1501 found
;; was there a result (before we potentially insert one)
1506 ;; - return t if it is found, else return nil
1507 ;; - if it does not need to be rebuilt, then don't set end
1508 ;; - if it does need to be rebuilt then do set end
1509 name
(setq beg
(org-babel-find-named-result name
))
1511 (when (and hash
(not (string= hash
(match-string 3))))
1512 (goto-char beg
) (setq end beg
) ;; beginning of result
1514 (delete-region end
(org-babel-result-end)) nil
)))
1517 ;; - return t if it is found, else return nil
1518 ;; - if it is found, and the hash doesn't match, delete and set end
1519 (or on-lob-line
(re-search-forward "^[ \t]*#\\+end_src" nil t
))
1520 (progn (end-of-line 1)
1521 (if (eobp) (insert "\n") (forward-char 1))
1524 (progn ;; unnamed results line already exists
1525 (re-search-forward "[^ \f\t\n\r\v]" nil t
)
1526 (beginning-of-line 1)
1528 (concat org-babel-result-regexp
"\n")))
1530 ;; must remove and rebuild if hash!=old-hash
1531 (if (and hash
(not (string= hash
(match-string 3))))
1535 end
(org-babel-result-end)))
1536 (setq end nil
)))))))))
1537 (if (and insert end
)
1541 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1546 (org-number-sequence 1 indent
) "")
1549 (when hash
(concat "["hash
"]"))
1551 (when name
(concat " " name
)) "\n"))
1552 (unless beg
(insert "\n") (backward-char))
1553 (beginning-of-line 0)
1554 (if hash
(org-babel-hide-hash))
1558 (defvar org-block-regexp
)
1559 (defun org-babel-read-result ()
1560 "Read the result at `point' into emacs-lisp."
1561 (let ((case-fold-search t
) result-string
)
1563 ((org-at-table-p) (org-babel-read-table))
1564 ((org-at-item-p) (org-babel-read-list))
1565 ((looking-at org-bracket-link-regexp
) (org-babel-read-link))
1566 ((looking-at org-block-regexp
) (org-babel-trim (match-string 4)))
1567 ((looking-at "^[ \t]*: ")
1570 (mapconcat (lambda (line)
1571 (if (and (> (length line
) 1)
1572 (string-match "^[ \t]*: \\(.+\\)" line
))
1573 (match-string 1 line
)
1577 (point) (org-babel-result-end)) "[\r\n]+")
1579 (or (org-babel-number-p result-string
) result-string
))
1580 ((looking-at org-babel-result-regexp
)
1581 (save-excursion (forward-line 1) (org-babel-read-result))))))
1583 (defun org-babel-read-table ()
1584 "Read the table at `point' into emacs-lisp."
1585 (mapcar (lambda (row)
1586 (if (and (symbolp row
) (equal row
'hline
)) row
1587 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
)) row
)))
1588 (org-table-to-lisp)))
1590 (defun org-babel-read-list ()
1591 "Read the list at `point' into emacs-lisp."
1592 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
))
1593 (mapcar #'cadr
(cdr (org-list-parse-list)))))
1595 (defvar org-link-types-re
)
1596 (defun org-babel-read-link ()
1597 "Read the link at `point' into emacs-lisp.
1598 If the path of the link is a file path it is expanded using
1599 `expand-file-name'."
1600 (let* ((case-fold-search t
)
1601 (raw (and (looking-at org-bracket-link-regexp
)
1602 (org-babel-clean-text-properties (match-string 1))))
1603 (type (and (string-match org-link-types-re raw
)
1604 (match-string 1 raw
))))
1606 ((not type
) (expand-file-name raw
))
1607 ((string= type
"file")
1608 (and (string-match "file\\(.*\\):\\(.+\\)" raw
)
1609 (expand-file-name (match-string 2 raw
))))
1612 (defun org-babel-format-result (result &optional sep
)
1613 "Format RESULT for writing to file."
1614 (flet ((echo-res (result)
1615 (if (stringp result
) result
(format "%S" result
))))
1624 (echo-res result
))))
1626 (defun org-babel-insert-result
1627 (result &optional result-params info hash indent lang
)
1628 "Insert RESULT into the current buffer.
1629 By default RESULT is inserted after the end of the
1630 current source block. With optional argument RESULT-PARAMS
1631 controls insertion of results in the org-mode file.
1632 RESULT-PARAMS can take the following values...
1634 replace - (default option) insert results after the source block
1635 replacing any previously inserted results
1637 silent -- no results are inserted
1639 file ---- the results are interpreted as a file path, and are
1640 inserted into the buffer using the Org-mode file syntax
1642 list ---- the results are interpreted as an Org-mode list.
1644 raw ----- results are added directly to the Org-mode file. This
1645 is a good option if you code block will output org-mode
1648 org ----- similar in effect to raw, only the results are wrapped
1649 in an org code block. Similar to the raw option, on
1650 export the results will be interpreted as org-formatted
1651 text, however by wrapping the results in an org code
1652 block they can be replaced upon re-execution of the
1655 html ---- results are added inside of a #+BEGIN_HTML block. This
1656 is a good option if you code block will output html
1659 latex --- results are added inside of a #+BEGIN_LATEX block.
1660 This is a good option if you code block will output
1661 latex formatted text.
1663 code ---- the results are extracted in the syntax of the source
1664 code of the language being evaluated and are added
1665 inside of a #+BEGIN_SRC block with the source-code
1666 language set appropriately. Note this relies on the
1667 optional LANG argument."
1668 (if (stringp result
)
1670 (setq result
(org-babel-clean-text-properties result
))
1671 (when (member "file" result-params
)
1672 (setq result
(org-babel-result-to-file result
))))
1673 (unless (listp result
) (setq result
(format "%S" result
))))
1674 (if (and result-params
(member "silent" result-params
))
1676 (message (replace-regexp-in-string "%" "%%" (format "%S" result
)))
1681 (when (or (org-babel-get-inline-src-block-matches)
1682 (org-babel-get-lob-one-liner-matches))
1683 (goto-char (match-end 0))
1684 (insert (if (listp result
) "\n" " "))
1686 (existing-result (unless inlinep
1687 (org-babel-where-is-src-block-result
1688 t info hash indent
)))
1690 (cdr (assoc :results_switches
(nth 2 info
))))
1692 (when (and (stringp result
) ; ensure results end in a newline
1694 (> (length result
) 0)
1695 (not (or (string-equal (substring result -
1) "\n")
1696 (string-equal (substring result -
1) "\r"))))
1697 (setq result
(concat result
"\n")))
1698 (if (not existing-result
)
1699 (setq beg
(or inlinep
(point)))
1700 (goto-char existing-result
)
1702 (re-search-forward "#" nil t
)
1703 (setq indent
(- (current-column) 1)))
1707 ((member "replace" result-params
)
1708 (delete-region (point) (org-babel-result-end)))
1709 ((member "append" result-params
)
1710 (goto-char (org-babel-result-end)) (setq beg
(point-marker)))
1711 ((member "prepend" result-params
)))) ; already there
1712 (setq results-switches
1713 (if results-switches
(concat " " results-switches
) ""))
1714 ;; insert results based on type
1716 ;; do nothing for an empty result
1717 ((= (length result
) 0))
1718 ;; insert a list if preferred
1719 ((member "list" result-params
)
1722 (org-list-to-generic
1725 (lambda (el) (list nil
(if (stringp el
) el
(format "%S" el
))))
1726 (if (listp result
) result
(list result
))))
1727 '(:splicep nil
:istart
"- " :iend
"\n")))
1729 ;; assume the result is a table if it's not a string
1730 ((not (stringp result
))
1732 (insert (concat (orgtbl-to-orgtbl
1733 (if (or (eq 'hline
(car result
))
1734 (and (listp (car result
))
1735 (listp (cdr (car result
)))))
1736 result
(list result
))
1737 '(:fmt
(lambda (cell) (format "%s" cell
)))) "\n"))
1738 (goto-char beg
) (when (org-at-table-p) (org-table-align)))
1739 ((member "file" result-params
)
1740 (when inlinep
(goto-char inlinep
))
1742 (t (goto-char beg
) (insert result
)))
1743 (when (listp result
) (goto-char (org-table-end)))
1744 (setq end
(point-marker))
1745 ;; possibly wrap result
1746 (flet ((wrap (start finish
)
1747 (goto-char beg
) (insert (concat start
"\n"))
1748 (goto-char end
) (insert (concat finish
"\n"))
1749 (setq end
(point-marker))))
1751 ((member "html" result-params
)
1752 (wrap "#+BEGIN_HTML" "#+END_HTML"))
1753 ((member "latex" result-params
)
1754 (wrap "#+BEGIN_LaTeX" "#+END_LaTeX"))
1755 ((member "code" result-params
)
1756 (wrap (format "#+BEGIN_SRC %s%s" (or lang
"none") results-switches
)
1758 ((member "org" result-params
)
1759 (wrap "#+BEGIN_ORG" "#+END_ORG"))
1760 ((member "raw" result-params
)
1761 (goto-char beg
) (if (org-at-table-p) (org-cycle)))
1762 ((member "wrap" result-params
)
1763 (when (and (stringp result
) (not (member "file" result-params
)))
1764 (org-babel-examplize-region beg end results-switches
))
1765 (wrap "#+BEGIN_RESULT" "#+END_RESULT"))
1766 ((and (stringp result
) (not (member "file" result-params
)))
1767 (org-babel-examplize-region beg end results-switches
)
1768 (setq end
(point)))))
1769 ;; possibly indent the results to match the #+results line
1770 (when (and (not inlinep
) (numberp indent
) indent
(> indent
0)
1771 ;; in this case `table-align' does the work for us
1772 (not (and (listp result
)
1773 (member "append" result-params
))))
1774 (indent-rigidly beg end indent
))))
1775 (if (= (length result
) 0)
1776 (if (member "value" result-params
)
1777 (message "Code block returned no value.")
1778 (message "Code block produced no output."))
1779 (message "Code block evaluation complete."))))
1781 (defun org-babel-remove-result (&optional info
)
1782 "Remove the result of the current source block."
1784 (let ((location (org-babel-where-is-src-block-result nil info
)) start
)
1786 (setq start
(- location
1))
1788 (goto-char location
) (forward-line 1)
1789 (delete-region start
(org-babel-result-end))))))
1791 (defun org-babel-result-end ()
1792 "Return the point at the end of the current set of results"
1795 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
1796 ((org-at-item-p) (let* ((struct (org-list-struct))
1797 (prvs (org-list-prevs-alist struct
)))
1798 (org-list-get-list-end (point-at-bol) struct prvs
)))
1800 (let ((case-fold-search t
)
1801 (blocks-re (regexp-opt
1802 (list "latex" "html" "example" "src" "result" "org"))))
1803 (if (looking-at (concat "[ \t]*#\\+begin_" blocks-re
))
1804 (progn (re-search-forward (concat "[ \t]*#\\+end_" blocks-re
) nil t
)
1806 (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
1810 (defun org-babel-result-to-file (result)
1811 "Convert RESULT into an `org-mode' link.
1812 If the `default-directory' is different from the containing
1813 file's directory then expand relative links."
1814 (flet ((cond-exp (file)
1815 (if (and default-directory
1817 (not (string= (expand-file-name default-directory
)
1819 (file-name-directory buffer-file-name
)))))
1820 (expand-file-name file default-directory
)
1822 (if (stringp result
)
1823 (format "[[file:%s]]" (cond-exp result
))
1824 (when (and (listp result
) (= 2 (length result
))
1825 (stringp (car result
)) (stringp (cadr result
)))
1826 (format "[[file:%s][%s]]" (car result
) (cadr result
))))))
1828 (defun org-babel-examplize-region (beg end
&optional results-switches
)
1829 "Comment out region using the inline '==' or ': ' org example quote."
1831 (flet ((chars-between (b e
) (string-match "[\\S]" (buffer-substring b e
))))
1832 (if (or (chars-between (save-excursion (goto-char beg
) (point-at-bol)) beg
)
1833 (chars-between end
(save-excursion (goto-char end
) (point-at-eol))))
1836 (insert (format "=%s=" (prog1 (buffer-substring beg end
)
1837 (delete-region beg end
)))))
1838 (let ((size (count-lines beg end
)))
1840 (cond ((= size
0)) ; do nothing for an empty result
1841 ((< size org-babel-min-lines-for-block-output
)
1844 (beginning-of-line 1) (insert ": ") (forward-line 1)))
1847 (insert (if results-switches
1848 (format "#+begin_example%s\n" results-switches
)
1849 "#+begin_example\n"))
1850 (if (markerp end
) (goto-char end
) (forward-char (- end beg
)))
1851 (insert "#+end_example\n"))))))))
1853 (defun org-babel-update-block-body (new-body)
1854 "Update the body of the current code block to NEW-BODY."
1855 (if (not (org-babel-where-is-src-block-head))
1856 (error "not in source block")
1858 (replace-match (concat (org-babel-trim new-body
) "\n") nil t nil
5))
1859 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
1861 (defun org-babel-merge-params (&rest plists
)
1862 "Combine all parameter association lists in PLISTS.
1863 Later elements of PLISTS override the values of previous elements.
1864 This takes into account some special considerations for certain
1865 parameters when merging lists."
1866 (let ((results-exclusive-groups
1867 (mapcar (lambda (group) (mapcar #'symbol-name group
))
1868 (cdr (assoc 'results org-babel-common-header-args-w-values
))))
1869 (exports-exclusive-groups
1870 (mapcar (lambda (group) (mapcar #'symbol-name group
))
1871 (cdr (assoc 'exports org-babel-common-header-args-w-values
))))
1873 params results exports tangle noweb cache vars shebang comments padline
)
1874 (flet ((e-merge (exclusive-groups &rest result-params
)
1875 ;; maintain exclusivity of mutually exclusive parameters
1877 (mapc (lambda (new-params)
1878 (mapc (lambda (new-param)
1879 (mapc (lambda (exclusive-group)
1880 (when (member new-param exclusive-group
)
1881 (mapcar (lambda (excluded-param)
1888 (setq output
(org-uniquify
1889 (cons new-param output
))))
1899 (let ((name (if (listp (cdr pair
))
1901 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
1903 (intern (match-string 1 (cdr pair
)))))))
1907 (if (member name
(mapcar #'car vars
))
1911 (unless (equal (car p
) name
) p
))
1914 (list (cons name pair
))))
1915 ;; if no name is given and we already have named variables
1916 ;; then assign to named variables in order
1917 (if (and vars
(nth variable-index vars
))
1918 (prog1 (setf (cddr (nth variable-index vars
))
1919 (concat (symbol-name
1920 (car (nth variable-index vars
)))
1922 (incf variable-index
))
1923 (error "variable \"%s\" must be assigned a default value"
1926 (setq results
(e-merge results-exclusive-groups
1929 (let ((r (cdr pair
)))
1930 (if (stringp r
) r
(eval r
)))))))
1933 (setq results
(e-merge results-exclusive-groups
1935 (unless (or (member "both" exports
)
1936 (member "none" exports
)
1937 (member "code" exports
))
1938 (setq exports
(e-merge exports-exclusive-groups
1939 exports
'("results"))))
1940 (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))
1942 (setq exports
(e-merge exports-exclusive-groups
1943 exports
(split-string (cdr pair
)))))
1944 (:tangle
;; take the latest -- always overwrite
1945 (setq tangle
(or (list (cdr pair
)) tangle
)))
1947 (setq noweb
(e-merge '(("yes" "no" "tangle")) noweb
1948 (split-string (or (cdr pair
) "")))))
1950 (setq cache
(e-merge '(("yes" "no")) cache
1951 (split-string (or (cdr pair
) "")))))
1953 (setq padline
(e-merge '(("yes" "no")) padline
1954 (split-string (or (cdr pair
) "")))))
1955 (:shebang
;; take the latest -- always overwrite
1956 (setq shebang
(or (list (cdr pair
)) shebang
)))
1958 (setq comments
(e-merge '(("yes" "no")) comments
1959 (split-string (or (cdr pair
) "")))))
1960 (t ;; replace: this covers e.g. :session
1961 (setq params
(cons pair
(assq-delete-all (car pair
) params
))))))
1964 (setq vars
(reverse vars
))
1965 (while vars
(setq params
(cons (cons :var
(cddr (pop vars
))) params
)))
1968 (let ((key (intern (concat ":" (symbol-name hd
))))
1970 (setf params
(cons (cons key
(mapconcat 'identity val
" ")) params
))))
1971 '(results exports tangle noweb padline cache shebang comments
))
1974 (defun org-babel-expand-noweb-references (&optional info parent-buffer
)
1975 "Expand Noweb references in the body of the current source code block.
1977 For example the following reference would be replaced with the
1978 body of the source-code block named 'example-block'.
1982 Note that any text preceding the <<foo>> construct on a line will
1983 be interposed between the lines of the replacement text. So for
1984 example if <<foo>> is placed behind a comment, then the entire
1985 replacement text will also be commented.
1987 This function must be called from inside of the buffer containing
1988 the source-code block which holds BODY.
1990 In addition the following syntax can be used to insert the
1991 results of evaluating the source-code block named 'example-block'.
1995 Any optional arguments can be passed to example-block by placing
1996 the arguments inside the parenthesis following the convention
1997 defined by `org-babel-lob'. For example
1999 <<example-block(a=9)>>
2001 would set the value of argument \"a\" equal to \"9\". Note that
2002 these arguments are not evaluated in the current source-code
2003 block but are passed literally to the \"example-block\"."
2004 (let* ((parent-buffer (or parent-buffer
(current-buffer)))
2005 (info (or info
(org-babel-get-src-block-info)))
2008 (comment (string= "noweb" (cdr (assoc :comments
(nth 2 info
)))))
2009 (new-body "") index source-name evaluate prefix blocks-in-buffer
)
2010 (flet ((nb-add (text) (setq new-body
(concat new-body text
)))
2013 (funcall (intern (concat lang
"-mode")))
2014 (comment-region (point) (progn (insert text
) (point)))
2015 (org-babel-trim (buffer-string))))
2016 (blocks () ;; return the info lists of all blocks in this buffer
2020 (org-babel-map-src-blocks nil
2021 (setq infos
(cons (org-babel-get-src-block-info 'light
)
2025 (insert body
) (goto-char (point-min))
2026 (setq index
(point))
2027 (while (and (re-search-forward "<<\\(.+?\\)>>" nil t
))
2028 (save-match-data (setf source-name
(match-string 1)))
2029 (save-match-data (setq evaluate
(string-match "\(.*\)" source-name
)))
2032 (buffer-substring (match-beginning 0)
2034 (beginning-of-line 1) (point)))))
2035 ;; add interval to new-body (removing noweb reference)
2036 (goto-char (match-beginning 0))
2037 (nb-add (buffer-substring index
(point)))
2038 (goto-char (match-end 0))
2039 (setq index
(point))
2041 (with-current-buffer parent-buffer
2042 (mapconcat ;; interpose PREFIX between every line
2046 (let ((raw (org-babel-ref-resolve source-name
)))
2047 (if (stringp raw
) raw
(format "%S" raw
)))
2049 ;; retrieve from the library of babel
2050 (nth 2 (assoc (intern source-name
)
2051 org-babel-library-of-babel
))
2052 ;; return the contents of headlines literally
2054 (when (org-babel-ref-goto-headline-id source-name
)
2055 (org-babel-ref-headline-body)))
2056 ;; find the expansion of reference in this buffer
2059 (when (string= source-name
2060 (or (cdr (assoc :noweb-ref
(nth 2 i
)))
2062 (let ((body (org-babel-expand-noweb-references i
)))
2065 (concat (c-wrap (car cs
)) "\n"
2066 body
"\n" (c-wrap (cadr cs
))))
2067 (org-babel-tangle-comment-links i
))
2069 (or blocks-in-buffer
2070 (setq blocks-in-buffer
(blocks)))
2072 ;; possibly raise an error if named block doesn't exist
2073 (if (member lang org-babel-noweb-error-langs
)
2075 "<<" source-name
">> "
2076 "could not be resolved (see "
2077 "`org-babel-noweb-error-langs')"))
2079 "[\n\r]") (concat "\n" prefix
)))))
2080 (nb-add (buffer-substring index
(point-max)))))
2083 (defun org-babel-clean-text-properties (text)
2084 "Strip all properties from text return."
2086 (set-text-properties 0 (length text
) nil text
) text
))
2088 (defun org-babel-strip-protective-commas (body)
2089 "Strip protective commas from bodies of source blocks."
2091 (replace-regexp-in-string "^,#" "#" body
)))
2093 (defun org-babel-script-escape (str &optional force
)
2094 "Safely convert tables into elisp lists."
2095 (let (in-single in-double out
)
2096 ((lambda (escaped) (condition-case nil
(org-babel-read escaped
) (error escaped
)))
2100 (or (and (string-equal "[" (substring str
0 1))
2101 (string-equal "]" (substring str -
1)))
2102 (and (string-equal "{" (substring str
0 1))
2103 (string-equal "}" (substring str -
1)))
2104 (and (string-equal "(" (substring str
0 1))
2105 (string-equal ")" (substring str -
1))))))
2115 (91 (if (or in-double in-single
) ; [
2118 (93 (if (or in-double in-single
) ; ]
2121 (123 (if (or in-double in-single
) ; {
2124 (125 (if (or in-double in-single
) ; }
2127 (44 (if (or in-double in-single
) ; ,
2128 (cons 44 out
) (cons 32 out
)))
2129 (39 (if in-double
; '
2131 (setq in-single
(not in-single
)) (cons 34 out
)))
2132 (34 (if in-single
; "
2133 (append (list 34 32) out
)
2134 (setq in-double
(not in-double
)) (cons 34 out
)))
2135 (t (cons ch out
)))))
2136 (string-to-list str
))
2137 (apply #'string
(reverse out
)))))
2140 (defun org-babel-read (cell &optional inhibit-lisp-eval
)
2141 "Convert the string value of CELL to a number if appropriate.
2142 Otherwise if cell looks like lisp (meaning it starts with a
2143 \"(\", \"'\", \"`\" or a \"[\") then read it as lisp, otherwise
2144 return it unmodified as a string. Optional argument NO-LISP-EVAL
2145 inhibits lisp evaluation for situations in which is it not
2147 (if (and (stringp cell
) (not (equal cell
"")))
2148 (or (org-babel-number-p cell
)
2149 (if (and (not inhibit-lisp-eval
)
2150 (member (substring cell
0 1) '("(" "'" "`" "[")))
2152 (if (string= (substring cell
0 1) "\"")
2154 (progn (set-text-properties 0 (length cell
) nil cell
) cell
))))
2157 (defun org-babel-number-p (string)
2158 "If STRING represents a number return it's value."
2159 (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string
)
2160 (= (length (substring string
(match-beginning 0)
2163 (string-to-number string
)))
2165 (defun org-babel-import-elisp-from-file (file-name &optional separator
)
2166 "Read the results located at FILE-NAME into an elisp table.
2167 If the table is trivial, then return it as a scalar."
2169 (save-window-excursion
2173 (org-table-import file-name separator
)
2174 (delete-file file-name
)
2175 (setq result
(mapcar (lambda (row)
2176 (mapcar #'org-babel-string-read row
))
2177 (org-table-to-lisp))))
2179 (if (null (cdr result
)) ;; if result is trivial vector, then scalarize it
2180 (if (consp (car result
))
2181 (if (null (cdr (car result
)))
2187 (defun org-babel-string-read (cell)
2188 "Strip nested \"s from around strings."
2189 (org-babel-read (or (and (stringp cell
)
2190 (string-match "\\\"\\(.+\\)\\\"" cell
)
2191 (match-string 1 cell
))
2194 (defun org-babel-reverse-string (string)
2195 "Return the reverse of STRING."
2196 (apply 'string
(reverse (string-to-list string
))))
2198 (defun org-babel-chomp (string &optional regexp
)
2199 "Strip trailing spaces and carriage returns from STRING.
2200 Default regexp used is \"[ \f\t\n\r\v]\" but can be
2201 overwritten by specifying a regexp as a second argument."
2202 (let ((regexp (or regexp
"[ \f\t\n\r\v]")))
2203 (while (and (> (length string
) 0)
2204 (string-match regexp
(substring string -
1)))
2205 (setq string
(substring string
0 -
1)))
2208 (defun org-babel-trim (string &optional regexp
)
2209 "Strip leading and trailing spaces and carriage returns from STRING.
2210 Like `org-babel-chomp' only it runs on both the front and back
2212 (org-babel-chomp (org-babel-reverse-string
2213 (org-babel-chomp (org-babel-reverse-string string
) regexp
))
2216 (defvar org-babel-org-babel-call-process-region-original nil
)
2217 (defun org-babel-tramp-handle-call-process-region
2218 (start end program
&optional delete buffer display
&rest args
)
2219 "Use tramp to handle call-process-region.
2220 Fixes a bug in `tramp-handle-call-process-region'."
2221 (if (and (featurep 'tramp
) (file-remote-p default-directory
))
2222 (let ((tmpfile (tramp-compat-make-temp-file "")))
2223 (write-region start end tmpfile
)
2224 (when delete
(delete-region start end
))
2226 ;; (apply 'call-process program tmpfile buffer display args)
2228 (apply 'process-file program tmpfile buffer display args
)
2229 (delete-file tmpfile
)))
2230 ;; org-babel-call-process-region-original is the original emacs
2231 ;; definition. It is in scope from the let binding in
2232 ;; org-babel-execute-src-block
2233 (apply org-babel-call-process-region-original
2234 start end program delete buffer display args
)))
2236 (defun org-babel-local-file-name (file)
2237 "Return the local name component of FILE."
2238 (if (file-remote-p file
)
2240 (with-parsed-tramp-file-name file nil
2244 (defun org-babel-process-file-name (name &optional no-quote-p
)
2245 "Prepare NAME to be used in an external process.
2246 If NAME specifies a remote location, the remote portion of the
2247 name is removed, since in that case the process will be executing
2248 remotely. The file name is then processed by
2249 `expand-file-name'. Unless second argument NO-QUOTE-P is non-nil,
2250 the file name is additionally processed by
2251 `shell-quote-argument'"
2252 ((lambda (f) (if no-quote-p f
(shell-quote-argument f
)))
2253 (expand-file-name (org-babel-local-file-name name
))))
2255 (defvar org-babel-temporary-directory
)
2256 (unless (or noninteractive
(boundp 'org-babel-temporary-directory
))
2257 (defvar org-babel-temporary-directory
2258 (or (and (boundp 'org-babel-temporary-directory
)
2259 (file-exists-p org-babel-temporary-directory
)
2260 org-babel-temporary-directory
)
2261 (make-temp-file "babel-" t
))
2262 "Directory to hold temporary files created to execute code blocks.
2263 Used by `org-babel-temp-file'. This directory will be removed on
2266 (defun org-babel-temp-file (prefix &optional suffix
)
2267 "Create a temporary file in the `org-babel-temporary-directory'.
2268 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2269 value of `temporary-file-directory' temporarily set to the value
2270 of `org-babel-temporary-directory'."
2271 (if (file-remote-p default-directory
)
2273 (concat (file-remote-p default-directory
)
2275 prefix temporary-file-directory
)
2277 (let ((temporary-file-directory
2278 (or (and (boundp 'org-babel-temporary-directory
)
2279 (file-exists-p org-babel-temporary-directory
)
2280 org-babel-temporary-directory
)
2281 temporary-file-directory
)))
2282 (make-temp-file prefix nil suffix
))))
2284 (defun org-babel-remove-temporary-directory ()
2285 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2286 (when (and (boundp 'org-babel-temporary-directory
)
2287 (file-exists-p org-babel-temporary-directory
))
2288 ;; taken from `delete-directory' in files.el
2291 (mapc (lambda (file)
2292 ;; This test is equivalent to
2293 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2294 ;; but more efficient
2295 (if (eq t
(car (file-attributes file
)))
2296 (delete-directory file
)
2297 (delete-file file
)))
2298 ;; We do not want to delete "." and "..".
2299 (directory-files org-babel-temporary-directory
'full
2300 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2301 (delete-directory org-babel-temporary-directory
))
2303 (message "Failed to remove temporary Org-babel directory %s"
2304 (if (boundp 'org-babel-temporary-directory
)
2305 org-babel-temporary-directory
2306 "[directory not defined]"))))))
2308 (add-hook 'kill-emacs-hook
'org-babel-remove-temporary-directory
)