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-babel-map-call-lines
"ob-lob" (file &rest body
))
75 (declare-function org-number-sequence
"org-compat" (from &optional to inc
))
76 (declare-function org-at-item-p
"org-list" ())
77 (declare-function org-list-parse-list
"org-list" (&optional delete
))
78 (declare-function org-list-to-generic
"org-list" (LIST PARAMS
))
79 (declare-function org-list-struct
"org-list" ())
80 (declare-function org-list-prevs-alist
"org-list" (struct))
81 (declare-function org-list-get-list-end
"org-list" (item struct prevs
))
83 (defgroup org-babel nil
84 "Code block evaluation and management in `org-mode' documents."
88 (defcustom org-confirm-babel-evaluate t
89 "Confirm before evaluation.
90 Require confirmation before interactively evaluating code
91 blocks in Org-mode buffers. The default value of this variable
92 is t, meaning confirmation is required for any code block
93 evaluation. This variable can be set to nil to inhibit any
94 future confirmation requests. This variable can also be set to a
95 function which takes two arguments the language of the code block
96 and the body of the code block. Such a function should then
97 return a non-nil value if the user should be prompted for
98 execution or nil if no prompt is required.
100 Warning: Disabling confirmation may result in accidental
101 evaluation of potentially harmful code. It may be advisable
102 remove code block execution from C-c C-c as further protection
103 against accidental code block evaluation. The
104 `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
105 remove code block execution from the C-c C-c keybinding."
107 :type
'(choice boolean function
))
108 ;; don't allow this variable to be changed through file settings
109 (put 'org-confirm-babel-evaluate
'safe-local-variable
(lambda (x) (eq x t
)))
111 (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
112 "Remove code block evaluation from the C-c C-c key binding."
116 (defvar org-babel-src-name-regexp
117 "^[ \t]*#\\+name:[ \t]*"
118 "Regular expression used to match a source name line.")
120 (defvar org-babel-multi-line-header-regexp
121 "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
122 "Regular expression used to match multi-line header arguments.")
124 (defvar org-babel-src-name-w-name-regexp
125 (concat org-babel-src-name-regexp
127 org-babel-multi-line-header-regexp
129 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)")
130 "Regular expression matching source name lines with a name.")
132 (defvar org-babel-src-block-regexp
134 ;; (1) indentation (2) lang
135 "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
137 "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
138 ;; (4) header arguments
141 "\\([^\000]*?\n\\)?[ \t]*#\\+end_src")
142 "Regexp used to identify code blocks.")
144 (defvar org-babel-inline-src-block-regexp
146 ;; (1) replacement target (2) lang
147 "\\(?:^\\|[^-[:alnum:]]\\)\\(src_\\([^ \f\t\n\r\v]+\\)"
148 ;; (3,4) (unused, headers)
149 "\\(\\|\\[\\(.*?\\)\\]\\)"
151 "{\\([^\f\n\r\v]+?\\)}\\)")
152 "Regexp used to identify inline src-blocks.")
154 (defun org-babel-get-header (params key
&optional others
)
155 "Select only header argument of type KEY from a list.
156 Optional argument OTHERS indicates that only the header that do
157 not match KEY should be returned."
160 (lambda (p) (when (funcall (if others
#'not
#'identity
) (eq (car p
) key
)) p
))
163 (defun org-babel-get-inline-src-block-matches()
164 "Set match data if within body of an inline source block.
165 Returns non-nil if match-data set"
166 (let ((src-at-0-p (save-excursion
167 (beginning-of-line 1)
168 (string= "src" (thing-at-point 'word
))))
169 (first-line-p (= 1 (line-number-at-pos)))
171 (let ((search-for (cond ((and src-at-0-p first-line-p
"src_"))
172 (first-line-p "[ \t]src_")
173 (t "[ \f\t\n\r\v]src_")))
174 (lower-limit (if first-line-p
176 (- (point-at-bol) 1))))
178 (when (or (and src-at-0-p
(bobp))
179 (and (re-search-forward "}" (point-at-eol) t
)
180 (re-search-backward search-for lower-limit t
)
182 (when (looking-at org-babel-inline-src-block-regexp
)
185 (defvar org-babel-inline-lob-one-liner-regexp
)
186 (defun org-babel-get-lob-one-liner-matches()
187 "Set match data if on line of an lob one liner.
188 Returns non-nil if match-data set"
190 (unless (= (point) (point-at-bol)) ;; move before inline block
191 (re-search-backward "[ \f\t\n\r\v]" nil t
))
192 (if (looking-at org-babel-inline-lob-one-liner-regexp
)
196 (defun org-babel-get-src-block-info (&optional light
)
197 "Get information on the current source block.
199 Optional argument LIGHT does not resolve remote variable
200 references; a process which could likely result in the execution
201 of other code blocks.
204 (language body header-arguments-alist switches name indent)."
205 (let ((case-fold-search t
) head info name indent
)
207 (if (setq head
(org-babel-where-is-src-block-head))
210 (setq info
(org-babel-parse-src-block-match))
211 (setq indent
(car (last info
)))
212 (setq info
(butlast info
))
213 (while (and (forward-line -
1)
214 (looking-at org-babel-multi-line-header-regexp
))
216 (org-babel-merge-params
218 (org-babel-parse-header-arguments (match-string 1)))))
219 (when (looking-at org-babel-src-name-w-name-regexp
)
220 (setq name
(org-babel-clean-text-properties (match-string 3)))
221 (when (and (match-string 5) (> (length (match-string 5)) 0))
222 (setf (nth 2 info
) ;; merge functional-syntax vars and header-args
223 (org-babel-merge-params
225 (lambda (ref) (cons :var ref
))
227 (lambda (var) ;; check that each variable is initialized
228 (if (string-match ".+=.+" var
)
231 "variable \"%s\"%s must be assigned a default value"
232 var
(if name
(format " in block \"%s\"" name
) ""))))
233 (org-babel-ref-split-args (match-string 5))))
235 ;; inline source block
236 (when (org-babel-get-inline-src-block-matches)
237 (setq info
(org-babel-parse-inline-src-block-match))))
238 ;; resolve variable references and add summary parameters
239 (when (and info
(not light
))
240 (setf (nth 2 info
) (org-babel-process-params (nth 2 info
))))
241 (when info
(append info
(list name indent
)))))
243 (defun org-babel-confirm-evaluate (info)
244 "Confirm evaluation of the code block INFO.
245 This behavior can be suppressed by setting the value of
246 `org-confirm-babel-evaluate' to nil, in which case all future
247 interactive code block evaluations will proceed without any
248 confirmation from the user.
250 Note disabling confirmation may result in accidental evaluation
251 of potentially harmful code."
252 (let* ((eval (or (cdr (assoc :eval
(nth 2 info
)))
253 (when (assoc :noeval
(nth 2 info
)) "no")))
254 (query (cond ((equal eval
"query") t
)
255 ((functionp org-confirm-babel-evaluate
)
256 (funcall org-confirm-babel-evaluate
257 (nth 0 info
) (nth 1 info
)))
258 (t org-confirm-babel-evaluate
))))
259 (if (or (equal eval
"never") (equal eval
"no")
262 (format "Evaluate this%scode block%son your system? "
263 (if info
(format " %s " (nth 0 info
)) " ")
265 (format " (%s) " (nth 4 info
)) " "))))))
266 (prog1 nil
(message "Evaluation %s"
267 (if (or (equal eval
"never") (equal eval
"no"))
268 "Disabled" "Aborted")))
272 (defun org-babel-execute-safely-maybe ()
273 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
274 (org-babel-execute-maybe)))
276 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-execute-safely-maybe
)
279 (defun org-babel-execute-maybe ()
281 (or (org-babel-execute-src-block-maybe)
282 (org-babel-lob-execute-maybe)))
284 (defun org-babel-execute-src-block-maybe ()
285 "Conditionally execute a source block.
286 Detect if this is context for a Babel src-block and if so
287 then run `org-babel-execute-src-block'."
289 (let ((info (org-babel-get-src-block-info)))
291 (progn (org-babel-eval-wipe-error-buffer)
292 (org-babel-execute-src-block current-prefix-arg info
) t
) nil
)))
295 (defun org-babel-view-src-block-info ()
296 "Display information on the current source block.
297 This includes header arguments, language and name, and is largely
298 a window into the `org-babel-get-src-block-info' function."
300 (let ((info (org-babel-get-src-block-info 'light
)))
301 (flet ((full (it) (> (length it
) 0))
302 (printf (fmt &rest args
) (princ (apply #'format fmt args
))))
304 (with-help-window (help-buffer)
305 (let ((name (nth 4 info
))
307 (switches (nth 3 info
))
308 (header-args (nth 2 info
)))
309 (when name
(printf "Name: %s\n" name
))
310 (when lang
(printf "Lang: %s\n" lang
))
311 (when (full switches
) (printf "Switches: %s\n" switches
))
312 (printf "Header Arguments:\n")
313 (dolist (pair (sort header-args
314 (lambda (a b
) (string< (symbol-name (car a
))
315 (symbol-name (car b
))))))
316 (when (full (cdr pair
))
317 (printf "\t%S%s\t%s\n"
319 (if (> (length (format "%S" (car pair
))) 7) "" "\t")
323 (defun org-babel-expand-src-block-maybe ()
324 "Conditionally expand a source block.
325 Detect if this is context for a org-babel src-block and if so
326 then run `org-babel-expand-src-block'."
328 (let ((info (org-babel-get-src-block-info)))
330 (progn (org-babel-expand-src-block current-prefix-arg info
) t
)
334 (defun org-babel-load-in-session-maybe ()
335 "Conditionally load a source block in a session.
336 Detect if this is context for a org-babel src-block and if so
337 then run `org-babel-load-in-session'."
339 (let ((info (org-babel-get-src-block-info)))
341 (progn (org-babel-load-in-session current-prefix-arg info
) t
)
344 (add-hook 'org-metaup-hook
'org-babel-load-in-session-maybe
)
347 (defun org-babel-pop-to-session-maybe ()
348 "Conditionally pop to a session.
349 Detect if this is context for a org-babel src-block and if so
350 then run `org-babel-pop-to-session'."
352 (let ((info (org-babel-get-src-block-info)))
353 (if info
(progn (org-babel-pop-to-session current-prefix-arg info
) t
) nil
)))
355 (add-hook 'org-metadown-hook
'org-babel-pop-to-session-maybe
)
357 (defconst org-babel-common-header-args-w-values
358 '((cache .
((no yes
)))
360 (colnames .
((nil no yes
)))
361 (comments .
((no link yes org both noweb
)))
363 (eval .
((never query
)))
364 (exports .
((code results both none
)))
366 (hlines .
((no yes
)))
367 (mkdirp .
((yes no
)))
370 (noweb .
((yes no tangle
)))
372 (padline .
((yes no
)))
373 (results .
((file list vector table scalar verbatim
)
374 (raw org html latex code pp wrap
)
375 (replace silent append prepend
)
377 (rownames .
((no yes
)))
381 (tangle .
((tangle yes no
:any
)))
384 (defconst org-babel-header-arg-names
385 (mapcar #'car org-babel-common-header-args-w-values
)
386 "Common header arguments used by org-babel.
387 Note that individual languages may define their own language
388 specific header arguments as well.")
390 (defvar org-babel-default-header-args
391 '((:session .
"none") (:results .
"replace") (:exports .
"code")
392 (:cache .
"no") (:noweb .
"no") (:hlines .
"no") (:tangle .
"no")
393 (:padnewline .
"yes"))
394 "Default arguments to use when evaluating a source block.")
396 (defvar org-babel-default-inline-header-args
397 '((:session .
"none") (:results .
"replace") (:exports .
"results"))
398 "Default arguments to use when evaluating an inline source block.")
400 (defvar org-babel-data-names
'("TBLNAME" "RESULTS" "NAME"))
402 (defvar org-babel-result-regexp
403 (concat "^[ \t]*#\\+"
404 (regexp-opt org-babel-data-names t
)
405 "\\(\\[\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*")
406 "Regular expression used to match result lines.
407 If the results are associated with a hash key then the hash will
408 be saved in the second match data.")
410 (defvar org-babel-result-w-name-regexp
411 (concat org-babel-result-regexp
412 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
414 (defvar org-babel-min-lines-for-block-output
10
415 "The minimum number of lines for block output.
416 If number of lines of output is equal to or exceeds this
417 value, the output is placed in a #+begin_example...#+end_example
418 block. Otherwise the output is marked as literal by inserting
419 colons at the starts of the lines. This variable only takes
420 effect if the :results output option is in effect.")
422 (defvar org-babel-noweb-error-langs nil
423 "Languages for which Babel will raise literate programming errors.
424 List of languages for which errors should be raised when the
425 source code block satisfying a noweb reference in this language
426 can not be resolved.")
428 (defvar org-babel-hash-show
4
429 "Number of initial characters to show of a hidden results hash.")
431 (defvar org-babel-after-execute-hook nil
432 "Hook for functions to be called after `org-babel-execute-src-block'")
433 (defun org-babel-named-src-block-regexp-for-name (name)
434 "This generates a regexp used to match a src block named NAME."
435 (concat org-babel-src-name-regexp
(regexp-quote name
) "[ \t\n]*"
436 (substring org-babel-src-block-regexp
1)))
439 (defvar call-process-region
)
442 (defun org-babel-execute-src-block (&optional arg info params
)
443 "Execute the current source code block.
444 Insert the results of execution into the buffer. Source code
445 execution and the collection and formatting of results can be
446 controlled through a variety of header arguments.
448 With prefix argument ARG, force re-execution even if a an
449 existing result cached in the buffer would otherwise have been
452 Optionally supply a value for INFO in the form returned by
453 `org-babel-get-src-block-info'.
455 Optionally supply a value for PARAMS which will be merged with
456 the header arguments specified at the front of the source code
459 (let ((info (or info
(org-babel-get-src-block-info))))
460 (when (org-babel-confirm-evaluate info
)
461 (let* ((lang (nth 0 info
))
463 (org-babel-process-params
464 (org-babel-merge-params (nth 2 info
) params
))
466 (cache?
(and (not arg
) (cdr (assoc :cache params
))
467 (string= "yes" (cdr (assoc :cache params
)))))
468 (result-params (cdr (assoc :result-params params
)))
469 (new-hash (when cache?
(org-babel-sha1-hash info
)))
470 (old-hash (when cache?
(org-babel-current-result-hash)))
471 (body (setf (nth 1 info
)
472 (let ((noweb (cdr (assoc :noweb params
))))
474 (or (string= "yes" noweb
)
475 (string= "tangle" noweb
)))
476 (org-babel-expand-noweb-references info
)
478 (dir (cdr (assoc :dir params
)))
480 (or (and dir
(file-name-as-directory dir
)) default-directory
))
481 (org-babel-call-process-region-original
482 (if (boundp 'org-babel-call-process-region-original
)
483 org-babel-call-process-region-original
484 (symbol-function 'call-process-region
)))
485 (indent (car (last info
)))
488 (flet ((call-process-region (&rest args
)
489 (apply 'org-babel-tramp-handle-call-process-region args
)))
490 (flet ((lang-check (f)
491 (let ((f (intern (concat "org-babel-execute:" f
))))
492 (when (fboundp f
) f
))))
494 (or (lang-check lang
)
495 (lang-check (symbol-name
496 (cdr (assoc lang org-src-lang-modes
))))
497 (error "No org-babel-execute function for %s!" lang
))))
498 (if (and (not arg
) new-hash
(equal new-hash old-hash
))
499 (save-excursion ;; return cached result
500 (goto-char (org-babel-where-is-src-block-result nil info
))
501 (end-of-line 1) (forward-char 1)
502 (setq result
(org-babel-read-result))
503 (message (replace-regexp-in-string
504 "%" "%%" (format "%S" result
))) result
)
505 (message "executing %s code block%s..."
507 (if (nth 4 info
) (format " (%s)" (nth 4 info
)) ""))
510 (if (and (eq (cdr (assoc :result-type params
)) 'value
)
511 (or (member "vector" result-params
)
512 (member "table" result-params
))
513 (not (listp result
)))
514 (list (list result
)) result
))
515 (funcall cmd body params
)))
516 ;; if non-empty result and :file then write to :file
517 (when (cdr (assoc :file params
))
519 (with-temp-file (cdr (assoc :file params
))
521 (org-babel-format-result
522 result
(cdr (assoc :sep
(nth 2 info
)))))))
523 (setq result
(cdr (assoc :file params
))))
524 (org-babel-insert-result
525 result result-params info new-hash indent lang
)
526 (run-hooks 'org-babel-after-execute-hook
)
528 (setq call-process-region
'org-babel-call-process-region-original
))))))
530 (defun org-babel-expand-body:generic
(body params
&optional var-lines
)
531 "Expand BODY with PARAMS.
532 Expand a block of code with org-babel according to it's header
533 arguments. This generic implementation of body expansion is
534 called for languages which have not defined their own specific
535 org-babel-expand-body:lang function."
536 (mapconcat #'identity
(append var-lines
(list body
)) "\n"))
539 (defun org-babel-expand-src-block (&optional arg info params
)
540 "Expand the current source code block.
541 Expand according to the source code block's header
542 arguments and pop open the results in a preview buffer."
544 (let* ((info (or info
(org-babel-get-src-block-info)))
546 (params (setf (nth 2 info
)
547 (sort (org-babel-merge-params (nth 2 info
) params
)
548 (lambda (el1 el2
) (string< (symbol-name (car el1
))
549 (symbol-name (car el2
)))))))
550 (body (setf (nth 1 info
)
551 (if (and (cdr (assoc :noweb params
))
552 (string= "yes" (cdr (assoc :noweb params
))))
553 (org-babel-expand-noweb-references info
) (nth 1 info
))))
554 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
555 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
558 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
559 (org-babel-expand-body:generic
560 body params
(and (fboundp assignments-cmd
)
561 (funcall assignments-cmd params
))))))
563 nil expanded
(concat "*Org-Babel Preview " (buffer-name) "[ " lang
" ]*"))))
565 (defun org-babel-edit-distance (s1 s2
)
566 "Return the edit (levenshtein) distance between strings S1 S2."
567 (let* ((l1 (length s1
))
569 (dist (map 'vector
(lambda (_) (make-vector (1+ l2
) nil
))
570 (number-sequence 1 (1+ l1
)))))
571 (flet ((in (i j
) (aref (aref dist i
) j
))
572 (mmin (&rest lst
) (apply #'min
(remove nil lst
))))
573 (setf (aref (aref dist
0) 0) 0)
574 (dolist (i (number-sequence 1 l1
))
575 (dolist (j (number-sequence 1 l2
))
576 (setf (aref (aref dist i
) j
)
577 (+ (if (equal (aref s1
(1- i
)) (aref s2
(1- j
))) 0 1)
578 (mmin (in (1- i
) j
) (in i
(1- j
)) (in (1- i
) (1- j
)))))))
582 (defun org-babel-check-src-block ()
583 "Check for misspelled header arguments in the current code block."
585 ;; TODO: report malformed code block
586 ;; TODO: report incompatible combinations of header arguments
587 ;; TODO: report uninitialized variables
588 (let ((too-close 2)) ;; <- control closeness to report potential match
589 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg
)) 1))
590 (and (org-babel-where-is-src-block-head)
591 (org-babel-parse-header-arguments
592 (org-babel-clean-text-properties
593 (match-string 4))))))
594 (dolist (name (mapcar #'symbol-name org-babel-header-arg-names
))
595 (when (and (not (string= header name
))
596 (<= (org-babel-edit-distance header name
) too-close
))
597 (error "supplied header \"%S\" is suspiciously close to \"%S\""
599 (message "No suspicious header arguments found.")))
602 (defun org-babel-insert-header-arg ()
603 "Insert a header argument selecting from lists of common args and values."
605 (let* ((lang (car (org-babel-get-src-block-info 'light
)))
606 (lang-headers (intern (concat "org-babel-header-arg-names:" lang
)))
607 (headers (append (if (boundp lang-headers
)
608 (mapcar (lambda (h) (cons h
:any
))
611 org-babel-common-header-args-w-values
))
612 (arg (org-icompleting-read
615 (lambda (header-spec) (symbol-name (car header-spec
)))
618 (let ((vals (cdr (assoc (intern arg
) headers
))))
624 (read-from-minibuffer "value: "))
628 (let ((arg (org-icompleting-read
630 (cons "default" (mapcar #'symbol-name group
)))))
631 (if (and arg
(not (string= "default" arg
)))
637 (defun org-babel-load-in-session (&optional arg info
)
638 "Load the body of the current source-code block.
639 Evaluate the header arguments for the source block before
640 entering the session. After loading the body this pops open the
643 (let* ((info (or info
(org-babel-get-src-block-info)))
645 (params (nth 2 info
))
646 (body (setf (nth 1 info
)
647 (if (and (cdr (assoc :noweb params
))
648 (string= "yes" (cdr (assoc :noweb params
))))
649 (org-babel-expand-noweb-references info
)
651 (session (cdr (assoc :session params
)))
652 (dir (cdr (assoc :dir params
)))
654 (or (and dir
(file-name-as-directory dir
)) default-directory
))
655 (cmd (intern (concat "org-babel-load-session:" lang
))))
656 (unless (fboundp cmd
)
657 (error "No org-babel-load-session function for %s!" lang
))
658 (pop-to-buffer (funcall cmd session body params
))
662 (defun org-babel-initiate-session (&optional arg info
)
663 "Initiate session for current code block.
664 If called with a prefix argument then resolve any variable
665 references in the header arguments and assign these variables in
666 the session. Copy the body of the code block to the kill ring."
668 (let* ((info (or info
(org-babel-get-src-block-info (not arg
))))
671 (params (nth 2 info
))
672 (session (cdr (assoc :session params
)))
673 (dir (cdr (assoc :dir params
)))
675 (or (and dir
(file-name-as-directory dir
)) default-directory
))
676 (init-cmd (intern (format "org-babel-%s-initiate-session" lang
)))
677 (prep-cmd (intern (concat "org-babel-prep-session:" lang
))))
678 (if (and (stringp session
) (string= session
"none"))
679 (error "This block is not using a session!"))
680 (unless (fboundp init-cmd
)
681 (error "No org-babel-initiate-session function for %s!" lang
))
682 (with-temp-buffer (insert (org-babel-trim body
))
683 (copy-region-as-kill (point-min) (point-max)))
685 (unless (fboundp prep-cmd
)
686 (error "No org-babel-prep-session function for %s!" lang
))
687 (funcall prep-cmd session params
))
688 (funcall init-cmd session params
)))
691 (defun org-babel-switch-to-session (&optional arg info
)
692 "Switch to the session of the current code block.
693 Uses `org-babel-initiate-session' to start the session. If called
694 with a prefix argument then this is passed on to
695 `org-babel-initiate-session'."
697 (pop-to-buffer (org-babel-initiate-session arg info
))
700 (defalias 'org-babel-pop-to-session
'org-babel-switch-to-session
)
703 (defun org-babel-switch-to-session-with-code (&optional arg info
)
704 "Switch to code buffer and display session."
708 (let ((other-window-buffer (window-buffer (next-window))))
709 (set-window-buffer (next-window) (current-buffer))
710 (set-window-buffer (selected-window) other-window-buffer
))
712 (let ((info (org-babel-get-src-block-info))
713 (org-src-window-setup 'reorganize-frame
))
715 (org-babel-switch-to-session arg info
))
719 (defmacro org-babel-do-in-edit-buffer
(&rest body
)
720 "Evaluate BODY in edit buffer if there is a code block at point.
721 Return t if a code block was found at point, nil otherwise."
722 `(let ((org-src-window-setup 'switch-invisibly
))
723 (when (and (org-babel-where-is-src-block-head)
724 (org-edit-src-code nil nil nil
))
725 (unwind-protect (progn ,@body
)
726 (if (org-bound-and-true-p org-edit-src-from-org-mode
)
727 (org-edit-src-exit)))
729 (def-edebug-spec org-babel-do-in-edit-buffer
(body))
731 (defun org-babel-do-key-sequence-in-edit-buffer (key)
732 "Read key sequence and execute the command in edit buffer.
733 Enter a key sequence to be executed in the language major-mode
734 edit buffer. For example, TAB will alter the contents of the
735 Org-mode code block according to the effect of TAB in the
736 language major-mode buffer. For languages that support
737 interactive sessions, this can be used to send code from the Org
738 buffer to the session for evaluation using the native major-mode
739 evaluation mechanisms."
740 (interactive "kEnter key-sequence to execute in edit buffer: ")
741 (org-babel-do-in-edit-buffer
743 (key-binding (or key
(read-key-sequence nil
))))))
745 (defvar org-bracket-link-regexp
)
747 (defun org-babel-open-src-block-result (&optional re-run
)
748 "If `point' is on a src block then open the results of the
749 source code block, otherwise return nil. With optional prefix
750 argument RE-RUN the source-code block is evaluated even if
751 results already exist."
753 (let ((info (org-babel-get-src-block-info)))
756 ;; go to the results, if there aren't any then run the block
757 (goto-char (or (and (not re-run
) (org-babel-where-is-src-block-result))
758 (progn (org-babel-execute-src-block)
759 (org-babel-where-is-src-block-result))))
761 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
763 (if (looking-at org-bracket-link-regexp
)
766 (let ((r (org-babel-format-result
767 (org-babel-read-result) (cdr (assoc :sep
(nth 2 info
))))))
768 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
769 (delete-region (point-min) (point-max))
774 (defmacro org-babel-map-src-blocks
(file &rest body
)
775 "Evaluate BODY forms on each source-block in FILE.
776 If FILE is nil evaluate BODY forms on source blocks in current
777 buffer. During evaluation of BODY the following local variables
778 are set relative to the currently matched code block.
780 full-block ------- string holding the entirety of the code block
781 beg-block -------- point at the beginning of the code block
782 end-block -------- point at the end of the matched code block
783 lang ------------- string holding the language of the code block
784 beg-lang --------- point at the beginning of the lang
785 end-lang --------- point at the end of the lang
786 switches --------- string holding the switches
787 beg-switches ----- point at the beginning of the switches
788 end-switches ----- point at the end of the switches
789 header-args ------ string holding the header-args
790 beg-header-args -- point at the beginning of the header-args
791 end-header-args -- point at the end of the header-args
792 body ------------- string holding the body of the code block
793 beg-body --------- point at the beginning of the body
794 end-body --------- point at the end of the body"
796 (let ((tempvar (make-symbol "file")))
797 `(let* ((,tempvar
,file
)
798 (visited-p (or (null ,tempvar
)
799 (get-file-buffer (expand-file-name ,tempvar
))))
800 (point (point)) to-be-removed
)
801 (save-window-excursion
802 (when ,tempvar
(find-file ,tempvar
))
803 (setq to-be-removed
(current-buffer))
804 (goto-char (point-min))
805 (while (re-search-forward org-babel-src-block-regexp nil t
)
806 (goto-char (match-beginning 0))
807 (let ((full-block (match-string 0))
808 (beg-block (match-beginning 0))
809 (end-block (match-end 0))
810 (lang (match-string 2))
811 (beg-lang (match-beginning 2))
812 (end-lang (match-end 2))
813 (switches (match-string 3))
814 (beg-switches (match-beginning 3))
815 (end-switches (match-end 3))
816 (header-args (match-string 4))
817 (beg-header-args (match-beginning 4))
818 (end-header-args (match-end 4))
819 (body (match-string 5))
820 (beg-body (match-beginning 5))
821 (end-body (match-end 5)))
823 (goto-char end-block
))))
824 (unless visited-p
(kill-buffer to-be-removed
))
826 (def-edebug-spec org-babel-map-src-blocks
(form body
))
829 (defmacro org-babel-map-inline-src-blocks
(file &rest body
)
830 "Evaluate BODY forms on each inline source-block in FILE.
831 If FILE is nil evaluate BODY forms on source blocks in current
834 (let ((tempvar (make-symbol "file")))
835 `(let* ((,tempvar
,file
)
836 (visited-p (or (null ,tempvar
)
837 (get-file-buffer (expand-file-name ,tempvar
))))
838 (point (point)) to-be-removed
)
839 (save-window-excursion
840 (when ,tempvar
(find-file ,tempvar
))
841 (setq to-be-removed
(current-buffer))
842 (goto-char (point-min))
843 (while (re-search-forward org-babel-inline-src-block-regexp nil t
)
844 (goto-char (match-beginning 1))
845 (save-match-data ,@body
)
846 (goto-char (match-end 0))))
847 (unless visited-p
(kill-buffer to-be-removed
))
849 (def-edebug-spec org-babel-map-inline-src-blocks
(form body
))
852 (defun org-babel-execute-buffer (&optional arg
)
853 "Execute source code blocks in a buffer.
854 Call `org-babel-execute-src-block' on every source block in
857 (org-babel-eval-wipe-error-buffer)
858 (org-save-outline-visibility t
859 (org-babel-map-src-blocks nil
860 (org-babel-execute-src-block arg
))
861 (org-babel-map-inline-src-blocks nil
862 (org-babel-execute-src-block arg
))
863 (org-babel-map-call-lines nil
864 (org-babel-lob-execute-maybe))))
867 (defun org-babel-execute-subtree (&optional arg
)
868 "Execute source code blocks in a subtree.
869 Call `org-babel-execute-src-block' on every source block in
870 the current subtree."
874 (org-narrow-to-subtree)
875 (org-babel-execute-buffer arg
)
879 (defun org-babel-sha1-hash (&optional info
)
880 "Generate an sha1 hash based on the value of info."
882 (let ((print-level nil
)
883 (info (or info
(org-babel-get-src-block-info))))
885 (sort (copy-sequence (nth 2 info
))
886 (lambda (a b
) (string< (car a
) (car b
)))))
888 (dolist (p '("replace" "silent" "append" "prepend"))
889 (setq lst
(remove p lst
)))
892 (let ((v (if (and (listp (cdr arg
)) (null (cddr arg
)))
893 (copy-sequence (cdr arg
))
895 (when (and v
(not (and (sequencep v
)
899 ((and (listp v
) ; lists are sorted
900 (member (car arg
) '(:result-params
)))
901 (sort (rm v
) #'string
<))
902 ((and (stringp v
) ; strings are sorted
903 (member (car arg
) '(:results
:exports
)))
904 (mapconcat #'identity
(sort (rm (split-string v
))
908 (when (org-called-interactively-p 'interactive
) (message hash
)) hash
)
909 (let ((it (format "%s-%s"
912 (delq nil
(mapcar (lambda (arg)
913 (let ((normalized (norm arg
)))
915 (format "%S" normalized
))))
920 (defun org-babel-current-result-hash ()
921 "Return the in-buffer hash associated with INFO."
922 (org-babel-where-is-src-block-result)
923 (org-babel-clean-text-properties (match-string 3)))
925 (defun org-babel-hide-hash ()
926 "Hide the hash in the current results line.
927 Only the initial `org-babel-hash-show' characters of the hash
928 will remain visible."
929 (add-to-invisibility-spec '(org-babel-hide-hash . t
))
931 (when (and (re-search-forward org-babel-result-regexp nil t
)
933 (let* ((start (match-beginning 3))
934 (hide-start (+ org-babel-hash-show start
))
936 (hash (match-string 3))
938 (setq ov1
(make-overlay start hide-start
))
939 (setq ov2
(make-overlay hide-start end
))
940 (overlay-put ov2
'invisible
'org-babel-hide-hash
)
941 (overlay-put ov1
'babel-hash hash
)))))
943 (defun org-babel-hide-all-hashes ()
944 "Hide the hash in the current buffer.
945 Only the initial `org-babel-hash-show' characters of each hash
946 will remain visible. This function should be called as part of
947 the `org-mode-hook'."
949 (while (re-search-forward org-babel-result-regexp nil t
)
950 (goto-char (match-beginning 0))
951 (org-babel-hide-hash)
952 (goto-char (match-end 0)))))
953 (add-hook 'org-mode-hook
'org-babel-hide-all-hashes
)
955 (defun org-babel-hash-at-point (&optional point
)
956 "Return the value of the hash at POINT.
957 The hash is also added as the last element of the kill ring.
958 This can be called with C-c C-c."
960 (let ((hash (car (delq nil
(mapcar
961 (lambda (ol) (overlay-get ol
'babel-hash
))
962 (overlays-at (or point
(point))))))))
963 (when hash
(kill-new hash
) (message hash
))))
964 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-hash-at-point
)
966 (defun org-babel-result-hide-spec ()
967 "Hide portions of results lines.
968 Add `org-babel-hide-result' as an invisibility spec for hiding
969 portions of results lines."
970 (add-to-invisibility-spec '(org-babel-hide-result . t
)))
971 (add-hook 'org-mode-hook
'org-babel-result-hide-spec
)
973 (defvar org-babel-hide-result-overlays nil
974 "Overlays hiding results.")
976 (defun org-babel-result-hide-all ()
977 "Fold all results in the current buffer."
979 (org-babel-show-result-all)
981 (while (re-search-forward org-babel-result-regexp nil t
)
982 (save-excursion (goto-char (match-beginning 0))
983 (org-babel-hide-result-toggle-maybe)))))
985 (defun org-babel-show-result-all ()
986 "Unfold all results in the current buffer."
987 (mapc 'delete-overlay org-babel-hide-result-overlays
)
988 (setq org-babel-hide-result-overlays nil
))
991 (defun org-babel-hide-result-toggle-maybe ()
992 "Toggle visibility of result at point."
994 (let ((case-fold-search t
))
996 (beginning-of-line 1)
997 (looking-at org-babel-result-regexp
))
998 (progn (org-babel-hide-result-toggle)
999 t
) ;; to signal that we took action
1000 nil
))) ;; to signal that we did not
1002 (defun org-babel-hide-result-toggle (&optional force
)
1003 "Toggle the visibility of the current result."
1007 (if (re-search-forward org-babel-result-regexp nil t
)
1008 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
1009 (end (progn (goto-char (- (org-babel-result-end) 1)) (point)))
1011 (if (memq t
(mapcar (lambda (overlay)
1012 (eq (overlay-get overlay
'invisible
)
1013 'org-babel-hide-result
))
1014 (overlays-at start
)))
1015 (if (or (not force
) (eq force
'off
))
1017 (when (member ov org-babel-hide-result-overlays
)
1018 (setq org-babel-hide-result-overlays
1019 (delq ov org-babel-hide-result-overlays
)))
1020 (when (eq (overlay-get ov
'invisible
)
1021 'org-babel-hide-result
)
1022 (delete-overlay ov
)))
1023 (overlays-at start
)))
1024 (setq ov
(make-overlay start end
))
1025 (overlay-put ov
'invisible
'org-babel-hide-result
)
1026 ;; make the block accessible to isearch
1028 ov
'isearch-open-invisible
1030 (when (member ov org-babel-hide-result-overlays
)
1031 (setq org-babel-hide-result-overlays
1032 (delq ov org-babel-hide-result-overlays
)))
1033 (when (eq (overlay-get ov
'invisible
)
1034 'org-babel-hide-result
)
1035 (delete-overlay ov
))))
1036 (push ov org-babel-hide-result-overlays
)))
1037 (error "Not looking at a result line"))))
1039 ;; org-tab-after-check-for-cycling-hook
1040 (add-hook 'org-tab-first-hook
'org-babel-hide-result-toggle-maybe
)
1041 ;; Remove overlays when changing major mode
1042 (add-hook 'org-mode-hook
1043 (lambda () (org-add-hook 'change-major-mode-hook
1044 'org-babel-show-result-all
'append
'local
)))
1046 (defvar org-file-properties
)
1047 (defun org-babel-params-from-properties (&optional lang
)
1048 "Retrieve parameters specified as properties.
1049 Return an association list of any source block params which
1050 may be specified in the properties of the current outline entry."
1053 (org-babel-parse-multiple-vars
1056 (lambda (header-arg)
1057 (and (setq val
(org-entry-get (point) header-arg t
))
1058 (cons (intern (concat ":" header-arg
))
1059 (org-babel-read val
))))
1063 org-babel-header-arg-names
1065 (setq sym
(intern (concat "org-babel-header-arg-names:"
1067 (and (boundp sym
) (eval sym
)))))))))))
1069 (defvar org-src-preserve-indentation
)
1070 (defun org-babel-parse-src-block-match ()
1071 "Parse the results from a match of the `org-babel-src-block-regexp'."
1072 (let* ((block-indentation (length (match-string 1)))
1073 (lang (org-babel-clean-text-properties (match-string 2)))
1074 (lang-headers (intern (concat "org-babel-default-header-args:" lang
)))
1075 (switches (match-string 3))
1076 (body (org-babel-clean-text-properties
1077 (let* ((body (match-string 5))
1078 (sub-length (- (length body
) 1)))
1079 (if (and (> sub-length
0)
1080 (string= "\n" (substring body sub-length
)))
1081 (substring body
0 sub-length
)
1083 (preserve-indentation (or org-src-preserve-indentation
1084 (string-match "-i\\>" switches
))))
1086 ;; get block body less properties, protective commas, and indentation
1089 (insert (org-babel-strip-protective-commas body
))
1090 (unless preserve-indentation
(org-do-remove-indentation))
1092 (org-babel-merge-params
1093 org-babel-default-header-args
1094 (org-babel-params-from-properties lang
)
1095 (if (boundp lang-headers
) (eval lang-headers
) nil
)
1096 (org-babel-parse-header-arguments
1097 (org-babel-clean-text-properties (or (match-string 4) ""))))
1099 block-indentation
)))
1101 (defun org-babel-parse-inline-src-block-match ()
1102 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
1103 (let* ((lang (org-babel-clean-text-properties (match-string 2)))
1104 (lang-headers (intern (concat "org-babel-default-header-args:" lang
))))
1106 (org-babel-strip-protective-commas
1107 (org-babel-clean-text-properties (match-string 5)))
1108 (org-babel-merge-params
1109 org-babel-default-inline-header-args
1110 (org-babel-params-from-properties lang
)
1111 (if (boundp lang-headers
) (eval lang-headers
) nil
)
1112 (org-babel-parse-header-arguments
1113 (org-babel-clean-text-properties (or (match-string 4) "")))))))
1115 (defun org-babel-balanced-split (string alts
)
1116 "Split STRING on instances of ALTS.
1117 ALTS is a cons of two character options where each option may be
1118 either the numeric code of a single character or a list of
1119 character alternatives. For example to split on balanced
1120 instances of \"[ \t]:\" set ALTS to '((32 9) . 58)."
1121 (flet ((matches (ch spec
) (or (and (numberp spec
) (= spec ch
))
1125 (and (matches ch
(cdr alts
))
1126 (matches last
(car alts
)))
1127 (matches ch alts
))))
1128 (let ((balance 0) (quote nil
) (partial nil
) (lst nil
) (last 0))
1129 (mapc (lambda (ch) ; split on [], (), "" balanced instances of [ \t]:
1130 (setq balance
(+ balance
1131 (cond ((or (equal 91 ch
) (equal 40 ch
)) 1)
1132 ((or (equal 93 ch
) (equal 41 ch
)) -
1)
1134 (when (and (equal 34 ch
) (not (equal 92 last
)))
1135 (setq quote
(not quote
)))
1136 (setq partial
(cons ch partial
))
1137 (when (and (= balance
0) (not quote
) (matched ch last
))
1138 (setq lst
(cons (apply #'string
(nreverse
1145 (string-to-list string
))
1146 (nreverse (cons (apply #'string
(nreverse partial
)) lst
)))))
1148 (defun org-babel-parse-header-arguments (arg-string)
1149 "Parse a string of header arguments returning an alist."
1150 (when (> (length arg-string
) 0)
1151 (org-babel-parse-multiple-vars
1156 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1158 (cons (intern (match-string 1 arg
))
1159 (org-babel-read (org-babel-chomp (match-string 2 arg
))))
1160 (cons (intern (org-babel-chomp arg
)) nil
)))
1162 (cons (car raw
) (mapcar (lambda (r) (concat ":" r
)) (cdr raw
))))
1163 (org-babel-balanced-split arg-string
'((32 9) .
58))))))))
1165 (defun org-babel-parse-multiple-vars (header-arguments)
1166 "Expand multiple variable assignments behind a single :var keyword.
1168 This allows expression of multiple variables with one :var as
1171 #+PROPERTY: var foo=1, bar=2"
1173 (mapc (lambda (pair)
1174 (if (eq (car pair
) :var
)
1175 (mapcar (lambda (v) (push (cons :var
(org-babel-trim v
)) results
))
1176 (org-babel-balanced-split (cdr pair
) 32))
1177 (push pair results
)))
1179 (nreverse results
)))
1181 (defun org-babel-process-params (params)
1182 "Expand variables in PARAMS and add summary parameters."
1183 (let* ((processed-vars (mapcar (lambda (el)
1184 (if (consp (cdr el
))
1186 (org-babel-ref-parse (cdr el
))))
1187 (org-babel-get-header params
:var
)))
1188 (vars-and-names (if (and (assoc :colname-names params
)
1189 (assoc :rowname-names params
))
1190 (list processed-vars
)
1191 (org-babel-disassemble-tables
1193 (cdr (assoc :hlines params
))
1194 (cdr (assoc :colnames params
))
1195 (cdr (assoc :rownames params
)))))
1196 (raw-result (or (cdr (assoc :results params
)) ""))
1197 (result-params (append
1198 (split-string (if (stringp raw-result
)
1201 (cdr (assoc :result-params params
)))))
1203 (mapcar (lambda (var) (cons :var var
)) (car vars-and-names
))
1205 (cons :colname-names
(or (cdr (assoc :colname-names params
))
1206 (cadr vars-and-names
)))
1207 (cons :rowname-names
(or (cdr (assoc :rowname-names params
))
1208 (caddr vars-and-names
)))
1209 (cons :result-params result-params
)
1210 (cons :result-type
(cond ((member "output" result-params
) 'output
)
1211 ((member "value" result-params
) 'value
)
1213 (org-babel-get-header params
:var
'other
))))
1215 ;; row and column names
1216 (defun org-babel-del-hlines (table)
1217 "Remove all 'hlines from TABLE."
1218 (remove 'hline table
))
1220 (defun org-babel-get-colnames (table)
1221 "Return the column names of TABLE.
1222 Return a cons cell, the `car' of which contains the TABLE less
1223 colnames, and the `cdr' of which contains a list of the column
1225 (if (equal 'hline
(nth 1 table
))
1226 (cons (cddr table
) (car table
))
1227 (cons (cdr table
) (car table
))))
1229 (defun org-babel-get-rownames (table)
1230 "Return the row names of TABLE.
1231 Return a cons cell, the `car' of which contains the TABLE less
1232 colnames, and the `cdr' of which contains a list of the column
1233 names. Note: this function removes any hlines in TABLE."
1234 (flet ((trans (table) (apply #'mapcar
* #'list table
)))
1235 (let* ((width (apply 'max
1236 (mapcar (lambda (el) (if (listp el
) (length el
) 0)) table
)))
1237 (table (trans (mapcar (lambda (row)
1238 (if (not (equal row
'hline
))
1242 (setq row
(cons 'hline row
)))
1245 (cons (mapcar (lambda (row) (if (equal (car row
) 'hline
) 'hline row
))
1246 (trans (cdr table
)))
1247 (remove 'hline
(car table
))))))
1249 (defun org-babel-put-colnames (table colnames
)
1250 "Add COLNAMES to TABLE if they exist."
1251 (if colnames
(apply 'list colnames
'hline table
) table
))
1253 (defun org-babel-put-rownames (table rownames
)
1254 "Add ROWNAMES to TABLE if they exist."
1256 (mapcar (lambda (row)
1258 (cons (or (pop rownames
) "") row
)
1262 (defun org-babel-pick-name (names selector
)
1263 "Select one out of an alist of row or column names.
1264 SELECTOR can be either a list of names in which case those names
1265 will be returned directly, or an index into the list NAMES in
1266 which case the indexed names will be return."
1267 (if (listp selector
)
1270 (if (and selector
(symbolp selector
) (not (equal t selector
)))
1271 (cdr (assoc selector names
))
1272 (if (integerp selector
)
1273 (nth (- selector
1) names
)
1274 (cdr (car (last names
))))))))
1276 (defun org-babel-disassemble-tables (vars hlines colnames rownames
)
1277 "Parse tables for further processing.
1278 Process the variables in VARS according to the HLINES,
1279 ROWNAMES and COLNAMES header arguments. Return a list consisting
1280 of the vars, cnames and rnames."
1281 (let (cnames rnames
)
1285 (when (listp (cdr var
))
1286 (when (and (not (equal colnames
"no"))
1287 (or colnames
(and (equal (nth 1 (cdr var
)) 'hline
)
1288 (not (member 'hline
(cddr (cdr var
)))))))
1289 (let ((both (org-babel-get-colnames (cdr var
))))
1290 (setq cnames
(cons (cons (car var
) (cdr both
))
1292 (setq var
(cons (car var
) (car both
)))))
1293 (when (and rownames
(not (equal rownames
"no")))
1294 (let ((both (org-babel-get-rownames (cdr var
))))
1295 (setq rnames
(cons (cons (car var
) (cdr both
))
1297 (setq var
(cons (car var
) (car both
)))))
1298 (when (and hlines
(not (equal hlines
"yes")))
1299 (setq var
(cons (car var
) (org-babel-del-hlines (cdr var
))))))
1302 (reverse cnames
) (reverse rnames
))))
1304 (defun org-babel-reassemble-table (table colnames rownames
)
1305 "Add column and row names to a table.
1306 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1307 to the table for reinsertion to org-mode."
1310 (if (and colnames
(listp (car table
)) (= (length (car table
))
1312 (org-babel-put-colnames table colnames
) table
))
1313 (if (and rownames
(= (length table
) (length rownames
)))
1314 (org-babel-put-rownames table rownames
) table
))
1317 (defun org-babel-where-is-src-block-head ()
1318 "Find where the current source block begins.
1319 Return the point at the beginning of the current source
1320 block. Specifically at the beginning of the #+BEGIN_SRC line.
1321 If the point is not on a source block then return nil."
1322 (let ((initial (point)) top bottom
)
1324 (save-excursion ;; on a source name line or a #+header line
1325 (beginning-of-line 1)
1326 (and (or (looking-at org-babel-src-name-regexp
)
1327 (looking-at org-babel-multi-line-header-regexp
))
1329 (while (and (forward-line 1)
1330 (looking-at org-babel-multi-line-header-regexp
)))
1331 (looking-at org-babel-src-block-regexp
))
1333 (save-excursion ;; on a #+begin_src line
1334 (beginning-of-line 1)
1335 (and (looking-at org-babel-src-block-regexp
)
1337 (save-excursion ;; inside a src block
1339 (re-search-backward "^[ \t]*#\\+begin_src" nil t
) (setq top
(point))
1340 (re-search-forward "^[ \t]*#\\+end_src" nil t
) (setq bottom
(point))
1341 (< top initial
) (< initial bottom
)
1342 (progn (goto-char top
) (beginning-of-line 1)
1343 (looking-at org-babel-src-block-regexp
))
1347 (defun org-babel-goto-src-block-head ()
1348 "Go to the beginning of the current code block."
1351 (if head
(goto-char head
) (error "not currently in a code block")))
1352 (org-babel-where-is-src-block-head)))
1355 (defun org-babel-goto-named-src-block (name)
1356 "Go to a named source-code block."
1358 (let ((completion-ignore-case t
))
1359 (list (org-icompleting-read "source-block name: "
1360 (org-babel-src-block-names) nil t
))))
1361 (let ((point (org-babel-find-named-block name
)))
1363 ;; taken from `org-open-at-point'
1364 (progn (goto-char point
) (org-show-context))
1365 (message "source-code block '%s' not found in this buffer" name
))))
1367 (defun org-babel-find-named-block (name)
1368 "Find a named source-code block.
1369 Return the location of the source block identified by source
1370 NAME, or nil if no such block exists. Set match data according to
1371 org-babel-named-src-block-regexp."
1373 (let ((case-fold-search t
)
1374 (regexp (org-babel-named-src-block-regexp-for-name name
)) msg
)
1375 (goto-char (point-min))
1376 (when (or (re-search-forward regexp nil t
)
1377 (re-search-backward regexp nil t
))
1378 (match-beginning 0)))))
1380 (defun org-babel-src-block-names (&optional file
)
1381 "Returns the names of source blocks in FILE or the current buffer."
1383 (when file
(find-file file
)) (goto-char (point-min))
1385 (while (re-search-forward org-babel-src-name-w-name-regexp nil t
)
1386 (setq names
(cons (match-string 3) names
)))
1390 (defun org-babel-goto-named-result (name)
1391 "Go to a named result."
1393 (let ((completion-ignore-case t
))
1394 (list (org-icompleting-read "source-block name: "
1395 (org-babel-result-names) nil t
))))
1396 (let ((point (org-babel-find-named-result name
)))
1398 ;; taken from `org-open-at-point'
1399 (progn (goto-char point
) (org-show-context))
1400 (message "result '%s' not found in this buffer" name
))))
1402 (defun org-babel-find-named-result (name &optional point
)
1403 "Find a named result.
1404 Return the location of the result named NAME in the current
1405 buffer or nil if no such result exists."
1407 (goto-char (or point
(point-min)))
1408 (catch 'is-a-code-block
1409 (when (re-search-forward
1410 (concat org-babel-result-regexp
1411 "[ \t]" (regexp-quote name
) "[ \t\n\f\v\r]") nil t
)
1412 (when (and (string= "name" (downcase (match-string 1)))
1413 (or (looking-at org-babel-src-block-regexp
)
1414 (looking-at org-babel-multi-line-header-regexp
)))
1415 (throw 'is-a-code-block
(org-babel-find-named-result name
(point))))
1416 (beginning-of-line 0) (point)))))
1418 (defun org-babel-result-names (&optional file
)
1419 "Returns the names of results in FILE or the current buffer."
1421 (when file
(find-file file
)) (goto-char (point-min))
1423 (while (re-search-forward org-babel-result-w-name-regexp nil t
)
1424 (setq names
(cons (match-string 4) names
)))
1428 (defun org-babel-next-src-block (&optional arg
)
1429 "Jump to the next source block.
1430 With optional prefix argument ARG, jump forward ARG many source blocks."
1432 (when (looking-at org-babel-src-block-regexp
) (forward-char 1))
1434 (re-search-forward org-babel-src-block-regexp nil nil
(or arg
1))
1435 (error (error "No further code blocks")))
1436 (goto-char (match-beginning 0)) (org-show-context))
1439 (defun org-babel-previous-src-block (&optional arg
)
1440 "Jump to the previous source block.
1441 With optional prefix argument ARG, jump backward ARG many source blocks."
1444 (re-search-backward org-babel-src-block-regexp nil nil
(or arg
1))
1445 (error (error "No previous code blocks")))
1446 (goto-char (match-beginning 0)) (org-show-context))
1448 (defvar org-babel-load-languages
)
1451 (defun org-babel-mark-block ()
1452 "Mark current src block"
1458 (looking-at org-babel-src-block-regexp
))
1459 (push-mark (match-end 5) nil t
)
1460 (goto-char (match-beginning 5))))
1461 (org-babel-where-is-src-block-head)))
1463 (defun org-babel-demarcate-block (&optional arg
)
1464 "Wrap or split the code in the region or on the point.
1465 When called from inside of a code block the current block is
1466 split. When called from outside of a code block a new code block
1467 is created. In both cases if the region is demarcated and if the
1468 region is not active then the point is demarcated."
1470 (let ((info (org-babel-get-src-block-info 'light
))
1471 (headers (progn (org-babel-where-is-src-block-head)
1473 (stars (concat (make-string (or (org-current-level) 1) ?
*) " ")))
1479 (let ((lang (nth 0 info
))
1480 (indent (make-string (nth 5 info
) ?
)))
1481 (when (string-match "^[[:space:]]*$"
1482 (buffer-substring (point-at-bol)
1484 (delete-region (point-at-bol) (point-at-eol)))
1486 (if (looking-at "^") "" "\n")
1487 indent
"#+end_src\n"
1488 (if arg stars indent
) "\n"
1489 indent
"#+begin_src " lang
1490 (if (> (length headers
) 1)
1491 (concat " " headers
) headers
)
1492 (if (looking-at "[\n\r]")
1494 (concat "\n" (make-string (current-column) ?
)))))))
1495 (move-end-of-line 2))
1496 (sort (if (region-active-p) (list (mark) (point)) (list (point))) #'>))
1497 (let ((start (point))
1498 (lang (org-icompleting-read "Lang: "
1499 (mapcar (lambda (el) (symbol-name (car el
)))
1500 org-babel-load-languages
)))
1501 (body (delete-and-extract-region
1502 (if (region-active-p) (mark) (point)) (point))))
1503 (insert (concat (if (looking-at "^") "" "\n")
1504 (if arg
(concat stars
"\n") "")
1505 "#+begin_src " lang
"\n"
1507 (if (or (= (length body
) 0)
1508 (string-match "[\r\n]$" body
)) "" "\n")
1510 (goto-char start
) (move-end-of-line 1)))))
1512 (defvar org-babel-lob-one-liner-regexp
)
1513 (defun org-babel-where-is-src-block-result (&optional insert info hash indent
)
1514 "Find where the current source block results begin.
1515 Return the point at the beginning of the result of the current
1516 source block. Specifically at the beginning of the results line.
1517 If no result exists for this block then create a results line
1518 following the source block."
1520 (let* ((on-lob-line (save-excursion
1521 (beginning-of-line 1)
1522 (looking-at org-babel-lob-one-liner-regexp
)))
1523 (inlinep (when (org-babel-get-inline-src-block-matches)
1525 (name (if on-lob-line
1526 (nth 0 (org-babel-lob-get-info))
1527 (nth 4 (or info
(org-babel-get-src-block-info 'light
)))))
1528 (head (unless on-lob-line
(org-babel-where-is-src-block-head)))
1530 (when head
(goto-char head
))
1532 found
;; was there a result (before we potentially insert one)
1537 ;; - return t if it is found, else return nil
1538 ;; - if it does not need to be rebuilt, then don't set end
1539 ;; - if it does need to be rebuilt then do set end
1540 name
(setq beg
(org-babel-find-named-result name
))
1542 (when (and hash
(not (string= hash
(match-string 3))))
1543 (goto-char beg
) (setq end beg
) ;; beginning of result
1545 (delete-region end
(org-babel-result-end)) nil
)))
1548 ;; - return t if it is found, else return nil
1549 ;; - if it is found, and the hash doesn't match, delete and set end
1550 (or on-lob-line
(re-search-forward "^[ \t]*#\\+end_src" nil t
))
1551 (progn (end-of-line 1)
1552 (if (eobp) (insert "\n") (forward-char 1))
1555 (progn ;; unnamed results line already exists
1556 (re-search-forward "[^ \f\t\n\r\v]" nil t
)
1557 (beginning-of-line 1)
1559 (concat org-babel-result-regexp
"\n")))
1561 ;; must remove and rebuild if hash!=old-hash
1562 (if (and hash
(not (string= hash
(match-string 3))))
1566 end
(org-babel-result-end)))
1567 (setq end nil
)))))))))
1568 (if (and insert end
)
1572 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1577 (org-number-sequence 1 indent
) "")
1580 (when hash
(concat "["hash
"]"))
1582 (when name
(concat " " name
)) "\n"))
1583 (unless beg
(insert "\n") (backward-char))
1584 (beginning-of-line 0)
1585 (if hash
(org-babel-hide-hash))
1589 (defvar org-block-regexp
)
1590 (defun org-babel-read-result ()
1591 "Read the result at `point' into emacs-lisp."
1592 (let ((case-fold-search t
) result-string
)
1594 ((org-at-table-p) (org-babel-read-table))
1595 ((org-at-item-p) (org-babel-read-list))
1596 ((looking-at org-bracket-link-regexp
) (org-babel-read-link))
1597 ((looking-at org-block-regexp
) (org-babel-trim (match-string 4)))
1598 ((looking-at "^[ \t]*: ")
1601 (mapconcat (lambda (line)
1602 (if (and (> (length line
) 1)
1603 (string-match "^[ \t]*: \\(.+\\)" line
))
1604 (match-string 1 line
)
1608 (point) (org-babel-result-end)) "[\r\n]+")
1610 (or (org-babel-number-p result-string
) result-string
))
1611 ((looking-at org-babel-result-regexp
)
1612 (save-excursion (forward-line 1) (org-babel-read-result))))))
1614 (defun org-babel-read-table ()
1615 "Read the table at `point' into emacs-lisp."
1616 (mapcar (lambda (row)
1617 (if (and (symbolp row
) (equal row
'hline
)) row
1618 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
)) row
)))
1619 (org-table-to-lisp)))
1621 (defun org-babel-read-list ()
1622 "Read the list at `point' into emacs-lisp."
1623 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
))
1624 (mapcar #'cadr
(cdr (org-list-parse-list)))))
1626 (defvar org-link-types-re
)
1627 (defun org-babel-read-link ()
1628 "Read the link at `point' into emacs-lisp.
1629 If the path of the link is a file path it is expanded using
1630 `expand-file-name'."
1631 (let* ((case-fold-search t
)
1632 (raw (and (looking-at org-bracket-link-regexp
)
1633 (org-babel-clean-text-properties (match-string 1))))
1634 (type (and (string-match org-link-types-re raw
)
1635 (match-string 1 raw
))))
1637 ((not type
) (expand-file-name raw
))
1638 ((string= type
"file")
1639 (and (string-match "file\\(.*\\):\\(.+\\)" raw
)
1640 (expand-file-name (match-string 2 raw
))))
1643 (defun org-babel-format-result (result &optional sep
)
1644 "Format RESULT for writing to file."
1645 (flet ((echo-res (result)
1646 (if (stringp result
) result
(format "%S" result
))))
1655 (echo-res result
))))
1657 (defun org-babel-insert-result
1658 (result &optional result-params info hash indent lang
)
1659 "Insert RESULT into the current buffer.
1660 By default RESULT is inserted after the end of the
1661 current source block. With optional argument RESULT-PARAMS
1662 controls insertion of results in the org-mode file.
1663 RESULT-PARAMS can take the following values...
1665 replace - (default option) insert results after the source block
1666 replacing any previously inserted results
1668 silent -- no results are inserted
1670 file ---- the results are interpreted as a file path, and are
1671 inserted into the buffer using the Org-mode file syntax
1673 list ---- the results are interpreted as an Org-mode list.
1675 raw ----- results are added directly to the Org-mode file. This
1676 is a good option if you code block will output org-mode
1679 org ----- similar in effect to raw, only the results are wrapped
1680 in an org code block. Similar to the raw option, on
1681 export the results will be interpreted as org-formatted
1682 text, however by wrapping the results in an org code
1683 block they can be replaced upon re-execution of the
1686 html ---- results are added inside of a #+BEGIN_HTML block. This
1687 is a good option if you code block will output html
1690 latex --- results are added inside of a #+BEGIN_LATEX block.
1691 This is a good option if you code block will output
1692 latex formatted text.
1694 code ---- the results are extracted in the syntax of the source
1695 code of the language being evaluated and are added
1696 inside of a #+BEGIN_SRC block with the source-code
1697 language set appropriately. Note this relies on the
1698 optional LANG argument."
1699 (if (stringp result
)
1701 (setq result
(org-babel-clean-text-properties result
))
1702 (when (member "file" result-params
)
1703 (setq result
(org-babel-result-to-file result
))))
1704 (unless (listp result
) (setq result
(format "%S" result
))))
1705 (if (and result-params
(member "silent" result-params
))
1707 (message (replace-regexp-in-string "%" "%%" (format "%S" result
)))
1712 (when (or (org-babel-get-inline-src-block-matches)
1713 (org-babel-get-lob-one-liner-matches))
1714 (goto-char (match-end 0))
1715 (insert (if (listp result
) "\n" " "))
1717 (existing-result (unless inlinep
1718 (org-babel-where-is-src-block-result
1719 t info hash indent
)))
1721 (cdr (assoc :results_switches
(nth 2 info
))))
1723 (when (and (stringp result
) ; ensure results end in a newline
1725 (> (length result
) 0)
1726 (not (or (string-equal (substring result -
1) "\n")
1727 (string-equal (substring result -
1) "\r"))))
1728 (setq result
(concat result
"\n")))
1729 (if (not existing-result
)
1730 (setq beg
(or inlinep
(point)))
1731 (goto-char existing-result
)
1733 (re-search-forward "#" nil t
)
1734 (setq indent
(- (current-column) 1)))
1738 ((member "replace" result-params
)
1739 (delete-region (point) (org-babel-result-end)))
1740 ((member "append" result-params
)
1741 (goto-char (org-babel-result-end)) (setq beg
(point-marker)))
1742 ((member "prepend" result-params
)))) ; already there
1743 (setq results-switches
1744 (if results-switches
(concat " " results-switches
) ""))
1745 ;; insert results based on type
1747 ;; do nothing for an empty result
1748 ((= (length result
) 0))
1749 ;; insert a list if preferred
1750 ((member "list" result-params
)
1753 (org-list-to-generic
1756 (lambda (el) (list nil
(if (stringp el
) el
(format "%S" el
))))
1757 (if (listp result
) result
(list result
))))
1758 '(:splicep nil
:istart
"- " :iend
"\n")))
1760 ;; assume the result is a table if it's not a string
1761 ((not (stringp result
))
1763 (insert (concat (orgtbl-to-orgtbl
1764 (if (or (eq 'hline
(car result
))
1765 (and (listp (car result
))
1766 (listp (cdr (car result
)))))
1767 result
(list result
))
1768 '(:fmt
(lambda (cell) (format "%s" cell
)))) "\n"))
1769 (goto-char beg
) (when (org-at-table-p) (org-table-align)))
1770 ((member "file" result-params
)
1771 (when inlinep
(goto-char inlinep
))
1773 (t (goto-char beg
) (insert result
)))
1774 (when (listp result
) (goto-char (org-table-end)))
1775 (setq end
(point-marker))
1776 ;; possibly wrap result
1777 (flet ((wrap (start finish
)
1778 (goto-char beg
) (insert (concat start
"\n"))
1779 (goto-char end
) (insert (concat finish
"\n"))
1780 (setq end
(point-marker))))
1782 ((member "html" result-params
)
1783 (wrap "#+BEGIN_HTML" "#+END_HTML"))
1784 ((member "latex" result-params
)
1785 (wrap "#+BEGIN_LaTeX" "#+END_LaTeX"))
1786 ((member "code" result-params
)
1787 (wrap (format "#+BEGIN_SRC %s%s" (or lang
"none") results-switches
)
1789 ((member "org" result-params
)
1790 (wrap "#+BEGIN_ORG" "#+END_ORG"))
1791 ((member "raw" result-params
)
1792 (goto-char beg
) (if (org-at-table-p) (org-cycle)))
1793 ((member "wrap" result-params
)
1794 (when (and (stringp result
) (not (member "file" result-params
)))
1795 (org-babel-examplize-region beg end results-switches
))
1796 (wrap "#+BEGIN_RESULT" "#+END_RESULT"))
1797 ((and (stringp result
) (not (member "file" result-params
)))
1798 (org-babel-examplize-region beg end results-switches
)
1799 (setq end
(point)))))
1800 ;; possibly indent the results to match the #+results line
1801 (when (and (not inlinep
) (numberp indent
) indent
(> indent
0)
1802 ;; in this case `table-align' does the work for us
1803 (not (and (listp result
)
1804 (member "append" result-params
))))
1805 (indent-rigidly beg end indent
))))
1806 (if (= (length result
) 0)
1807 (if (member "value" result-params
)
1808 (message "Code block returned no value.")
1809 (message "Code block produced no output."))
1810 (message "Code block evaluation complete."))))
1812 (defun org-babel-remove-result (&optional info
)
1813 "Remove the result of the current source block."
1815 (let ((location (org-babel-where-is-src-block-result nil info
)) start
)
1817 (setq start
(- location
1))
1819 (goto-char location
) (forward-line 1)
1820 (delete-region start
(org-babel-result-end))))))
1822 (defun org-babel-result-end ()
1823 "Return the point at the end of the current set of results"
1826 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
1827 ((org-at-item-p) (let* ((struct (org-list-struct))
1828 (prvs (org-list-prevs-alist struct
)))
1829 (org-list-get-list-end (point-at-bol) struct prvs
)))
1831 (let ((case-fold-search t
)
1832 (blocks-re (regexp-opt
1833 (list "latex" "html" "example" "src" "result" "org"))))
1834 (if (looking-at (concat "[ \t]*#\\+begin_" blocks-re
))
1835 (progn (re-search-forward (concat "[ \t]*#\\+end_" blocks-re
) nil t
)
1837 (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
1841 (defun org-babel-result-to-file (result)
1842 "Convert RESULT into an `org-mode' link.
1843 If the `default-directory' is different from the containing
1844 file's directory then expand relative links."
1845 (flet ((cond-exp (file)
1846 (if (and default-directory
1848 (not (string= (expand-file-name default-directory
)
1850 (file-name-directory buffer-file-name
)))))
1851 (expand-file-name file default-directory
)
1853 (if (stringp result
)
1854 (format "[[file:%s]]" (cond-exp result
))
1855 (when (and (listp result
) (= 2 (length result
))
1856 (stringp (car result
)) (stringp (cadr result
)))
1857 (format "[[file:%s][%s]]" (car result
) (cadr result
))))))
1859 (defun org-babel-examplize-region (beg end
&optional results-switches
)
1860 "Comment out region using the inline '==' or ': ' org example quote."
1862 (flet ((chars-between (b e
) (string-match "[\\S]" (buffer-substring b e
))))
1863 (if (or (chars-between (save-excursion (goto-char beg
) (point-at-bol)) beg
)
1864 (chars-between end
(save-excursion (goto-char end
) (point-at-eol))))
1867 (insert (format "=%s=" (prog1 (buffer-substring beg end
)
1868 (delete-region beg end
)))))
1869 (let ((size (count-lines beg end
)))
1871 (cond ((= size
0)) ; do nothing for an empty result
1872 ((< size org-babel-min-lines-for-block-output
)
1875 (beginning-of-line 1) (insert ": ") (forward-line 1)))
1878 (insert (if results-switches
1879 (format "#+begin_example%s\n" results-switches
)
1880 "#+begin_example\n"))
1881 (if (markerp end
) (goto-char end
) (forward-char (- end beg
)))
1882 (insert "#+end_example\n"))))))))
1884 (defun org-babel-update-block-body (new-body)
1885 "Update the body of the current code block to NEW-BODY."
1886 (if (not (org-babel-where-is-src-block-head))
1887 (error "not in source block")
1889 (replace-match (concat (org-babel-trim new-body
) "\n") nil t nil
5))
1890 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
1892 (defun org-babel-merge-params (&rest plists
)
1893 "Combine all parameter association lists in PLISTS.
1894 Later elements of PLISTS override the values of previous elements.
1895 This takes into account some special considerations for certain
1896 parameters when merging lists."
1897 (let ((results-exclusive-groups
1898 (mapcar (lambda (group) (mapcar #'symbol-name group
))
1899 (cdr (assoc 'results org-babel-common-header-args-w-values
))))
1900 (exports-exclusive-groups
1901 (mapcar (lambda (group) (mapcar #'symbol-name group
))
1902 (cdr (assoc 'exports org-babel-common-header-args-w-values
))))
1904 params results exports tangle noweb cache vars shebang comments padline
)
1905 (flet ((e-merge (exclusive-groups &rest result-params
)
1906 ;; maintain exclusivity of mutually exclusive parameters
1908 (mapc (lambda (new-params)
1909 (mapc (lambda (new-param)
1910 (mapc (lambda (exclusive-group)
1911 (when (member new-param exclusive-group
)
1912 (mapcar (lambda (excluded-param)
1919 (setq output
(org-uniquify
1920 (cons new-param output
))))
1930 (let ((name (if (listp (cdr pair
))
1932 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
1934 (intern (match-string 1 (cdr pair
)))))))
1938 (if (member name
(mapcar #'car vars
))
1942 (unless (equal (car p
) name
) p
))
1945 (list (cons name pair
))))
1946 ;; if no name is given and we already have named variables
1947 ;; then assign to named variables in order
1948 (if (and vars
(nth variable-index vars
))
1949 (prog1 (setf (cddr (nth variable-index vars
))
1950 (concat (symbol-name
1951 (car (nth variable-index vars
)))
1953 (incf variable-index
))
1954 (error "variable \"%s\" must be assigned a default value"
1957 (setq results
(e-merge results-exclusive-groups
1960 (let ((r (cdr pair
)))
1961 (if (stringp r
) r
(eval r
)))))))
1964 (setq results
(e-merge results-exclusive-groups
1966 (unless (or (member "both" exports
)
1967 (member "none" exports
)
1968 (member "code" exports
))
1969 (setq exports
(e-merge exports-exclusive-groups
1970 exports
'("results"))))
1971 (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))
1973 (setq exports
(e-merge exports-exclusive-groups
1974 exports
(split-string (cdr pair
)))))
1975 (:tangle
;; take the latest -- always overwrite
1976 (setq tangle
(or (list (cdr pair
)) tangle
)))
1978 (setq noweb
(e-merge '(("yes" "no" "tangle")) noweb
1979 (split-string (or (cdr pair
) "")))))
1981 (setq cache
(e-merge '(("yes" "no")) cache
1982 (split-string (or (cdr pair
) "")))))
1984 (setq padline
(e-merge '(("yes" "no")) padline
1985 (split-string (or (cdr pair
) "")))))
1986 (:shebang
;; take the latest -- always overwrite
1987 (setq shebang
(or (list (cdr pair
)) shebang
)))
1989 (setq comments
(e-merge '(("yes" "no")) comments
1990 (split-string (or (cdr pair
) "")))))
1991 (t ;; replace: this covers e.g. :session
1992 (setq params
(cons pair
(assq-delete-all (car pair
) params
))))))
1995 (setq vars
(reverse vars
))
1996 (while vars
(setq params
(cons (cons :var
(cddr (pop vars
))) params
)))
1999 (let ((key (intern (concat ":" (symbol-name hd
))))
2001 (setf params
(cons (cons key
(mapconcat 'identity val
" ")) params
))))
2002 '(results exports tangle noweb padline cache shebang comments
))
2005 (defun org-babel-expand-noweb-references (&optional info parent-buffer
)
2006 "Expand Noweb references in the body of the current source code block.
2008 For example the following reference would be replaced with the
2009 body of the source-code block named 'example-block'.
2013 Note that any text preceding the <<foo>> construct on a line will
2014 be interposed between the lines of the replacement text. So for
2015 example if <<foo>> is placed behind a comment, then the entire
2016 replacement text will also be commented.
2018 This function must be called from inside of the buffer containing
2019 the source-code block which holds BODY.
2021 In addition the following syntax can be used to insert the
2022 results of evaluating the source-code block named 'example-block'.
2026 Any optional arguments can be passed to example-block by placing
2027 the arguments inside the parenthesis following the convention
2028 defined by `org-babel-lob'. For example
2030 <<example-block(a=9)>>
2032 would set the value of argument \"a\" equal to \"9\". Note that
2033 these arguments are not evaluated in the current source-code
2034 block but are passed literally to the \"example-block\"."
2035 (let* ((parent-buffer (or parent-buffer
(current-buffer)))
2036 (info (or info
(org-babel-get-src-block-info)))
2039 (comment (string= "noweb" (cdr (assoc :comments
(nth 2 info
)))))
2040 (new-body "") index source-name evaluate prefix blocks-in-buffer
)
2041 (flet ((nb-add (text) (setq new-body
(concat new-body text
)))
2044 (funcall (intern (concat lang
"-mode")))
2045 (comment-region (point) (progn (insert text
) (point)))
2046 (org-babel-trim (buffer-string))))
2047 (blocks () ;; return the info lists of all blocks in this buffer
2051 (org-babel-map-src-blocks nil
2052 (setq infos
(cons (org-babel-get-src-block-info 'light
)
2056 (insert body
) (goto-char (point-min))
2057 (setq index
(point))
2058 (while (and (re-search-forward "<<\\(.+?\\)>>" nil t
))
2059 (save-match-data (setf source-name
(match-string 1)))
2060 (save-match-data (setq evaluate
(string-match "\(.*\)" source-name
)))
2063 (buffer-substring (match-beginning 0)
2065 (beginning-of-line 1) (point)))))
2066 ;; add interval to new-body (removing noweb reference)
2067 (goto-char (match-beginning 0))
2068 (nb-add (buffer-substring index
(point)))
2069 (goto-char (match-end 0))
2070 (setq index
(point))
2072 (with-current-buffer parent-buffer
2073 (mapconcat ;; interpose PREFIX between every line
2077 (let ((raw (org-babel-ref-resolve source-name
)))
2078 (if (stringp raw
) raw
(format "%S" raw
)))
2080 ;; retrieve from the library of babel
2081 (nth 2 (assoc (intern source-name
)
2082 org-babel-library-of-babel
))
2083 ;; return the contents of headlines literally
2085 (when (org-babel-ref-goto-headline-id source-name
)
2086 (org-babel-ref-headline-body)))
2087 ;; find the expansion of reference in this buffer
2090 (when (string= source-name
2091 (or (cdr (assoc :noweb-ref
(nth 2 i
)))
2093 (let ((body (org-babel-expand-noweb-references i
)))
2096 (concat (c-wrap (car cs
)) "\n"
2097 body
"\n" (c-wrap (cadr cs
))))
2098 (org-babel-tangle-comment-links i
))
2100 (or blocks-in-buffer
2101 (setq blocks-in-buffer
(blocks)))
2103 ;; possibly raise an error if named block doesn't exist
2104 (if (member lang org-babel-noweb-error-langs
)
2106 "<<" source-name
">> "
2107 "could not be resolved (see "
2108 "`org-babel-noweb-error-langs')"))
2110 "[\n\r]") (concat "\n" prefix
)))))
2111 (nb-add (buffer-substring index
(point-max)))))
2114 (defun org-babel-clean-text-properties (text)
2115 "Strip all properties from text return."
2117 (set-text-properties 0 (length text
) nil text
) text
))
2119 (defun org-babel-strip-protective-commas (body)
2120 "Strip protective commas from bodies of source blocks."
2122 (replace-regexp-in-string "^,#" "#" body
)))
2124 (defun org-babel-script-escape (str &optional force
)
2125 "Safely convert tables into elisp lists."
2126 (let (in-single in-double out
)
2127 ((lambda (escaped) (condition-case nil
(org-babel-read escaped
) (error escaped
)))
2131 (or (and (string-equal "[" (substring str
0 1))
2132 (string-equal "]" (substring str -
1)))
2133 (and (string-equal "{" (substring str
0 1))
2134 (string-equal "}" (substring str -
1)))
2135 (and (string-equal "(" (substring str
0 1))
2136 (string-equal ")" (substring str -
1))))))
2146 (91 (if (or in-double in-single
) ; [
2149 (93 (if (or in-double in-single
) ; ]
2152 (123 (if (or in-double in-single
) ; {
2155 (125 (if (or in-double in-single
) ; }
2158 (44 (if (or in-double in-single
) ; ,
2159 (cons 44 out
) (cons 32 out
)))
2160 (39 (if in-double
; '
2162 (setq in-single
(not in-single
)) (cons 34 out
)))
2163 (34 (if in-single
; "
2164 (append (list 34 32) out
)
2165 (setq in-double
(not in-double
)) (cons 34 out
)))
2166 (t (cons ch out
)))))
2167 (string-to-list str
))
2168 (apply #'string
(reverse out
)))))
2171 (defun org-babel-read (cell &optional inhibit-lisp-eval
)
2172 "Convert the string value of CELL to a number if appropriate.
2173 Otherwise if cell looks like lisp (meaning it starts with a
2174 \"(\", \"'\", \"`\" or a \"[\") then read it as lisp, otherwise
2175 return it unmodified as a string. Optional argument NO-LISP-EVAL
2176 inhibits lisp evaluation for situations in which is it not
2178 (if (and (stringp cell
) (not (equal cell
"")))
2179 (or (org-babel-number-p cell
)
2180 (if (and (not inhibit-lisp-eval
)
2181 (member (substring cell
0 1) '("(" "'" "`" "[")))
2183 (if (string= (substring cell
0 1) "\"")
2185 (progn (set-text-properties 0 (length cell
) nil cell
) cell
))))
2188 (defun org-babel-number-p (string)
2189 "If STRING represents a number return it's value."
2190 (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string
)
2191 (= (length (substring string
(match-beginning 0)
2194 (string-to-number string
)))
2196 (defun org-babel-import-elisp-from-file (file-name &optional separator
)
2197 "Read the results located at FILE-NAME into an elisp table.
2198 If the table is trivial, then return it as a scalar."
2200 (save-window-excursion
2204 (org-table-import file-name separator
)
2205 (delete-file file-name
)
2206 (setq result
(mapcar (lambda (row)
2207 (mapcar #'org-babel-string-read row
))
2208 (org-table-to-lisp))))
2210 (if (null (cdr result
)) ;; if result is trivial vector, then scalarize it
2211 (if (consp (car result
))
2212 (if (null (cdr (car result
)))
2218 (defun org-babel-string-read (cell)
2219 "Strip nested \"s from around strings."
2220 (org-babel-read (or (and (stringp cell
)
2221 (string-match "\\\"\\(.+\\)\\\"" cell
)
2222 (match-string 1 cell
))
2225 (defun org-babel-reverse-string (string)
2226 "Return the reverse of STRING."
2227 (apply 'string
(reverse (string-to-list string
))))
2229 (defun org-babel-chomp (string &optional regexp
)
2230 "Strip trailing spaces and carriage returns from STRING.
2231 Default regexp used is \"[ \f\t\n\r\v]\" but can be
2232 overwritten by specifying a regexp as a second argument."
2233 (let ((regexp (or regexp
"[ \f\t\n\r\v]")))
2234 (while (and (> (length string
) 0)
2235 (string-match regexp
(substring string -
1)))
2236 (setq string
(substring string
0 -
1)))
2239 (defun org-babel-trim (string &optional regexp
)
2240 "Strip leading and trailing spaces and carriage returns from STRING.
2241 Like `org-babel-chomp' only it runs on both the front and back
2243 (org-babel-chomp (org-babel-reverse-string
2244 (org-babel-chomp (org-babel-reverse-string string
) regexp
))
2247 (defvar org-babel-org-babel-call-process-region-original nil
)
2248 (defun org-babel-tramp-handle-call-process-region
2249 (start end program
&optional delete buffer display
&rest args
)
2250 "Use tramp to handle call-process-region.
2251 Fixes a bug in `tramp-handle-call-process-region'."
2252 (if (and (featurep 'tramp
) (file-remote-p default-directory
))
2253 (let ((tmpfile (tramp-compat-make-temp-file "")))
2254 (write-region start end tmpfile
)
2255 (when delete
(delete-region start end
))
2257 ;; (apply 'call-process program tmpfile buffer display args)
2259 (apply 'process-file program tmpfile buffer display args
)
2260 (delete-file tmpfile
)))
2261 ;; org-babel-call-process-region-original is the original emacs
2262 ;; definition. It is in scope from the let binding in
2263 ;; org-babel-execute-src-block
2264 (apply org-babel-call-process-region-original
2265 start end program delete buffer display args
)))
2267 (defun org-babel-local-file-name (file)
2268 "Return the local name component of FILE."
2269 (if (file-remote-p file
)
2271 (with-parsed-tramp-file-name file nil
2275 (defun org-babel-process-file-name (name &optional no-quote-p
)
2276 "Prepare NAME to be used in an external process.
2277 If NAME specifies a remote location, the remote portion of the
2278 name is removed, since in that case the process will be executing
2279 remotely. The file name is then processed by
2280 `expand-file-name'. Unless second argument NO-QUOTE-P is non-nil,
2281 the file name is additionally processed by
2282 `shell-quote-argument'"
2283 ((lambda (f) (if no-quote-p f
(shell-quote-argument f
)))
2284 (expand-file-name (org-babel-local-file-name name
))))
2286 (defvar org-babel-temporary-directory
)
2287 (unless (or noninteractive
(boundp 'org-babel-temporary-directory
))
2288 (defvar org-babel-temporary-directory
2289 (or (and (boundp 'org-babel-temporary-directory
)
2290 (file-exists-p org-babel-temporary-directory
)
2291 org-babel-temporary-directory
)
2292 (make-temp-file "babel-" t
))
2293 "Directory to hold temporary files created to execute code blocks.
2294 Used by `org-babel-temp-file'. This directory will be removed on
2297 (defun org-babel-temp-file (prefix &optional suffix
)
2298 "Create a temporary file in the `org-babel-temporary-directory'.
2299 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2300 value of `temporary-file-directory' temporarily set to the value
2301 of `org-babel-temporary-directory'."
2302 (if (file-remote-p default-directory
)
2304 (concat (file-remote-p default-directory
)
2306 prefix temporary-file-directory
)
2308 (let ((temporary-file-directory
2309 (or (and (boundp 'org-babel-temporary-directory
)
2310 (file-exists-p org-babel-temporary-directory
)
2311 org-babel-temporary-directory
)
2312 temporary-file-directory
)))
2313 (make-temp-file prefix nil suffix
))))
2315 (defun org-babel-remove-temporary-directory ()
2316 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2317 (when (and (boundp 'org-babel-temporary-directory
)
2318 (file-exists-p org-babel-temporary-directory
))
2319 ;; taken from `delete-directory' in files.el
2322 (mapc (lambda (file)
2323 ;; This test is equivalent to
2324 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2325 ;; but more efficient
2326 (if (eq t
(car (file-attributes file
)))
2327 (delete-directory file
)
2328 (delete-file file
)))
2329 ;; We do not want to delete "." and "..".
2330 (directory-files org-babel-temporary-directory
'full
2331 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2332 (delete-directory org-babel-temporary-directory
))
2334 (message "Failed to remove temporary Org-babel directory %s"
2335 (if (boundp 'org-babel-temporary-directory
)
2336 org-babel-temporary-directory
2337 "[directory not defined]"))))))
2339 (add-hook 'kill-emacs-hook
'org-babel-remove-temporary-directory
)