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 (defvar org-babel-inline-lob-one-liner-regexp
)
185 (defun org-babel-get-lob-one-liner-matches()
186 "Set match data if on line of an lob one liner.
187 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."
1050 (org-babel-parse-multiple-vars
1053 (lambda (header-arg)
1054 (and (setq val
(org-entry-get (point) header-arg t
))
1055 (cons (intern (concat ":" header-arg
))
1056 (org-babel-read val
))))
1060 org-babel-header-arg-names
1062 (setq sym
(intern (concat "org-babel-header-arg-names:"
1064 (and (boundp sym
) (eval sym
)))))))))))
1066 (defvar org-src-preserve-indentation
)
1067 (defun org-babel-parse-src-block-match ()
1068 "Parse the results from a match of the `org-babel-src-block-regexp'."
1069 (let* ((block-indentation (length (match-string 1)))
1070 (lang (org-babel-clean-text-properties (match-string 2)))
1071 (lang-headers (intern (concat "org-babel-default-header-args:" lang
)))
1072 (switches (match-string 3))
1073 (body (org-babel-clean-text-properties
1074 (let* ((body (match-string 5))
1075 (sub-length (- (length body
) 1)))
1076 (if (and (> sub-length
0)
1077 (string= "\n" (substring body sub-length
)))
1078 (substring body
0 sub-length
)
1080 (preserve-indentation (or org-src-preserve-indentation
1081 (string-match "-i\\>" switches
))))
1083 ;; get block body less properties, protective commas, and indentation
1086 (insert (org-babel-strip-protective-commas body
))
1087 (unless preserve-indentation
(org-do-remove-indentation))
1089 (org-babel-merge-params
1090 org-babel-default-header-args
1091 (org-babel-params-from-properties lang
)
1092 (if (boundp lang-headers
) (eval lang-headers
) nil
)
1093 (org-babel-parse-header-arguments
1094 (org-babel-clean-text-properties (or (match-string 4) ""))))
1096 block-indentation
)))
1098 (defun org-babel-parse-inline-src-block-match ()
1099 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
1100 (let* ((lang (org-babel-clean-text-properties (match-string 2)))
1101 (lang-headers (intern (concat "org-babel-default-header-args:" lang
))))
1103 (org-babel-strip-protective-commas
1104 (org-babel-clean-text-properties (match-string 5)))
1105 (org-babel-merge-params
1106 org-babel-default-inline-header-args
1107 (org-babel-params-from-properties lang
)
1108 (if (boundp lang-headers
) (eval lang-headers
) nil
)
1109 (org-babel-parse-header-arguments
1110 (org-babel-clean-text-properties (or (match-string 4) "")))))))
1112 (defun org-babel-balanced-split (string alts
)
1113 "Split STRING on instances of ALTS.
1114 ALTS is a cons of two character options where each option may be
1115 either the numeric code of a single character or a list of
1116 character alternatives. For example to split on balanced
1117 instances of \"[ \t]:\" set ALTS to '((32 9) . 58)."
1118 (flet ((matches (ch spec
) (or (and (numberp spec
) (= spec ch
))
1121 (and (matches ch
(cdr alts
))
1122 (matches last
(car alts
)))))
1123 (let ((balance 0) (partial nil
) (lst nil
) (last 0))
1124 (mapc (lambda (ch) ; split on [] or () balanced instances of [ \t]:
1125 (setq balance
(+ balance
1126 (cond ((or (equal 91 ch
) (equal 40 ch
)) 1)
1127 ((or (equal 93 ch
) (equal 41 ch
)) -
1)
1129 (setq partial
(cons ch partial
))
1130 (when (and (= balance
0) (matched ch last
))
1131 (setq lst
(cons (apply #'string
(nreverse (cddr partial
)))
1135 (string-to-list string
))
1136 (nreverse (cons (apply #'string
(nreverse partial
)) lst
)))))
1138 (defun org-babel-parse-header-arguments (arg-string)
1139 "Parse a string of header arguments returning an alist."
1140 (when (> (length arg-string
) 0)
1141 (org-babel-parse-multiple-vars
1146 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1148 (cons (intern (match-string 1 arg
))
1149 (org-babel-read (org-babel-chomp (match-string 2 arg
))))
1150 (cons (intern (org-babel-chomp arg
)) nil
)))
1152 (cons (car raw
) (mapcar (lambda (r) (concat ":" r
)) (cdr raw
))))
1153 (org-babel-balanced-split arg-string
'((32 9) .
58))))))))
1155 (defun org-babel-parse-multiple-vars (header-arguments)
1156 "Expand multiple variable assignments behind a single :var keyword.
1158 This allows expression of multiple variables with one :var as
1161 #+PROPERTY: var foo=1, bar=2"
1163 (mapc (lambda (pair)
1164 (if (eq (car pair
) :var
)
1165 (mapcar (lambda (v) (push (cons :var
(org-babel-trim v
)) results
))
1166 (org-babel-balanced-split (cdr pair
) '(44 .
(32 9))))
1167 (push pair results
)))
1169 (nreverse results
)))
1171 (defun org-babel-process-params (params)
1172 "Expand variables in PARAMS and add summary parameters."
1173 (let* ((vars-and-names (if (and (assoc :colname-names params
)
1174 (assoc :rowname-names params
))
1176 (org-babel-get-header params
:var
)))
1177 (org-babel-disassemble-tables
1178 (mapcar (lambda (el)
1179 (if (consp (cdr el
))
1181 (org-babel-ref-parse (cdr el
))))
1182 (org-babel-get-header params
:var
))
1183 (cdr (assoc :hlines params
))
1184 (cdr (assoc :colnames params
))
1185 (cdr (assoc :rownames params
)))))
1186 (raw-result (or (cdr (assoc :results params
)) ""))
1187 (result-params (append
1188 (split-string (if (stringp raw-result
)
1191 (cdr (assoc :result-params params
)))))
1193 (mapcar (lambda (var) (cons :var var
)) (car vars-and-names
))
1195 (cons :colname-names
(or (cdr (assoc :colname-names params
))
1196 (cadr vars-and-names
)))
1197 (cons :rowname-names
(or (cdr (assoc :rowname-names params
))
1198 (caddr vars-and-names
)))
1199 (cons :result-params result-params
)
1200 (cons :result-type
(cond ((member "output" result-params
) 'output
)
1201 ((member "value" result-params
) 'value
)
1203 (org-babel-get-header params
:var
'other
))))
1205 ;; row and column names
1206 (defun org-babel-del-hlines (table)
1207 "Remove all 'hlines from TABLE."
1208 (remove 'hline table
))
1210 (defun org-babel-get-colnames (table)
1211 "Return the column names of TABLE.
1212 Return a cons cell, the `car' of which contains the TABLE less
1213 colnames, and the `cdr' of which contains a list of the column
1215 (if (equal 'hline
(nth 1 table
))
1216 (cons (cddr table
) (car table
))
1217 (cons (cdr table
) (car table
))))
1219 (defun org-babel-get-rownames (table)
1220 "Return the row names of TABLE.
1221 Return a cons cell, the `car' of which contains the TABLE less
1222 colnames, and the `cdr' of which contains a list of the column
1223 names. Note: this function removes any hlines in TABLE."
1224 (flet ((trans (table) (apply #'mapcar
* #'list table
)))
1225 (let* ((width (apply 'max
1226 (mapcar (lambda (el) (if (listp el
) (length el
) 0)) table
)))
1227 (table (trans (mapcar (lambda (row)
1228 (if (not (equal row
'hline
))
1232 (setq row
(cons 'hline row
)))
1235 (cons (mapcar (lambda (row) (if (equal (car row
) 'hline
) 'hline row
))
1236 (trans (cdr table
)))
1237 (remove 'hline
(car table
))))))
1239 (defun org-babel-put-colnames (table colnames
)
1240 "Add COLNAMES to TABLE if they exist."
1241 (if colnames
(apply 'list colnames
'hline table
) table
))
1243 (defun org-babel-put-rownames (table rownames
)
1244 "Add ROWNAMES to TABLE if they exist."
1246 (mapcar (lambda (row)
1248 (cons (or (pop rownames
) "") row
)
1252 (defun org-babel-pick-name (names selector
)
1253 "Select one out of an alist of row or column names.
1254 SELECTOR can be either a list of names in which case those names
1255 will be returned directly, or an index into the list NAMES in
1256 which case the indexed names will be return."
1257 (if (listp selector
)
1260 (if (and selector
(symbolp selector
) (not (equal t selector
)))
1261 (cdr (assoc selector names
))
1262 (if (integerp selector
)
1263 (nth (- selector
1) names
)
1264 (cdr (car (last names
))))))))
1266 (defun org-babel-disassemble-tables (vars hlines colnames rownames
)
1267 "Parse tables for further processing.
1268 Process the variables in VARS according to the HLINES,
1269 ROWNAMES and COLNAMES header arguments. Return a list consisting
1270 of the vars, cnames and rnames."
1271 (let (cnames rnames
)
1275 (when (listp (cdr var
))
1276 (when (and (not (equal colnames
"no"))
1277 (or colnames
(and (equal (nth 1 (cdr var
)) 'hline
)
1278 (not (member 'hline
(cddr (cdr var
)))))))
1279 (let ((both (org-babel-get-colnames (cdr var
))))
1280 (setq cnames
(cons (cons (car var
) (cdr both
))
1282 (setq var
(cons (car var
) (car both
)))))
1283 (when (and rownames
(not (equal rownames
"no")))
1284 (let ((both (org-babel-get-rownames (cdr var
))))
1285 (setq rnames
(cons (cons (car var
) (cdr both
))
1287 (setq var
(cons (car var
) (car both
)))))
1288 (when (and hlines
(not (equal hlines
"yes")))
1289 (setq var
(cons (car var
) (org-babel-del-hlines (cdr var
))))))
1292 (reverse cnames
) (reverse rnames
))))
1294 (defun org-babel-reassemble-table (table colnames rownames
)
1295 "Add column and row names to a table.
1296 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1297 to the table for reinsertion to org-mode."
1300 (if (and colnames
(listp (car table
)) (= (length (car table
))
1302 (org-babel-put-colnames table colnames
) table
))
1303 (if (and rownames
(= (length table
) (length rownames
)))
1304 (org-babel-put-rownames table rownames
) table
))
1307 (defun org-babel-where-is-src-block-head ()
1308 "Find where the current source block begins.
1309 Return the point at the beginning of the current source
1310 block. Specifically at the beginning of the #+BEGIN_SRC line.
1311 If the point is not on a source block then return nil."
1312 (let ((initial (point)) top bottom
)
1314 (save-excursion ;; on a source name line or a #+header line
1315 (beginning-of-line 1)
1316 (and (or (looking-at org-babel-src-name-regexp
)
1317 (looking-at org-babel-multi-line-header-regexp
))
1319 (while (and (forward-line 1)
1320 (looking-at org-babel-multi-line-header-regexp
)))
1321 (looking-at org-babel-src-block-regexp
))
1323 (save-excursion ;; on a #+begin_src line
1324 (beginning-of-line 1)
1325 (and (looking-at org-babel-src-block-regexp
)
1327 (save-excursion ;; inside a src block
1329 (re-search-backward "^[ \t]*#\\+begin_src" nil t
) (setq top
(point))
1330 (re-search-forward "^[ \t]*#\\+end_src" nil t
) (setq bottom
(point))
1331 (< top initial
) (< initial bottom
)
1332 (progn (goto-char top
) (beginning-of-line 1)
1333 (looking-at org-babel-src-block-regexp
))
1337 (defun org-babel-goto-src-block-head ()
1338 "Go to the beginning of the current code block."
1341 (if head
(goto-char head
) (error "not currently in a code block")))
1342 (org-babel-where-is-src-block-head)))
1345 (defun org-babel-goto-named-src-block (name)
1346 "Go to a named source-code block."
1348 (let ((completion-ignore-case t
))
1349 (list (org-icompleting-read "source-block name: "
1350 (org-babel-src-block-names) nil t
))))
1351 (let ((point (org-babel-find-named-block name
)))
1353 ;; taken from `org-open-at-point'
1354 (progn (goto-char point
) (org-show-context))
1355 (message "source-code block '%s' not found in this buffer" name
))))
1357 (defun org-babel-find-named-block (name)
1358 "Find a named source-code block.
1359 Return the location of the source block identified by source
1360 NAME, or nil if no such block exists. Set match data according to
1361 org-babel-named-src-block-regexp."
1363 (let ((case-fold-search t
)
1364 (regexp (org-babel-named-src-block-regexp-for-name name
)) msg
)
1365 (goto-char (point-min))
1366 (when (or (re-search-forward regexp nil t
)
1367 (re-search-backward regexp nil t
))
1368 (match-beginning 0)))))
1370 (defun org-babel-src-block-names (&optional file
)
1371 "Returns the names of source blocks in FILE or the current buffer."
1373 (when file
(find-file file
)) (goto-char (point-min))
1375 (while (re-search-forward org-babel-src-name-w-name-regexp nil t
)
1376 (setq names
(cons (match-string 4) names
)))
1380 (defun org-babel-goto-named-result (name)
1381 "Go to a named result."
1383 (let ((completion-ignore-case t
))
1384 (list (org-icompleting-read "source-block name: "
1385 (org-babel-result-names) nil t
))))
1386 (let ((point (org-babel-find-named-result name
)))
1388 ;; taken from `org-open-at-point'
1389 (progn (goto-char point
) (org-show-context))
1390 (message "result '%s' not found in this buffer" name
))))
1392 (defun org-babel-find-named-result (name)
1393 "Find a named result.
1394 Return the location of the result named NAME in the current
1395 buffer or nil if no such result exists."
1397 (goto-char (point-min))
1398 (when (re-search-forward
1399 (concat org-babel-result-regexp
1400 "[ \t]" (regexp-quote name
) "[ \t\n\f\v\r]") nil t
)
1401 (beginning-of-line 0) (point))))
1403 (defun org-babel-result-names (&optional file
)
1404 "Returns the names of results in FILE or the current buffer."
1406 (when file
(find-file file
)) (goto-char (point-min))
1408 (while (re-search-forward org-babel-result-w-name-regexp nil t
)
1409 (setq names
(cons (match-string 4) names
)))
1413 (defun org-babel-next-src-block (&optional arg
)
1414 "Jump to the next source block.
1415 With optional prefix argument ARG, jump forward ARG many source blocks."
1417 (when (looking-at org-babel-src-block-regexp
) (forward-char 1))
1419 (re-search-forward org-babel-src-block-regexp nil nil
(or arg
1))
1420 (error (error "No further code blocks")))
1421 (goto-char (match-beginning 0)) (org-show-context))
1424 (defun org-babel-previous-src-block (&optional arg
)
1425 "Jump to the previous source block.
1426 With optional prefix argument ARG, jump backward ARG many source blocks."
1429 (re-search-backward org-babel-src-block-regexp nil nil
(or arg
1))
1430 (error (error "No previous code blocks")))
1431 (goto-char (match-beginning 0)) (org-show-context))
1433 (defvar org-babel-load-languages
)
1436 (defun org-babel-mark-block ()
1437 "Mark current src block"
1443 (looking-at org-babel-src-block-regexp
))
1444 (push-mark (match-end 5) nil t
)
1445 (goto-char (match-beginning 5))))
1446 (org-babel-where-is-src-block-head)))
1448 (defun org-babel-demarcate-block (&optional arg
)
1449 "Wrap or split the code in the region or on the point.
1450 When called from inside of a code block the current block is
1451 split. When called from outside of a code block a new code block
1452 is created. In both cases if the region is demarcated and if the
1453 region is not active then the point is demarcated."
1455 (let ((info (org-babel-get-src-block-info 'light
))
1456 (headers (progn (org-babel-where-is-src-block-head)
1458 (stars (concat (make-string (or (org-current-level) 1) ?
*) " ")))
1464 (let ((lang (nth 0 info
))
1465 (indent (make-string (nth 5 info
) ?
)))
1466 (when (string-match "^[[:space:]]*$"
1467 (buffer-substring (point-at-bol)
1469 (delete-region (point-at-bol) (point-at-eol)))
1471 (if (looking-at "^") "" "\n")
1472 indent
"#+end_src\n"
1473 (if arg stars indent
) "\n"
1474 indent
"#+begin_src " lang
1475 (if (> (length headers
) 1)
1476 (concat " " headers
) headers
)
1477 (if (looking-at "[\n\r]")
1479 (concat "\n" (make-string (current-column) ?
)))))))
1480 (move-end-of-line 2))
1481 (sort (if (region-active-p) (list (mark) (point)) (list (point))) #'>))
1482 (let ((start (point))
1483 (lang (org-icompleting-read "Lang: "
1484 (mapcar (lambda (el) (symbol-name (car el
)))
1485 org-babel-load-languages
)))
1486 (body (delete-and-extract-region
1487 (if (region-active-p) (mark) (point)) (point))))
1488 (insert (concat (if (looking-at "^") "" "\n")
1489 (if arg
(concat stars
"\n") "")
1490 "#+begin_src " lang
"\n"
1492 (if (or (= (length body
) 0)
1493 (string-match "[\r\n]$" body
)) "" "\n")
1495 (goto-char start
) (move-end-of-line 1)))))
1497 (defvar org-babel-lob-one-liner-regexp
)
1498 (defun org-babel-where-is-src-block-result (&optional insert info hash indent
)
1499 "Find where the current source block results begin.
1500 Return the point at the beginning of the result of the current
1501 source block. Specifically at the beginning of the results line.
1502 If no result exists for this block then create a results line
1503 following the source block."
1505 (let* ((on-lob-line (save-excursion
1506 (beginning-of-line 1)
1507 (looking-at org-babel-lob-one-liner-regexp
)))
1508 (inlinep (when (org-babel-get-inline-src-block-matches)
1510 (name (if on-lob-line
1511 (nth 0 (org-babel-lob-get-info))
1512 (nth 4 (or info
(org-babel-get-src-block-info 'light
)))))
1513 (head (unless on-lob-line
(org-babel-where-is-src-block-head)))
1515 (when head
(goto-char head
))
1517 found
;; was there a result (before we potentially insert one)
1522 ;; - return t if it is found, else return nil
1523 ;; - if it does not need to be rebuilt, then don't set end
1524 ;; - if it does need to be rebuilt then do set end
1525 name
(setq beg
(org-babel-find-named-result name
))
1527 (when (and hash
(not (string= hash
(match-string 3))))
1528 (goto-char beg
) (setq end beg
) ;; beginning of result
1530 (delete-region end
(org-babel-result-end)) nil
)))
1533 ;; - return t if it is found, else return nil
1534 ;; - if it is found, and the hash doesn't match, delete and set end
1535 (or on-lob-line
(re-search-forward "^[ \t]*#\\+end_src" nil t
))
1536 (progn (end-of-line 1)
1537 (if (eobp) (insert "\n") (forward-char 1))
1540 (progn ;; unnamed results line already exists
1541 (re-search-forward "[^ \f\t\n\r\v]" nil t
)
1542 (beginning-of-line 1)
1544 (concat org-babel-result-regexp
"\n")))
1546 ;; must remove and rebuild if hash!=old-hash
1547 (if (and hash
(not (string= hash
(match-string 3))))
1551 end
(org-babel-result-end)))
1552 (setq end nil
)))))))))
1553 (if (and insert end
)
1557 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1562 (org-number-sequence 1 indent
) "")
1565 (when hash
(concat "["hash
"]"))
1567 (when name
(concat " " name
)) "\n"))
1568 (unless beg
(insert "\n") (backward-char))
1569 (beginning-of-line 0)
1570 (if hash
(org-babel-hide-hash))
1574 (defvar org-block-regexp
)
1575 (defun org-babel-read-result ()
1576 "Read the result at `point' into emacs-lisp."
1577 (let ((case-fold-search t
) result-string
)
1579 ((org-at-table-p) (org-babel-read-table))
1580 ((org-at-item-p) (org-babel-read-list))
1581 ((looking-at org-bracket-link-regexp
) (org-babel-read-link))
1582 ((looking-at org-block-regexp
) (org-babel-trim (match-string 4)))
1583 ((looking-at "^[ \t]*: ")
1586 (mapconcat (lambda (line)
1587 (if (and (> (length line
) 1)
1588 (string-match "^[ \t]*: \\(.+\\)" line
))
1589 (match-string 1 line
)
1593 (point) (org-babel-result-end)) "[\r\n]+")
1595 (or (org-babel-number-p result-string
) result-string
))
1596 ((looking-at org-babel-result-regexp
)
1597 (save-excursion (forward-line 1) (org-babel-read-result))))))
1599 (defun org-babel-read-table ()
1600 "Read the table at `point' into emacs-lisp."
1601 (mapcar (lambda (row)
1602 (if (and (symbolp row
) (equal row
'hline
)) row
1603 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
)) row
)))
1604 (org-table-to-lisp)))
1606 (defun org-babel-read-list ()
1607 "Read the list at `point' into emacs-lisp."
1608 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
))
1609 (mapcar #'cadr
(cdr (org-list-parse-list)))))
1611 (defvar org-link-types-re
)
1612 (defun org-babel-read-link ()
1613 "Read the link at `point' into emacs-lisp.
1614 If the path of the link is a file path it is expanded using
1615 `expand-file-name'."
1616 (let* ((case-fold-search t
)
1617 (raw (and (looking-at org-bracket-link-regexp
)
1618 (org-babel-clean-text-properties (match-string 1))))
1619 (type (and (string-match org-link-types-re raw
)
1620 (match-string 1 raw
))))
1622 ((not type
) (expand-file-name raw
))
1623 ((string= type
"file")
1624 (and (string-match "file\\(.*\\):\\(.+\\)" raw
)
1625 (expand-file-name (match-string 2 raw
))))
1628 (defun org-babel-format-result (result &optional sep
)
1629 "Format RESULT for writing to file."
1630 (flet ((echo-res (result)
1631 (if (stringp result
) result
(format "%S" result
))))
1640 (echo-res result
))))
1642 (defun org-babel-insert-result
1643 (result &optional result-params info hash indent lang
)
1644 "Insert RESULT into the current buffer.
1645 By default RESULT is inserted after the end of the
1646 current source block. With optional argument RESULT-PARAMS
1647 controls insertion of results in the org-mode file.
1648 RESULT-PARAMS can take the following values...
1650 replace - (default option) insert results after the source block
1651 replacing any previously inserted results
1653 silent -- no results are inserted
1655 file ---- the results are interpreted as a file path, and are
1656 inserted into the buffer using the Org-mode file syntax
1658 list ---- the results are interpreted as an Org-mode list.
1660 raw ----- results are added directly to the Org-mode file. This
1661 is a good option if you code block will output org-mode
1664 org ----- similar in effect to raw, only the results are wrapped
1665 in an org code block. Similar to the raw option, on
1666 export the results will be interpreted as org-formatted
1667 text, however by wrapping the results in an org code
1668 block they can be replaced upon re-execution of the
1671 html ---- results are added inside of a #+BEGIN_HTML block. This
1672 is a good option if you code block will output html
1675 latex --- results are added inside of a #+BEGIN_LATEX block.
1676 This is a good option if you code block will output
1677 latex formatted text.
1679 code ---- the results are extracted in the syntax of the source
1680 code of the language being evaluated and are added
1681 inside of a #+BEGIN_SRC block with the source-code
1682 language set appropriately. Note this relies on the
1683 optional LANG argument."
1684 (if (stringp result
)
1686 (setq result
(org-babel-clean-text-properties result
))
1687 (when (member "file" result-params
)
1688 (setq result
(org-babel-result-to-file result
))))
1689 (unless (listp result
) (setq result
(format "%S" result
))))
1690 (if (and result-params
(member "silent" result-params
))
1692 (message (replace-regexp-in-string "%" "%%" (format "%S" result
)))
1697 (when (or (org-babel-get-inline-src-block-matches)
1698 (org-babel-get-lob-one-liner-matches))
1699 (goto-char (match-end 0))
1700 (insert (if (listp result
) "\n" " "))
1702 (existing-result (unless inlinep
1703 (org-babel-where-is-src-block-result
1704 t info hash indent
)))
1706 (cdr (assoc :results_switches
(nth 2 info
))))
1708 (when (and (stringp result
) ; ensure results end in a newline
1710 (> (length result
) 0)
1711 (not (or (string-equal (substring result -
1) "\n")
1712 (string-equal (substring result -
1) "\r"))))
1713 (setq result
(concat result
"\n")))
1714 (if (not existing-result
)
1715 (setq beg
(or inlinep
(point)))
1716 (goto-char existing-result
)
1718 (re-search-forward "#" nil t
)
1719 (setq indent
(- (current-column) 1)))
1723 ((member "replace" result-params
)
1724 (delete-region (point) (org-babel-result-end)))
1725 ((member "append" result-params
)
1726 (goto-char (org-babel-result-end)) (setq beg
(point-marker)))
1727 ((member "prepend" result-params
)))) ; already there
1728 (setq results-switches
1729 (if results-switches
(concat " " results-switches
) ""))
1730 ;; insert results based on type
1732 ;; do nothing for an empty result
1733 ((= (length result
) 0))
1734 ;; insert a list if preferred
1735 ((member "list" result-params
)
1738 (org-list-to-generic
1741 (lambda (el) (list nil
(if (stringp el
) el
(format "%S" el
))))
1742 (if (listp result
) result
(list result
))))
1743 '(:splicep nil
:istart
"- " :iend
"\n")))
1745 ;; assume the result is a table if it's not a string
1746 ((not (stringp result
))
1748 (insert (concat (orgtbl-to-orgtbl
1749 (if (or (eq 'hline
(car result
))
1750 (and (listp (car result
))
1751 (listp (cdr (car result
)))))
1752 result
(list result
))
1753 '(:fmt
(lambda (cell) (format "%s" cell
)))) "\n"))
1754 (goto-char beg
) (when (org-at-table-p) (org-table-align)))
1755 ((member "file" result-params
)
1756 (when inlinep
(goto-char inlinep
))
1758 (t (goto-char beg
) (insert result
)))
1759 (when (listp result
) (goto-char (org-table-end)))
1760 (setq end
(point-marker))
1761 ;; possibly wrap result
1762 (flet ((wrap (start finish
)
1763 (goto-char beg
) (insert (concat start
"\n"))
1764 (goto-char end
) (insert (concat finish
"\n"))
1765 (setq end
(point-marker))))
1767 ((member "html" result-params
)
1768 (wrap "#+BEGIN_HTML" "#+END_HTML"))
1769 ((member "latex" result-params
)
1770 (wrap "#+BEGIN_LaTeX" "#+END_LaTeX"))
1771 ((member "code" result-params
)
1772 (wrap (format "#+BEGIN_SRC %s%s" (or lang
"none") results-switches
)
1774 ((member "org" result-params
)
1775 (wrap "#+BEGIN_ORG" "#+END_ORG"))
1776 ((member "raw" result-params
)
1777 (goto-char beg
) (if (org-at-table-p) (org-cycle)))
1778 ((member "wrap" result-params
)
1779 (when (and (stringp result
) (not (member "file" result-params
)))
1780 (org-babel-examplize-region beg end results-switches
))
1781 (wrap "#+BEGIN_RESULT" "#+END_RESULT"))
1782 ((and (stringp result
) (not (member "file" result-params
)))
1783 (org-babel-examplize-region beg end results-switches
)
1784 (setq end
(point)))))
1785 ;; possibly indent the results to match the #+results line
1786 (when (and (not inlinep
) (numberp indent
) indent
(> indent
0)
1787 ;; in this case `table-align' does the work for us
1788 (not (and (listp result
)
1789 (member "append" result-params
))))
1790 (indent-rigidly beg end indent
))))
1791 (if (= (length result
) 0)
1792 (if (member "value" result-params
)
1793 (message "Code block returned no value.")
1794 (message "Code block produced no output."))
1795 (message "Code block evaluation complete."))))
1797 (defun org-babel-remove-result (&optional info
)
1798 "Remove the result of the current source block."
1800 (let ((location (org-babel-where-is-src-block-result nil info
)) start
)
1802 (setq start
(- location
1))
1804 (goto-char location
) (forward-line 1)
1805 (delete-region start
(org-babel-result-end))))))
1807 (defun org-babel-result-end ()
1808 "Return the point at the end of the current set of results"
1811 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
1812 ((org-at-item-p) (let* ((struct (org-list-struct))
1813 (prvs (org-list-prevs-alist struct
)))
1814 (org-list-get-list-end (point-at-bol) struct prvs
)))
1816 (let ((case-fold-search t
)
1817 (blocks-re (regexp-opt
1818 (list "latex" "html" "example" "src" "result" "org"))))
1819 (if (looking-at (concat "[ \t]*#\\+begin_" blocks-re
))
1820 (progn (re-search-forward (concat "[ \t]*#\\+end_" blocks-re
) nil t
)
1822 (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
1826 (defun org-babel-result-to-file (result)
1827 "Convert RESULT into an `org-mode' link.
1828 If the `default-directory' is different from the containing
1829 file's directory then expand relative links."
1830 (flet ((cond-exp (file)
1831 (if (and default-directory
1833 (not (string= (expand-file-name default-directory
)
1835 (file-name-directory buffer-file-name
)))))
1836 (expand-file-name file default-directory
)
1838 (if (stringp result
)
1839 (format "[[file:%s]]" (cond-exp result
))
1840 (when (and (listp result
) (= 2 (length result
))
1841 (stringp (car result
)) (stringp (cadr result
)))
1842 (format "[[file:%s][%s]]" (car result
) (cadr result
))))))
1844 (defun org-babel-examplize-region (beg end
&optional results-switches
)
1845 "Comment out region using the inline '==' or ': ' org example quote."
1847 (flet ((chars-between (b e
) (string-match "[\\S]" (buffer-substring b e
))))
1848 (if (or (chars-between (save-excursion (goto-char beg
) (point-at-bol)) beg
)
1849 (chars-between end
(save-excursion (goto-char end
) (point-at-eol))))
1852 (insert (format "=%s=" (prog1 (buffer-substring beg end
)
1853 (delete-region beg end
)))))
1854 (let ((size (count-lines beg end
)))
1856 (cond ((= size
0)) ; do nothing for an empty result
1857 ((< size org-babel-min-lines-for-block-output
)
1860 (beginning-of-line 1) (insert ": ") (forward-line 1)))
1863 (insert (if results-switches
1864 (format "#+begin_example%s\n" results-switches
)
1865 "#+begin_example\n"))
1866 (if (markerp end
) (goto-char end
) (forward-char (- end beg
)))
1867 (insert "#+end_example\n"))))))))
1869 (defun org-babel-update-block-body (new-body)
1870 "Update the body of the current code block to NEW-BODY."
1871 (if (not (org-babel-where-is-src-block-head))
1872 (error "not in source block")
1874 (replace-match (concat (org-babel-trim new-body
) "\n") nil t nil
5))
1875 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
1877 (defun org-babel-merge-params (&rest plists
)
1878 "Combine all parameter association lists in PLISTS.
1879 Later elements of PLISTS override the values of previous elements.
1880 This takes into account some special considerations for certain
1881 parameters when merging lists."
1882 (let ((results-exclusive-groups
1883 (mapcar (lambda (group) (mapcar #'symbol-name group
))
1884 (cdr (assoc 'results org-babel-common-header-args-w-values
))))
1885 (exports-exclusive-groups
1886 (mapcar (lambda (group) (mapcar #'symbol-name group
))
1887 (cdr (assoc 'exports org-babel-common-header-args-w-values
))))
1889 params results exports tangle noweb cache vars shebang comments padline
)
1890 (flet ((e-merge (exclusive-groups &rest result-params
)
1891 ;; maintain exclusivity of mutually exclusive parameters
1893 (mapc (lambda (new-params)
1894 (mapc (lambda (new-param)
1895 (mapc (lambda (exclusive-group)
1896 (when (member new-param exclusive-group
)
1897 (mapcar (lambda (excluded-param)
1904 (setq output
(org-uniquify
1905 (cons new-param output
))))
1915 (let ((name (if (listp (cdr pair
))
1917 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
1919 (intern (match-string 1 (cdr pair
)))))))
1923 (if (member name
(mapcar #'car vars
))
1927 (unless (equal (car p
) name
) p
))
1930 (list (cons name pair
))))
1931 ;; if no name is given and we already have named variables
1932 ;; then assign to named variables in order
1933 (if (and vars
(nth variable-index vars
))
1934 (prog1 (setf (cddr (nth variable-index vars
))
1935 (concat (symbol-name
1936 (car (nth variable-index vars
)))
1938 (incf variable-index
))
1939 (error "variable \"%s\" must be assigned a default value"
1942 (setq results
(e-merge results-exclusive-groups
1945 (let ((r (cdr pair
)))
1946 (if (stringp r
) r
(eval r
)))))))
1949 (setq results
(e-merge results-exclusive-groups
1951 (unless (or (member "both" exports
)
1952 (member "none" exports
)
1953 (member "code" exports
))
1954 (setq exports
(e-merge exports-exclusive-groups
1955 exports
'("results"))))
1956 (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))
1958 (setq exports
(e-merge exports-exclusive-groups
1959 exports
(split-string (cdr pair
)))))
1960 (:tangle
;; take the latest -- always overwrite
1961 (setq tangle
(or (list (cdr pair
)) tangle
)))
1963 (setq noweb
(e-merge '(("yes" "no" "tangle")) noweb
1964 (split-string (or (cdr pair
) "")))))
1966 (setq cache
(e-merge '(("yes" "no")) cache
1967 (split-string (or (cdr pair
) "")))))
1969 (setq padline
(e-merge '(("yes" "no")) padline
1970 (split-string (or (cdr pair
) "")))))
1971 (:shebang
;; take the latest -- always overwrite
1972 (setq shebang
(or (list (cdr pair
)) shebang
)))
1974 (setq comments
(e-merge '(("yes" "no")) comments
1975 (split-string (or (cdr pair
) "")))))
1976 (t ;; replace: this covers e.g. :session
1977 (setq params
(cons pair
(assq-delete-all (car pair
) params
))))))
1980 (setq vars
(reverse vars
))
1981 (while vars
(setq params
(cons (cons :var
(cddr (pop vars
))) params
)))
1984 (let ((key (intern (concat ":" (symbol-name hd
))))
1986 (setf params
(cons (cons key
(mapconcat 'identity val
" ")) params
))))
1987 '(results exports tangle noweb padline cache shebang comments
))
1990 (defun org-babel-expand-noweb-references (&optional info parent-buffer
)
1991 "Expand Noweb references in the body of the current source code block.
1993 For example the following reference would be replaced with the
1994 body of the source-code block named 'example-block'.
1998 Note that any text preceding the <<foo>> construct on a line will
1999 be interposed between the lines of the replacement text. So for
2000 example if <<foo>> is placed behind a comment, then the entire
2001 replacement text will also be commented.
2003 This function must be called from inside of the buffer containing
2004 the source-code block which holds BODY.
2006 In addition the following syntax can be used to insert the
2007 results of evaluating the source-code block named 'example-block'.
2011 Any optional arguments can be passed to example-block by placing
2012 the arguments inside the parenthesis following the convention
2013 defined by `org-babel-lob'. For example
2015 <<example-block(a=9)>>
2017 would set the value of argument \"a\" equal to \"9\". Note that
2018 these arguments are not evaluated in the current source-code
2019 block but are passed literally to the \"example-block\"."
2020 (let* ((parent-buffer (or parent-buffer
(current-buffer)))
2021 (info (or info
(org-babel-get-src-block-info)))
2024 (comment (string= "noweb" (cdr (assoc :comments
(nth 2 info
)))))
2025 (new-body "") index source-name evaluate prefix blocks-in-buffer
)
2026 (flet ((nb-add (text) (setq new-body
(concat new-body text
)))
2029 (funcall (intern (concat lang
"-mode")))
2030 (comment-region (point) (progn (insert text
) (point)))
2031 (org-babel-trim (buffer-string))))
2032 (blocks () ;; return the info lists of all blocks in this buffer
2036 (org-babel-map-src-blocks nil
2037 (setq infos
(cons (org-babel-get-src-block-info 'light
)
2041 (insert body
) (goto-char (point-min))
2042 (setq index
(point))
2043 (while (and (re-search-forward "<<\\(.+?\\)>>" nil t
))
2044 (save-match-data (setf source-name
(match-string 1)))
2045 (save-match-data (setq evaluate
(string-match "\(.*\)" source-name
)))
2048 (buffer-substring (match-beginning 0)
2050 (beginning-of-line 1) (point)))))
2051 ;; add interval to new-body (removing noweb reference)
2052 (goto-char (match-beginning 0))
2053 (nb-add (buffer-substring index
(point)))
2054 (goto-char (match-end 0))
2055 (setq index
(point))
2057 (with-current-buffer parent-buffer
2058 (mapconcat ;; interpose PREFIX between every line
2062 (let ((raw (org-babel-ref-resolve source-name
)))
2063 (if (stringp raw
) raw
(format "%S" raw
)))
2065 ;; retrieve from the library of babel
2066 (nth 2 (assoc (intern source-name
)
2067 org-babel-library-of-babel
))
2068 ;; return the contents of headlines literally
2070 (when (org-babel-ref-goto-headline-id source-name
)
2071 (org-babel-ref-headline-body)))
2072 ;; find the expansion of reference in this buffer
2075 (when (string= source-name
2076 (or (cdr (assoc :noweb-ref
(nth 2 i
)))
2078 (let ((body (org-babel-expand-noweb-references i
)))
2081 (concat (c-wrap (car cs
)) "\n"
2082 body
"\n" (c-wrap (cadr cs
))))
2083 (org-babel-tangle-comment-links i
))
2085 (or blocks-in-buffer
2086 (setq blocks-in-buffer
(blocks)))
2088 ;; possibly raise an error if named block doesn't exist
2089 (if (member lang org-babel-noweb-error-langs
)
2091 "<<" source-name
">> "
2092 "could not be resolved (see "
2093 "`org-babel-noweb-error-langs')"))
2095 "[\n\r]") (concat "\n" prefix
)))))
2096 (nb-add (buffer-substring index
(point-max)))))
2099 (defun org-babel-clean-text-properties (text)
2100 "Strip all properties from text return."
2102 (set-text-properties 0 (length text
) nil text
) text
))
2104 (defun org-babel-strip-protective-commas (body)
2105 "Strip protective commas from bodies of source blocks."
2107 (replace-regexp-in-string "^,#" "#" body
)))
2109 (defun org-babel-script-escape (str &optional force
)
2110 "Safely convert tables into elisp lists."
2111 (let (in-single in-double out
)
2112 ((lambda (escaped) (condition-case nil
(org-babel-read escaped
) (error escaped
)))
2116 (or (and (string-equal "[" (substring str
0 1))
2117 (string-equal "]" (substring str -
1)))
2118 (and (string-equal "{" (substring str
0 1))
2119 (string-equal "}" (substring str -
1)))
2120 (and (string-equal "(" (substring str
0 1))
2121 (string-equal ")" (substring str -
1))))))
2131 (91 (if (or in-double in-single
) ; [
2134 (93 (if (or in-double in-single
) ; ]
2137 (123 (if (or in-double in-single
) ; {
2140 (125 (if (or in-double in-single
) ; }
2143 (44 (if (or in-double in-single
) ; ,
2144 (cons 44 out
) (cons 32 out
)))
2145 (39 (if in-double
; '
2147 (setq in-single
(not in-single
)) (cons 34 out
)))
2148 (34 (if in-single
; "
2149 (append (list 34 32) out
)
2150 (setq in-double
(not in-double
)) (cons 34 out
)))
2151 (t (cons ch out
)))))
2152 (string-to-list str
))
2153 (apply #'string
(reverse out
)))))
2156 (defun org-babel-read (cell &optional inhibit-lisp-eval
)
2157 "Convert the string value of CELL to a number if appropriate.
2158 Otherwise if cell looks like lisp (meaning it starts with a
2159 \"(\", \"'\", \"`\" or a \"[\") then read it as lisp, otherwise
2160 return it unmodified as a string. Optional argument NO-LISP-EVAL
2161 inhibits lisp evaluation for situations in which is it not
2163 (if (and (stringp cell
) (not (equal cell
"")))
2164 (or (org-babel-number-p cell
)
2165 (if (and (not inhibit-lisp-eval
)
2166 (member (substring cell
0 1) '("(" "'" "`" "[")))
2168 (if (string= (substring cell
0 1) "\"")
2170 (progn (set-text-properties 0 (length cell
) nil cell
) cell
))))
2173 (defun org-babel-number-p (string)
2174 "If STRING represents a number return it's value."
2175 (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string
)
2176 (= (length (substring string
(match-beginning 0)
2179 (string-to-number string
)))
2181 (defun org-babel-import-elisp-from-file (file-name &optional separator
)
2182 "Read the results located at FILE-NAME into an elisp table.
2183 If the table is trivial, then return it as a scalar."
2185 (save-window-excursion
2189 (org-table-import file-name separator
)
2190 (delete-file file-name
)
2191 (setq result
(mapcar (lambda (row)
2192 (mapcar #'org-babel-string-read row
))
2193 (org-table-to-lisp))))
2195 (if (null (cdr result
)) ;; if result is trivial vector, then scalarize it
2196 (if (consp (car result
))
2197 (if (null (cdr (car result
)))
2203 (defun org-babel-string-read (cell)
2204 "Strip nested \"s from around strings."
2205 (org-babel-read (or (and (stringp cell
)
2206 (string-match "\\\"\\(.+\\)\\\"" cell
)
2207 (match-string 1 cell
))
2210 (defun org-babel-reverse-string (string)
2211 "Return the reverse of STRING."
2212 (apply 'string
(reverse (string-to-list string
))))
2214 (defun org-babel-chomp (string &optional regexp
)
2215 "Strip trailing spaces and carriage returns from STRING.
2216 Default regexp used is \"[ \f\t\n\r\v]\" but can be
2217 overwritten by specifying a regexp as a second argument."
2218 (let ((regexp (or regexp
"[ \f\t\n\r\v]")))
2219 (while (and (> (length string
) 0)
2220 (string-match regexp
(substring string -
1)))
2221 (setq string
(substring string
0 -
1)))
2224 (defun org-babel-trim (string &optional regexp
)
2225 "Strip leading and trailing spaces and carriage returns from STRING.
2226 Like `org-babel-chomp' only it runs on both the front and back
2228 (org-babel-chomp (org-babel-reverse-string
2229 (org-babel-chomp (org-babel-reverse-string string
) regexp
))
2232 (defvar org-babel-org-babel-call-process-region-original nil
)
2233 (defun org-babel-tramp-handle-call-process-region
2234 (start end program
&optional delete buffer display
&rest args
)
2235 "Use tramp to handle call-process-region.
2236 Fixes a bug in `tramp-handle-call-process-region'."
2237 (if (and (featurep 'tramp
) (file-remote-p default-directory
))
2238 (let ((tmpfile (tramp-compat-make-temp-file "")))
2239 (write-region start end tmpfile
)
2240 (when delete
(delete-region start end
))
2242 ;; (apply 'call-process program tmpfile buffer display args)
2244 (apply 'process-file program tmpfile buffer display args
)
2245 (delete-file tmpfile
)))
2246 ;; org-babel-call-process-region-original is the original emacs
2247 ;; definition. It is in scope from the let binding in
2248 ;; org-babel-execute-src-block
2249 (apply org-babel-call-process-region-original
2250 start end program delete buffer display args
)))
2252 (defun org-babel-local-file-name (file)
2253 "Return the local name component of FILE."
2254 (if (file-remote-p file
)
2256 (with-parsed-tramp-file-name file nil
2260 (defun org-babel-process-file-name (name &optional no-quote-p
)
2261 "Prepare NAME to be used in an external process.
2262 If NAME specifies a remote location, the remote portion of the
2263 name is removed, since in that case the process will be executing
2264 remotely. The file name is then processed by
2265 `expand-file-name'. Unless second argument NO-QUOTE-P is non-nil,
2266 the file name is additionally processed by
2267 `shell-quote-argument'"
2268 ((lambda (f) (if no-quote-p f
(shell-quote-argument f
)))
2269 (expand-file-name (org-babel-local-file-name name
))))
2271 (defvar org-babel-temporary-directory
)
2272 (unless (or noninteractive
(boundp 'org-babel-temporary-directory
))
2273 (defvar org-babel-temporary-directory
2274 (or (and (boundp 'org-babel-temporary-directory
)
2275 (file-exists-p org-babel-temporary-directory
)
2276 org-babel-temporary-directory
)
2277 (make-temp-file "babel-" t
))
2278 "Directory to hold temporary files created to execute code blocks.
2279 Used by `org-babel-temp-file'. This directory will be removed on
2282 (defun org-babel-temp-file (prefix &optional suffix
)
2283 "Create a temporary file in the `org-babel-temporary-directory'.
2284 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2285 value of `temporary-file-directory' temporarily set to the value
2286 of `org-babel-temporary-directory'."
2287 (if (file-remote-p default-directory
)
2289 (concat (file-remote-p default-directory
)
2291 prefix temporary-file-directory
)
2293 (let ((temporary-file-directory
2294 (or (and (boundp 'org-babel-temporary-directory
)
2295 (file-exists-p org-babel-temporary-directory
)
2296 org-babel-temporary-directory
)
2297 temporary-file-directory
)))
2298 (make-temp-file prefix nil suffix
))))
2300 (defun org-babel-remove-temporary-directory ()
2301 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2302 (when (and (boundp 'org-babel-temporary-directory
)
2303 (file-exists-p org-babel-temporary-directory
))
2304 ;; taken from `delete-directory' in files.el
2307 (mapc (lambda (file)
2308 ;; This test is equivalent to
2309 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2310 ;; but more efficient
2311 (if (eq t
(car (file-attributes file
)))
2312 (delete-directory file
)
2313 (delete-file file
)))
2314 ;; We do not want to delete "." and "..".
2315 (directory-files org-babel-temporary-directory
'full
2316 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2317 (delete-directory org-babel-temporary-directory
))
2319 (message "Failed to remove temporary Org-babel directory %s"
2320 (if (boundp 'org-babel-temporary-directory
)
2321 org-babel-temporary-directory
2322 "[directory not defined]"))))))
2324 (add-hook 'kill-emacs-hook
'org-babel-remove-temporary-directory
)