1 ;;; ob.el --- working with code blocks in org-mode
3 ;; Copyright (C) 2009-2012 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 org-reduce
"org" (CL-FUNC CL-SEQ
&rest CL-KEYS
))
36 (declare-function tramp-compat-make-temp-file
"tramp-compat"
37 (filename &optional dir-flag
))
38 (declare-function tramp-dissect-file-name
"tramp" (name &optional nodefault
))
39 (declare-function tramp-file-name-user
"tramp" (vec))
40 (declare-function tramp-file-name-host
"tramp" (vec))
41 (declare-function with-parsed-tramp-file-name
"tramp" (filename var
&rest body
))
42 (declare-function org-icompleting-read
"org" (&rest args
))
43 (declare-function org-edit-src-code
"org-src"
44 (&optional context code edit-buffer-name quietp
))
45 (declare-function org-edit-src-exit
"org-src" (&optional context
))
46 (declare-function org-open-at-point
"org" (&optional in-emacs reference-buffer
))
47 (declare-function org-save-outline-visibility
"org" (use-markers &rest body
))
48 (declare-function org-outline-overlay-data
"org" (&optional use-markers
))
49 (declare-function org-set-outline-overlay-data
"org" (data))
50 (declare-function org-narrow-to-subtree
"org" ())
51 (declare-function org-entry-get
"org"
52 (pom property
&optional inherit literal-nil
))
53 (declare-function org-make-options-regexp
"org" (kwds &optional extra
))
54 (declare-function org-do-remove-indentation
"org" (&optional n
))
55 (declare-function org-show-context
"org" (&optional key
))
56 (declare-function org-at-table-p
"org" (&optional table-type
))
57 (declare-function org-cycle
"org" (&optional arg
))
58 (declare-function org-uniquify
"org" (list))
59 (declare-function org-current-level
"org" ())
60 (declare-function org-table-import
"org-table" (file arg
))
61 (declare-function org-add-hook
"org-compat"
62 (hook function
&optional append local
))
63 (declare-function org-table-align
"org-table" ())
64 (declare-function org-table-end
"org-table" (&optional table-type
))
65 (declare-function orgtbl-to-generic
"org-table" (table params
))
66 (declare-function orgtbl-to-orgtbl
"org-table" (table params
))
67 (declare-function org-babel-tangle-comment-links
"ob-tangle" (&optional info
))
68 (declare-function org-babel-lob-get-info
"ob-lob" nil
)
69 (declare-function org-babel-ref-split-args
"ob-ref" (arg-string))
70 (declare-function org-babel-ref-parse
"ob-ref" (assignment))
71 (declare-function org-babel-ref-resolve
"ob-ref" (ref))
72 (declare-function org-babel-ref-goto-headline-id
"ob-ref" (id))
73 (declare-function org-babel-ref-headline-body
"ob-ref" ())
74 (declare-function org-babel-lob-execute-maybe
"ob-lob" ())
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 (defvar org-current-export-file
) ; dynamically bound
244 (defun org-babel-confirm-evaluate (info)
245 "Confirm evaluation of the code block INFO.
246 This behavior can be suppressed by setting the value of
247 `org-confirm-babel-evaluate' to nil, in which case all future
248 interactive code block evaluations will proceed without any
249 confirmation from the user.
251 Note disabling confirmation may result in accidental evaluation
252 of potentially harmful code."
253 (let* ((eval (or (cdr (assoc :eval
(nth 2 info
)))
254 (when (assoc :noeval
(nth 2 info
)) "no")))
255 (query (cond ((equal eval
"query") t
)
256 ((and org-current-export-file
257 (equal eval
"query-export")) t
)
258 ((functionp org-confirm-babel-evaluate
)
259 (funcall org-confirm-babel-evaluate
260 (nth 0 info
) (nth 1 info
)))
261 (t org-confirm-babel-evaluate
))))
262 (if (or (equal eval
"never") (equal eval
"no")
263 (and org-current-export-file
(or (equal eval
"no-export")
264 (equal eval
"never-export")))
267 (format "Evaluate this%scode block%son your system? "
268 (if info
(format " %s " (nth 0 info
)) " ")
270 (format " (%s) " (nth 4 info
)) " "))))))
271 (prog1 nil
(message "Evaluation %s"
272 (if (or (equal eval
"never") (equal eval
"no")
273 (equal eval
"no-export")
274 (equal eval
"never-export"))
275 "Disabled" "Aborted")))
279 (defun org-babel-execute-safely-maybe ()
280 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
281 (org-babel-execute-maybe)))
283 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-execute-safely-maybe
)
286 (defun org-babel-execute-maybe ()
288 (or (org-babel-execute-src-block-maybe)
289 (org-babel-lob-execute-maybe)))
291 (defun org-babel-execute-src-block-maybe ()
292 "Conditionally execute a source block.
293 Detect if this is context for a Babel src-block and if so
294 then run `org-babel-execute-src-block'."
296 (let ((info (org-babel-get-src-block-info)))
298 (progn (org-babel-eval-wipe-error-buffer)
299 (org-babel-execute-src-block current-prefix-arg info
) t
) nil
)))
302 (defun org-babel-view-src-block-info ()
303 "Display information on the current source block.
304 This includes header arguments, language and name, and is largely
305 a window into the `org-babel-get-src-block-info' function."
307 (let ((info (org-babel-get-src-block-info 'light
)))
308 (flet ((full (it) (> (length it
) 0))
309 (printf (fmt &rest args
) (princ (apply #'format fmt args
))))
311 (with-help-window (help-buffer)
312 (let ((name (nth 4 info
))
314 (switches (nth 3 info
))
315 (header-args (nth 2 info
)))
316 (when name
(printf "Name: %s\n" name
))
317 (when lang
(printf "Lang: %s\n" lang
))
318 (when (full switches
) (printf "Switches: %s\n" switches
))
319 (printf "Header Arguments:\n")
320 (dolist (pair (sort header-args
321 (lambda (a b
) (string< (symbol-name (car a
))
322 (symbol-name (car b
))))))
323 (when (full (cdr pair
))
324 (printf "\t%S%s\t%s\n"
326 (if (> (length (format "%S" (car pair
))) 7) "" "\t")
330 (defun org-babel-expand-src-block-maybe ()
331 "Conditionally expand a source block.
332 Detect if this is context for a org-babel src-block and if so
333 then run `org-babel-expand-src-block'."
335 (let ((info (org-babel-get-src-block-info)))
337 (progn (org-babel-expand-src-block current-prefix-arg info
) t
)
341 (defun org-babel-load-in-session-maybe ()
342 "Conditionally load a source block in a session.
343 Detect if this is context for a org-babel src-block and if so
344 then run `org-babel-load-in-session'."
346 (let ((info (org-babel-get-src-block-info)))
348 (progn (org-babel-load-in-session current-prefix-arg info
) t
)
351 (add-hook 'org-metaup-hook
'org-babel-load-in-session-maybe
)
354 (defun org-babel-pop-to-session-maybe ()
355 "Conditionally pop to a session.
356 Detect if this is context for a org-babel src-block and if so
357 then run `org-babel-pop-to-session'."
359 (let ((info (org-babel-get-src-block-info)))
360 (if info
(progn (org-babel-pop-to-session current-prefix-arg info
) t
) nil
)))
362 (add-hook 'org-metadown-hook
'org-babel-pop-to-session-maybe
)
364 (defconst org-babel-common-header-args-w-values
365 '((cache .
((no yes
)))
367 (colnames .
((nil no yes
)))
368 (comments .
((no link yes org both noweb
)))
370 (eval .
((never query
)))
371 (exports .
((code results both none
)))
373 (hlines .
((no yes
)))
374 (mkdirp .
((yes no
)))
377 (noweb .
((yes no tangle
)))
379 (padline .
((yes no
)))
380 (results .
((file list vector table scalar verbatim
)
381 (raw org html latex code pp wrap
)
382 (replace silent append prepend
)
384 (rownames .
((no yes
)))
388 (tangle .
((tangle yes no
:any
)))
392 (defconst org-babel-header-arg-names
393 (mapcar #'car org-babel-common-header-args-w-values
)
394 "Common header arguments used by org-babel.
395 Note that individual languages may define their own language
396 specific header arguments as well.")
398 (defvar org-babel-default-header-args
399 '((:session .
"none") (:results .
"replace") (:exports .
"code")
400 (:cache .
"no") (:noweb .
"no") (:hlines .
"no") (:tangle .
"no")
401 (:padnewline .
"yes"))
402 "Default arguments to use when evaluating a source block.")
404 (defvar org-babel-default-inline-header-args
405 '((:session .
"none") (:results .
"replace") (:exports .
"results"))
406 "Default arguments to use when evaluating an inline source block.")
408 (defvar org-babel-data-names
'("TBLNAME" "RESULTS" "NAME"))
410 (defvar org-babel-result-regexp
411 (concat "^[ \t]*#\\+"
412 (regexp-opt org-babel-data-names t
)
413 "\\(\\[\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*")
414 "Regular expression used to match result lines.
415 If the results are associated with a hash key then the hash will
416 be saved in the second match data.")
418 (defvar org-babel-result-w-name-regexp
419 (concat org-babel-result-regexp
420 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
422 (defvar org-babel-min-lines-for-block-output
10
423 "The minimum number of lines for block output.
424 If number of lines of output is equal to or exceeds this
425 value, the output is placed in a #+begin_example...#+end_example
426 block. Otherwise the output is marked as literal by inserting
427 colons at the starts of the lines. This variable only takes
428 effect if the :results output option is in effect.")
430 (defvar org-babel-noweb-error-langs nil
431 "Languages for which Babel will raise literate programming errors.
432 List of languages for which errors should be raised when the
433 source code block satisfying a noweb reference in this language
434 can not be resolved.")
436 (defvar org-babel-hash-show
4
437 "Number of initial characters to show of a hidden results hash.")
439 (defvar org-babel-after-execute-hook nil
440 "Hook for functions to be called after `org-babel-execute-src-block'")
442 (defun org-babel-named-src-block-regexp-for-name (name)
443 "This generates a regexp used to match a src block named NAME."
444 (concat org-babel-src-name-regexp
(regexp-quote name
)
445 "\\([ \t]\\|$\\|(\\)" ".*[\r\n]"
446 (substring org-babel-src-block-regexp
1)))
448 (defun org-babel-named-data-regexp-for-name (name)
449 "This generates a regexp used to match data named NAME."
450 (concat org-babel-result-regexp
(regexp-quote name
) "\\([ \t]\\|$\\)"))
453 (defvar call-process-region
)
456 (defun org-babel-execute-src-block (&optional arg info params
)
457 "Execute the current source code block.
458 Insert the results of execution into the buffer. Source code
459 execution and the collection and formatting of results can be
460 controlled through a variety of header arguments.
462 With prefix argument ARG, force re-execution even if an existing
463 result cached in the buffer would otherwise have been returned.
465 Optionally supply a value for INFO in the form returned by
466 `org-babel-get-src-block-info'.
468 Optionally supply a value for PARAMS which will be merged with
469 the header arguments specified at the front of the source code
472 (let ((info (or info
(org-babel-get-src-block-info))))
473 (when (org-babel-confirm-evaluate info
)
474 (let* ((lang (nth 0 info
))
476 (org-babel-process-params
477 (org-babel-merge-params (nth 2 info
) params
))
479 (cache?
(and (not arg
) (cdr (assoc :cache params
))
480 (string= "yes" (cdr (assoc :cache params
)))))
481 (result-params (cdr (assoc :result-params params
)))
482 (new-hash (when cache?
(org-babel-sha1-hash info
)))
483 (old-hash (when cache?
(org-babel-current-result-hash)))
484 (body (setf (nth 1 info
)
485 (let ((noweb (cdr (assoc :noweb params
))))
487 (or (string= "yes" noweb
)
488 (string= "tangle" noweb
)))
489 (org-babel-expand-noweb-references info
)
491 (dir (cdr (assoc :dir params
)))
493 (or (and dir
(file-name-as-directory dir
)) default-directory
))
494 (org-babel-call-process-region-original
495 (if (boundp 'org-babel-call-process-region-original
)
496 org-babel-call-process-region-original
497 (symbol-function 'call-process-region
)))
498 (indent (car (last info
)))
501 (flet ((call-process-region (&rest args
)
502 (apply 'org-babel-tramp-handle-call-process-region args
)))
503 (flet ((lang-check (f)
504 (let ((f (intern (concat "org-babel-execute:" f
))))
505 (when (fboundp f
) f
))))
507 (or (lang-check lang
)
508 (lang-check (symbol-name
509 (cdr (assoc lang org-src-lang-modes
))))
510 (error "No org-babel-execute function for %s!" lang
))))
511 (if (and (not arg
) new-hash
(equal new-hash old-hash
))
512 (save-excursion ;; return cached result
513 (goto-char (org-babel-where-is-src-block-result nil info
))
514 (end-of-line 1) (forward-char 1)
515 (setq result
(org-babel-read-result))
516 (message (replace-regexp-in-string
517 "%" "%%" (format "%S" result
))) result
)
518 (message "executing %s code block%s..."
520 (if (nth 4 info
) (format " (%s)" (nth 4 info
)) ""))
523 (if (and (eq (cdr (assoc :result-type params
)) 'value
)
524 (or (member "vector" result-params
)
525 (member "table" result-params
))
526 (not (listp result
)))
527 (list (list result
)) result
))
528 (funcall cmd body params
)))
529 ;; if non-empty result and :file then write to :file
530 (when (cdr (assoc :file params
))
532 (with-temp-file (cdr (assoc :file params
))
534 (org-babel-format-result
535 result
(cdr (assoc :sep
(nth 2 info
)))))))
536 (setq result
(cdr (assoc :file params
))))
537 (org-babel-insert-result
538 result result-params info new-hash indent lang
)
539 (run-hooks 'org-babel-after-execute-hook
)
541 (setq call-process-region
'org-babel-call-process-region-original
))))))
543 (defun org-babel-expand-body:generic
(body params
&optional var-lines
)
544 "Expand BODY with PARAMS.
545 Expand a block of code with org-babel according to its header
546 arguments. This generic implementation of body expansion is
547 called for languages which have not defined their own specific
548 org-babel-expand-body:lang function."
549 (mapconcat #'identity
(append var-lines
(list body
)) "\n"))
552 (defun org-babel-expand-src-block (&optional arg info params
)
553 "Expand the current source code block.
554 Expand according to the source code block's header
555 arguments and pop open the results in a preview buffer."
557 (let* ((info (or info
(org-babel-get-src-block-info)))
559 (params (setf (nth 2 info
)
560 (sort (org-babel-merge-params (nth 2 info
) params
)
561 (lambda (el1 el2
) (string< (symbol-name (car el1
))
562 (symbol-name (car el2
)))))))
563 (body (setf (nth 1 info
)
564 (if (and (cdr (assoc :noweb params
))
565 (string= "yes" (cdr (assoc :noweb params
))))
566 (org-babel-expand-noweb-references info
) (nth 1 info
))))
567 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
568 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
571 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
572 (org-babel-expand-body:generic
573 body params
(and (fboundp assignments-cmd
)
574 (funcall assignments-cmd params
))))))
576 nil expanded
(concat "*Org-Babel Preview " (buffer-name) "[ " lang
" ]*"))))
578 (defun org-babel-edit-distance (s1 s2
)
579 "Return the edit (levenshtein) distance between strings S1 S2."
580 (let* ((l1 (length s1
))
582 (dist (map 'vector
(lambda (_) (make-vector (1+ l2
) nil
))
583 (number-sequence 1 (1+ l1
)))))
584 (flet ((in (i j
) (aref (aref dist i
) j
))
585 (mmin (&rest lst
) (apply #'min
(remove nil lst
))))
586 (setf (aref (aref dist
0) 0) 0)
587 (dolist (i (number-sequence 1 l1
))
588 (dolist (j (number-sequence 1 l2
))
589 (setf (aref (aref dist i
) j
)
590 (+ (if (equal (aref s1
(1- i
)) (aref s2
(1- j
))) 0 1)
591 (mmin (in (1- i
) j
) (in i
(1- j
)) (in (1- i
) (1- j
)))))))
595 (defun org-babel-check-src-block ()
596 "Check for misspelled header arguments in the current code block."
598 ;; TODO: report malformed code block
599 ;; TODO: report incompatible combinations of header arguments
600 ;; TODO: report uninitialized variables
601 (let ((too-close 2)) ;; <- control closeness to report potential match
602 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg
)) 1))
603 (and (org-babel-where-is-src-block-head)
604 (org-babel-parse-header-arguments
605 (org-babel-clean-text-properties
606 (match-string 4))))))
607 (dolist (name (mapcar #'symbol-name org-babel-header-arg-names
))
608 (when (and (not (string= header name
))
609 (<= (org-babel-edit-distance header name
) too-close
))
610 (error "supplied header \"%S\" is suspiciously close to \"%S\""
612 (message "No suspicious header arguments found.")))
615 (defun org-babel-insert-header-arg ()
616 "Insert a header argument selecting from lists of common args and values."
618 (let* ((lang (car (org-babel-get-src-block-info 'light
)))
619 (lang-headers (intern (concat "org-babel-header-arg-names:" lang
)))
620 (headers (append (if (boundp lang-headers
)
621 (mapcar (lambda (h) (cons h
:any
))
624 org-babel-common-header-args-w-values
))
625 (arg (org-icompleting-read
628 (lambda (header-spec) (symbol-name (car header-spec
)))
631 (let ((vals (cdr (assoc (intern arg
) headers
))))
637 (read-from-minibuffer "value: "))
641 (let ((arg (org-icompleting-read
643 (cons "default" (mapcar #'symbol-name group
)))))
644 (if (and arg
(not (string= "default" arg
)))
650 (defun org-babel-load-in-session (&optional arg info
)
651 "Load the body of the current source-code block.
652 Evaluate the header arguments for the source block before
653 entering the session. After loading the body this pops open the
656 (let* ((info (or info
(org-babel-get-src-block-info)))
658 (params (nth 2 info
))
659 (body (setf (nth 1 info
)
660 (if (and (cdr (assoc :noweb params
))
661 (string= "yes" (cdr (assoc :noweb params
))))
662 (org-babel-expand-noweb-references info
)
664 (session (cdr (assoc :session params
)))
665 (dir (cdr (assoc :dir params
)))
667 (or (and dir
(file-name-as-directory dir
)) default-directory
))
668 (cmd (intern (concat "org-babel-load-session:" lang
))))
669 (unless (fboundp cmd
)
670 (error "No org-babel-load-session function for %s!" lang
))
671 (pop-to-buffer (funcall cmd session body params
))
675 (defun org-babel-initiate-session (&optional arg info
)
676 "Initiate session for current code block.
677 If called with a prefix argument then resolve any variable
678 references in the header arguments and assign these variables in
679 the session. Copy the body of the code block to the kill ring."
681 (let* ((info (or info
(org-babel-get-src-block-info (not arg
))))
684 (params (nth 2 info
))
685 (session (cdr (assoc :session params
)))
686 (dir (cdr (assoc :dir params
)))
688 (or (and dir
(file-name-as-directory dir
)) default-directory
))
689 (init-cmd (intern (format "org-babel-%s-initiate-session" lang
)))
690 (prep-cmd (intern (concat "org-babel-prep-session:" lang
))))
691 (if (and (stringp session
) (string= session
"none"))
692 (error "This block is not using a session!"))
693 (unless (fboundp init-cmd
)
694 (error "No org-babel-initiate-session function for %s!" lang
))
695 (with-temp-buffer (insert (org-babel-trim body
))
696 (copy-region-as-kill (point-min) (point-max)))
698 (unless (fboundp prep-cmd
)
699 (error "No org-babel-prep-session function for %s!" lang
))
700 (funcall prep-cmd session params
))
701 (funcall init-cmd session params
)))
704 (defun org-babel-switch-to-session (&optional arg info
)
705 "Switch to the session of the current code block.
706 Uses `org-babel-initiate-session' to start the session. If called
707 with a prefix argument then this is passed on to
708 `org-babel-initiate-session'."
710 (pop-to-buffer (org-babel-initiate-session arg info
))
713 (defalias 'org-babel-pop-to-session
'org-babel-switch-to-session
)
716 (defun org-babel-switch-to-session-with-code (&optional arg info
)
717 "Switch to code buffer and display session."
721 (let ((other-window-buffer (window-buffer (next-window))))
722 (set-window-buffer (next-window) (current-buffer))
723 (set-window-buffer (selected-window) other-window-buffer
))
725 (let ((info (org-babel-get-src-block-info))
726 (org-src-window-setup 'reorganize-frame
))
728 (org-babel-switch-to-session arg info
))
732 (defmacro org-babel-do-in-edit-buffer
(&rest body
)
733 "Evaluate BODY in edit buffer if there is a code block at point.
734 Return t if a code block was found at point, nil otherwise."
735 `(let ((org-src-window-setup 'switch-invisibly
))
736 (when (and (org-babel-where-is-src-block-head)
737 (org-edit-src-code nil nil nil
))
738 (unwind-protect (progn ,@body
)
739 (if (org-bound-and-true-p org-edit-src-from-org-mode
)
740 (org-edit-src-exit)))
742 (def-edebug-spec org-babel-do-in-edit-buffer
(body))
744 (defun org-babel-do-key-sequence-in-edit-buffer (key)
745 "Read key sequence and execute the command in edit buffer.
746 Enter a key sequence to be executed in the language major-mode
747 edit buffer. For example, TAB will alter the contents of the
748 Org-mode code block according to the effect of TAB in the
749 language major-mode buffer. For languages that support
750 interactive sessions, this can be used to send code from the Org
751 buffer to the session for evaluation using the native major-mode
752 evaluation mechanisms."
753 (interactive "kEnter key-sequence to execute in edit buffer: ")
754 (org-babel-do-in-edit-buffer
756 (key-binding (or key
(read-key-sequence nil
))))))
758 (defvar org-bracket-link-regexp
)
760 (defun org-babel-open-src-block-result (&optional re-run
)
761 "If `point' is on a src block then open the results of the
762 source code block, otherwise return nil. With optional prefix
763 argument RE-RUN the source-code block is evaluated even if
764 results already exist."
766 (let ((info (org-babel-get-src-block-info)))
769 ;; go to the results, if there aren't any then run the block
770 (goto-char (or (and (not re-run
) (org-babel-where-is-src-block-result))
771 (progn (org-babel-execute-src-block)
772 (org-babel-where-is-src-block-result))))
774 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
776 (if (looking-at org-bracket-link-regexp
)
779 (let ((r (org-babel-format-result
780 (org-babel-read-result) (cdr (assoc :sep
(nth 2 info
))))))
781 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
782 (delete-region (point-min) (point-max))
787 (defmacro org-babel-map-src-blocks
(file &rest body
)
788 "Evaluate BODY forms on each source-block in FILE.
789 If FILE is nil evaluate BODY forms on source blocks in current
790 buffer. During evaluation of BODY the following local variables
791 are set relative to the currently matched code block.
793 full-block ------- string holding the entirety of the code block
794 beg-block -------- point at the beginning of the code block
795 end-block -------- point at the end of the matched code block
796 lang ------------- string holding the language of the code block
797 beg-lang --------- point at the beginning of the lang
798 end-lang --------- point at the end of the lang
799 switches --------- string holding the switches
800 beg-switches ----- point at the beginning of the switches
801 end-switches ----- point at the end of the switches
802 header-args ------ string holding the header-args
803 beg-header-args -- point at the beginning of the header-args
804 end-header-args -- point at the end of the header-args
805 body ------------- string holding the body of the code block
806 beg-body --------- point at the beginning of the body
807 end-body --------- point at the end of the body"
809 (let ((tempvar (make-symbol "file")))
810 `(let* ((,tempvar
,file
)
811 (visited-p (or (null ,tempvar
)
812 (get-file-buffer (expand-file-name ,tempvar
))))
813 (point (point)) to-be-removed
)
814 (save-window-excursion
815 (when ,tempvar
(find-file ,tempvar
))
816 (setq to-be-removed
(current-buffer))
817 (goto-char (point-min))
818 (while (re-search-forward org-babel-src-block-regexp nil t
)
819 (goto-char (match-beginning 0))
820 (let ((full-block (match-string 0))
821 (beg-block (match-beginning 0))
822 (end-block (match-end 0))
823 (lang (match-string 2))
824 (beg-lang (match-beginning 2))
825 (end-lang (match-end 2))
826 (switches (match-string 3))
827 (beg-switches (match-beginning 3))
828 (end-switches (match-end 3))
829 (header-args (match-string 4))
830 (beg-header-args (match-beginning 4))
831 (end-header-args (match-end 4))
832 (body (match-string 5))
833 (beg-body (match-beginning 5))
834 (end-body (match-end 5)))
836 (goto-char end-block
))))
837 (unless visited-p
(kill-buffer to-be-removed
))
839 (def-edebug-spec org-babel-map-src-blocks
(form body
))
842 (defmacro org-babel-map-inline-src-blocks
(file &rest body
)
843 "Evaluate BODY forms on each inline source-block in FILE.
844 If FILE is nil evaluate BODY forms on source blocks in current
847 (let ((tempvar (make-symbol "file")))
848 `(let* ((,tempvar
,file
)
849 (visited-p (or (null ,tempvar
)
850 (get-file-buffer (expand-file-name ,tempvar
))))
851 (point (point)) to-be-removed
)
852 (save-window-excursion
853 (when ,tempvar
(find-file ,tempvar
))
854 (setq to-be-removed
(current-buffer))
855 (goto-char (point-min))
856 (while (re-search-forward org-babel-inline-src-block-regexp nil t
)
857 (goto-char (match-beginning 1))
858 (save-match-data ,@body
)
859 (goto-char (match-end 0))))
860 (unless visited-p
(kill-buffer to-be-removed
))
862 (def-edebug-spec org-babel-map-inline-src-blocks
(form body
))
864 (defvar org-babel-lob-one-liner-regexp
)
866 (defmacro org-babel-map-call-lines
(file &rest body
)
867 "Evaluate BODY forms on each call line in FILE.
868 If FILE is nil evaluate BODY forms on source blocks in current
871 (let ((tempvar (make-symbol "file")))
872 `(let* ((,tempvar
,file
)
873 (visited-p (or (null ,tempvar
)
874 (get-file-buffer (expand-file-name ,tempvar
))))
875 (point (point)) to-be-removed
)
876 (save-window-excursion
877 (when ,tempvar
(find-file ,tempvar
))
878 (setq to-be-removed
(current-buffer))
879 (goto-char (point-min))
880 (while (re-search-forward org-babel-lob-one-liner-regexp nil t
)
881 (goto-char (match-beginning 1))
882 (save-match-data ,@body
)
883 (goto-char (match-end 0))))
884 (unless visited-p
(kill-buffer to-be-removed
))
886 (def-edebug-spec org-babel-map-call-lines
(form body
))
889 (defun org-babel-execute-buffer (&optional arg
)
890 "Execute source code blocks in a buffer.
891 Call `org-babel-execute-src-block' on every source block in
894 (org-babel-eval-wipe-error-buffer)
895 (org-save-outline-visibility t
896 (org-babel-map-src-blocks nil
897 (org-babel-execute-src-block arg
))
898 (org-babel-map-inline-src-blocks nil
899 (org-babel-execute-src-block arg
))
900 (org-babel-map-call-lines nil
901 (org-babel-lob-execute-maybe))))
904 (defun org-babel-execute-subtree (&optional arg
)
905 "Execute source code blocks in a subtree.
906 Call `org-babel-execute-src-block' on every source block in
907 the current subtree."
911 (org-narrow-to-subtree)
912 (org-babel-execute-buffer arg
)
916 (defun org-babel-sha1-hash (&optional info
)
917 "Generate an sha1 hash based on the value of info."
919 (let ((print-level nil
)
920 (info (or info
(org-babel-get-src-block-info))))
922 (sort (copy-sequence (nth 2 info
))
923 (lambda (a b
) (string< (car a
) (car b
)))))
925 (dolist (p '("replace" "silent" "append" "prepend"))
926 (setq lst
(remove p lst
)))
929 (let ((v (if (and (listp (cdr arg
)) (null (cddr arg
)))
930 (copy-sequence (cdr arg
))
932 (when (and v
(not (and (sequencep v
)
936 ((and (listp v
) ; lists are sorted
937 (member (car arg
) '(:result-params
)))
938 (sort (rm v
) #'string
<))
939 ((and (stringp v
) ; strings are sorted
940 (member (car arg
) '(:results
:exports
)))
941 (mapconcat #'identity
(sort (rm (split-string v
))
945 (when (org-called-interactively-p 'interactive
) (message hash
)) hash
)
946 (let ((it (format "%s-%s"
949 (delq nil
(mapcar (lambda (arg)
950 (let ((normalized (norm arg
)))
952 (format "%S" normalized
))))
957 (defun org-babel-current-result-hash ()
958 "Return the in-buffer hash associated with INFO."
959 (org-babel-where-is-src-block-result)
960 (org-babel-clean-text-properties (match-string 3)))
962 (defun org-babel-hide-hash ()
963 "Hide the hash in the current results line.
964 Only the initial `org-babel-hash-show' characters of the hash
965 will remain visible."
966 (add-to-invisibility-spec '(org-babel-hide-hash . t
))
968 (when (and (re-search-forward org-babel-result-regexp nil t
)
970 (let* ((start (match-beginning 3))
971 (hide-start (+ org-babel-hash-show start
))
973 (hash (match-string 3))
975 (setq ov1
(make-overlay start hide-start
))
976 (setq ov2
(make-overlay hide-start end
))
977 (overlay-put ov2
'invisible
'org-babel-hide-hash
)
978 (overlay-put ov1
'babel-hash hash
)))))
980 (defun org-babel-hide-all-hashes ()
981 "Hide the hash in the current buffer.
982 Only the initial `org-babel-hash-show' characters of each hash
983 will remain visible. This function should be called as part of
984 the `org-mode-hook'."
986 (while (re-search-forward org-babel-result-regexp nil t
)
987 (goto-char (match-beginning 0))
988 (org-babel-hide-hash)
989 (goto-char (match-end 0)))))
990 (add-hook 'org-mode-hook
'org-babel-hide-all-hashes
)
992 (defun org-babel-hash-at-point (&optional point
)
993 "Return the value of the hash at POINT.
994 The hash is also added as the last element of the kill ring.
995 This can be called with C-c C-c."
997 (let ((hash (car (delq nil
(mapcar
998 (lambda (ol) (overlay-get ol
'babel-hash
))
999 (overlays-at (or point
(point))))))))
1000 (when hash
(kill-new hash
) (message hash
))))
1001 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-hash-at-point
)
1003 (defvar org-file-properties
)
1004 (defun org-babel-params-from-properties (&optional lang
)
1005 "Retrieve parameters specified as properties.
1006 Return an association list of any source block params which
1007 may be specified in the properties of the current outline entry."
1010 (org-babel-parse-multiple-vars
1013 (lambda (header-arg)
1014 (and (setq val
(org-entry-get (point) header-arg t
))
1015 (cons (intern (concat ":" header-arg
))
1016 (org-babel-read val
))))
1020 org-babel-header-arg-names
1022 (setq sym
(intern (concat "org-babel-header-arg-names:"
1024 (and (boundp sym
) (eval sym
)))))))))))
1026 (defvar org-src-preserve-indentation
)
1027 (defun org-babel-parse-src-block-match ()
1028 "Parse the results from a match of the `org-babel-src-block-regexp'."
1029 (let* ((block-indentation (length (match-string 1)))
1030 (lang (org-babel-clean-text-properties (match-string 2)))
1031 (lang-headers (intern (concat "org-babel-default-header-args:" lang
)))
1032 (switches (match-string 3))
1033 (body (org-babel-clean-text-properties
1034 (let* ((body (match-string 5))
1035 (sub-length (- (length body
) 1)))
1036 (if (and (> sub-length
0)
1037 (string= "\n" (substring body sub-length
)))
1038 (substring body
0 sub-length
)
1040 (preserve-indentation (or org-src-preserve-indentation
1041 (string-match "-i\\>" switches
))))
1043 ;; get block body less properties, protective commas, and indentation
1046 (insert (org-babel-strip-protective-commas body
))
1047 (unless preserve-indentation
(org-do-remove-indentation))
1049 (org-babel-merge-params
1050 org-babel-default-header-args
1051 (org-babel-params-from-properties lang
)
1052 (if (boundp lang-headers
) (eval lang-headers
) nil
)
1053 (org-babel-parse-header-arguments
1054 (org-babel-clean-text-properties (or (match-string 4) ""))))
1056 block-indentation
)))
1058 (defun org-babel-parse-inline-src-block-match ()
1059 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
1060 (let* ((lang (org-babel-clean-text-properties (match-string 2)))
1061 (lang-headers (intern (concat "org-babel-default-header-args:" lang
))))
1063 (org-babel-strip-protective-commas
1064 (org-babel-clean-text-properties (match-string 5)))
1065 (org-babel-merge-params
1066 org-babel-default-inline-header-args
1067 (org-babel-params-from-properties lang
)
1068 (if (boundp lang-headers
) (eval lang-headers
) nil
)
1069 (org-babel-parse-header-arguments
1070 (org-babel-clean-text-properties (or (match-string 4) "")))))))
1072 (defun org-babel-balanced-split (string alts
)
1073 "Split STRING on instances of ALTS.
1074 ALTS is a cons of two character options where each option may be
1075 either the numeric code of a single character or a list of
1076 character alternatives. For example to split on balanced
1077 instances of \"[ \t]:\" set ALTS to '((32 9) . 58)."
1078 (flet ((matches (ch spec
) (if (listp spec
) (member ch spec
) (equal spec ch
)))
1081 (and (matches ch
(cdr alts
))
1082 (matches last
(car alts
)))
1083 (matches ch alts
))))
1084 (let ((balance 0) (quote nil
) (partial nil
) (lst nil
) (last 0))
1085 (mapc (lambda (ch) ; split on [], (), "" balanced instances of [ \t]:
1086 (setq balance
(+ balance
1087 (cond ((or (equal 91 ch
) (equal 40 ch
)) 1)
1088 ((or (equal 93 ch
) (equal 41 ch
)) -
1)
1090 (when (and (equal 34 ch
) (not (equal 92 last
)))
1091 (setq quote
(not quote
)))
1092 (setq partial
(cons ch partial
))
1093 (when (and (= balance
0) (not quote
) (matched ch last
))
1094 (setq lst
(cons (apply #'string
(nreverse
1101 (string-to-list string
))
1102 (nreverse (cons (apply #'string
(nreverse partial
)) lst
)))))
1104 (defun org-babel-join-splits-near-ch (ch list
)
1105 "Join splits where \"=\" is on either end of the split."
1106 (flet ((last= (str) (= ch
(aref str
(1- (length str
)))))
1107 (first= (str) (= ch
(aref str
0))))
1109 (org-reduce (lambda (acc el
)
1110 (let ((head (car acc
)))
1111 (if (and head
(or (last= head
) (first= el
)))
1112 (cons (concat head el
) (cdr acc
))
1114 list
:initial-value nil
))))
1116 (defun org-babel-parse-header-arguments (arg-string)
1117 "Parse a string of header arguments returning an alist."
1118 (when (> (length arg-string
) 0)
1119 (org-babel-parse-multiple-vars
1124 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1126 (cons (intern (match-string 1 arg
))
1127 (org-babel-read (org-babel-chomp (match-string 2 arg
))))
1128 (cons (intern (org-babel-chomp arg
)) nil
)))
1130 (cons (car raw
) (mapcar (lambda (r) (concat ":" r
)) (cdr raw
))))
1131 (org-babel-balanced-split arg-string
'((32 9) .
58))))))))
1133 (defun org-babel-parse-multiple-vars (header-arguments)
1134 "Expand multiple variable assignments behind a single :var keyword.
1136 This allows expression of multiple variables with one :var as
1139 #+PROPERTY: var foo=1, bar=2"
1141 (mapc (lambda (pair)
1142 (if (eq (car pair
) :var
)
1143 (mapcar (lambda (v) (push (cons :var
(org-babel-trim v
)) results
))
1144 (org-babel-join-splits-near-ch
1145 61 (org-babel-balanced-split (cdr pair
) 32)))
1146 (push pair results
)))
1148 (nreverse results
)))
1150 (defun org-babel-process-params (params)
1151 "Expand variables in PARAMS and add summary parameters."
1152 (let* ((processed-vars (mapcar (lambda (el)
1153 (if (consp (cdr el
))
1155 (org-babel-ref-parse (cdr el
))))
1156 (org-babel-get-header params
:var
)))
1157 (vars-and-names (if (and (assoc :colname-names params
)
1158 (assoc :rowname-names params
))
1159 (list processed-vars
)
1160 (org-babel-disassemble-tables
1162 (cdr (assoc :hlines params
))
1163 (cdr (assoc :colnames params
))
1164 (cdr (assoc :rownames params
)))))
1165 (raw-result (or (cdr (assoc :results params
)) ""))
1166 (result-params (append
1167 (split-string (if (stringp raw-result
)
1170 (cdr (assoc :result-params params
)))))
1172 (mapcar (lambda (var) (cons :var var
)) (car vars-and-names
))
1174 (cons :colname-names
(or (cdr (assoc :colname-names params
))
1175 (cadr vars-and-names
)))
1176 (cons :rowname-names
(or (cdr (assoc :rowname-names params
))
1177 (caddr vars-and-names
)))
1178 (cons :result-params result-params
)
1179 (cons :result-type
(cond ((member "output" result-params
) 'output
)
1180 ((member "value" result-params
) 'value
)
1182 (org-babel-get-header params
:var
'other
))))
1184 ;; row and column names
1185 (defun org-babel-del-hlines (table)
1186 "Remove all 'hlines from TABLE."
1187 (remove 'hline table
))
1189 (defun org-babel-get-colnames (table)
1190 "Return the column names of TABLE.
1191 Return a cons cell, the `car' of which contains the TABLE less
1192 colnames, and the `cdr' of which contains a list of the column
1194 (if (equal 'hline
(nth 1 table
))
1195 (cons (cddr table
) (car table
))
1196 (cons (cdr table
) (car table
))))
1198 (defun org-babel-get-rownames (table)
1199 "Return the row names of TABLE.
1200 Return a cons cell, the `car' of which contains the TABLE less
1201 colnames, and the `cdr' of which contains a list of the column
1202 names. Note: this function removes any hlines in TABLE."
1203 (flet ((trans (table) (apply #'mapcar
* #'list table
)))
1204 (let* ((width (apply 'max
1205 (mapcar (lambda (el) (if (listp el
) (length el
) 0)) table
)))
1206 (table (trans (mapcar (lambda (row)
1207 (if (not (equal row
'hline
))
1211 (setq row
(cons 'hline row
)))
1214 (cons (mapcar (lambda (row) (if (equal (car row
) 'hline
) 'hline row
))
1215 (trans (cdr table
)))
1216 (remove 'hline
(car table
))))))
1218 (defun org-babel-put-colnames (table colnames
)
1219 "Add COLNAMES to TABLE if they exist."
1220 (if colnames
(apply 'list colnames
'hline table
) table
))
1222 (defun org-babel-put-rownames (table rownames
)
1223 "Add ROWNAMES to TABLE if they exist."
1225 (mapcar (lambda (row)
1227 (cons (or (pop rownames
) "") row
)
1231 (defun org-babel-pick-name (names selector
)
1232 "Select one out of an alist of row or column names.
1233 SELECTOR can be either a list of names in which case those names
1234 will be returned directly, or an index into the list NAMES in
1235 which case the indexed names will be return."
1236 (if (listp selector
)
1239 (if (and selector
(symbolp selector
) (not (equal t selector
)))
1240 (cdr (assoc selector names
))
1241 (if (integerp selector
)
1242 (nth (- selector
1) names
)
1243 (cdr (car (last names
))))))))
1245 (defun org-babel-disassemble-tables (vars hlines colnames rownames
)
1246 "Parse tables for further processing.
1247 Process the variables in VARS according to the HLINES,
1248 ROWNAMES and COLNAMES header arguments. Return a list consisting
1249 of the vars, cnames and rnames."
1250 (let (cnames rnames
)
1254 (when (listp (cdr var
))
1255 (when (and (not (equal colnames
"no"))
1256 (or colnames
(and (equal (nth 1 (cdr var
)) 'hline
)
1257 (not (member 'hline
(cddr (cdr var
)))))))
1258 (let ((both (org-babel-get-colnames (cdr var
))))
1259 (setq cnames
(cons (cons (car var
) (cdr both
))
1261 (setq var
(cons (car var
) (car both
)))))
1262 (when (and rownames
(not (equal rownames
"no")))
1263 (let ((both (org-babel-get-rownames (cdr var
))))
1264 (setq rnames
(cons (cons (car var
) (cdr both
))
1266 (setq var
(cons (car var
) (car both
)))))
1267 (when (and hlines
(not (equal hlines
"yes")))
1268 (setq var
(cons (car var
) (org-babel-del-hlines (cdr var
))))))
1271 (reverse cnames
) (reverse rnames
))))
1273 (defun org-babel-reassemble-table (table colnames rownames
)
1274 "Add column and row names to a table.
1275 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1276 to the table for reinsertion to org-mode."
1279 (if (and colnames
(listp (car table
)) (= (length (car table
))
1281 (org-babel-put-colnames table colnames
) table
))
1282 (if (and rownames
(= (length table
) (length rownames
)))
1283 (org-babel-put-rownames table rownames
) table
))
1286 (defun org-babel-where-is-src-block-head ()
1287 "Find where the current source block begins.
1288 Return the point at the beginning of the current source
1289 block. Specifically at the beginning of the #+BEGIN_SRC line.
1290 If the point is not on a source block then return nil."
1291 (let ((initial (point)) top bottom
)
1293 (save-excursion ;; on a source name line or a #+header line
1294 (beginning-of-line 1)
1295 (and (or (looking-at org-babel-src-name-regexp
)
1296 (looking-at org-babel-multi-line-header-regexp
))
1298 (while (and (forward-line 1)
1299 (looking-at org-babel-multi-line-header-regexp
)))
1300 (looking-at org-babel-src-block-regexp
))
1302 (save-excursion ;; on a #+begin_src line
1303 (beginning-of-line 1)
1304 (and (looking-at org-babel-src-block-regexp
)
1306 (save-excursion ;; inside a src block
1308 (re-search-backward "^[ \t]*#\\+begin_src" nil t
) (setq top
(point))
1309 (re-search-forward "^[ \t]*#\\+end_src" nil t
) (setq bottom
(point))
1310 (< top initial
) (< initial bottom
)
1311 (progn (goto-char top
) (beginning-of-line 1)
1312 (looking-at org-babel-src-block-regexp
))
1316 (defun org-babel-goto-src-block-head ()
1317 "Go to the beginning of the current code block."
1320 (if head
(goto-char head
) (error "not currently in a code block")))
1321 (org-babel-where-is-src-block-head)))
1324 (defun org-babel-goto-named-src-block (name)
1325 "Go to a named source-code block."
1327 (let ((completion-ignore-case t
))
1328 (list (org-icompleting-read "source-block name: "
1329 (org-babel-src-block-names) nil t
))))
1330 (let ((point (org-babel-find-named-block name
)))
1332 ;; taken from `org-open-at-point'
1333 (progn (goto-char point
) (org-show-context))
1334 (message "source-code block '%s' not found in this buffer" name
))))
1336 (defun org-babel-find-named-block (name)
1337 "Find a named source-code block.
1338 Return the location of the source block identified by source
1339 NAME, or nil if no such block exists. Set match data according to
1340 org-babel-named-src-block-regexp."
1342 (let ((case-fold-search t
)
1343 (regexp (org-babel-named-src-block-regexp-for-name name
)) msg
)
1344 (goto-char (point-min))
1345 (when (or (re-search-forward regexp nil t
)
1346 (re-search-backward regexp nil t
))
1347 (match-beginning 0)))))
1349 (defun org-babel-src-block-names (&optional file
)
1350 "Returns the names of source blocks in FILE or the current buffer."
1352 (when file
(find-file file
)) (goto-char (point-min))
1354 (while (re-search-forward org-babel-src-name-w-name-regexp nil t
)
1355 (setq names
(cons (match-string 3) names
)))
1359 (defun org-babel-goto-named-result (name)
1360 "Go to a named result."
1362 (let ((completion-ignore-case t
))
1363 (list (org-icompleting-read "source-block name: "
1364 (org-babel-result-names) nil t
))))
1365 (let ((point (org-babel-find-named-result name
)))
1367 ;; taken from `org-open-at-point'
1368 (progn (goto-char point
) (org-show-context))
1369 (message "result '%s' not found in this buffer" name
))))
1371 (defun org-babel-find-named-result (name &optional point
)
1372 "Find a named result.
1373 Return the location of the result named NAME in the current
1374 buffer or nil if no such result exists."
1376 (goto-char (or point
(point-min)))
1377 (catch 'is-a-code-block
1378 (when (re-search-forward
1379 (concat org-babel-result-regexp
1380 "[ \t]" (regexp-quote name
) "[ \t\n\f\v\r]") nil t
)
1381 (when (and (string= "name" (downcase (match-string 1)))
1382 (or (looking-at org-babel-src-block-regexp
)
1383 (looking-at org-babel-multi-line-header-regexp
)))
1384 (throw 'is-a-code-block
(org-babel-find-named-result name
(point))))
1385 (beginning-of-line 0) (point)))))
1387 (defun org-babel-result-names (&optional file
)
1388 "Returns the names of results in FILE or the current buffer."
1390 (when file
(find-file file
)) (goto-char (point-min))
1392 (while (re-search-forward org-babel-result-w-name-regexp nil t
)
1393 (setq names
(cons (match-string 4) names
)))
1397 (defun org-babel-next-src-block (&optional arg
)
1398 "Jump to the next source block.
1399 With optional prefix argument ARG, jump forward ARG many source blocks."
1401 (when (looking-at org-babel-src-block-regexp
) (forward-char 1))
1403 (re-search-forward org-babel-src-block-regexp nil nil
(or arg
1))
1404 (error (error "No further code blocks")))
1405 (goto-char (match-beginning 0)) (org-show-context))
1408 (defun org-babel-previous-src-block (&optional arg
)
1409 "Jump to the previous source block.
1410 With optional prefix argument ARG, jump backward ARG many source blocks."
1413 (re-search-backward org-babel-src-block-regexp nil nil
(or arg
1))
1414 (error (error "No previous code blocks")))
1415 (goto-char (match-beginning 0)) (org-show-context))
1417 (defvar org-babel-load-languages
)
1420 (defun org-babel-mark-block ()
1421 "Mark current src block"
1427 (looking-at org-babel-src-block-regexp
))
1428 (push-mark (match-end 5) nil t
)
1429 (goto-char (match-beginning 5))))
1430 (org-babel-where-is-src-block-head)))
1432 (defun org-babel-demarcate-block (&optional arg
)
1433 "Wrap or split the code in the region or on the point.
1434 When called from inside of a code block the current block is
1435 split. When called from outside of a code block a new code block
1436 is created. In both cases if the region is demarcated and if the
1437 region is not active then the point is demarcated."
1439 (let ((info (org-babel-get-src-block-info 'light
))
1440 (headers (progn (org-babel-where-is-src-block-head)
1442 (stars (concat (make-string (or (org-current-level) 1) ?
*) " ")))
1448 (let ((lang (nth 0 info
))
1449 (indent (make-string (nth 5 info
) ?
)))
1450 (when (string-match "^[[:space:]]*$"
1451 (buffer-substring (point-at-bol)
1453 (delete-region (point-at-bol) (point-at-eol)))
1455 (if (looking-at "^") "" "\n")
1456 indent
"#+end_src\n"
1457 (if arg stars indent
) "\n"
1458 indent
"#+begin_src " lang
1459 (if (> (length headers
) 1)
1460 (concat " " headers
) headers
)
1461 (if (looking-at "[\n\r]")
1463 (concat "\n" (make-string (current-column) ?
)))))))
1464 (move-end-of-line 2))
1465 (sort (if (region-active-p) (list (mark) (point)) (list (point))) #'>))
1466 (let ((start (point))
1467 (lang (org-icompleting-read "Lang: "
1468 (mapcar (lambda (el) (symbol-name (car el
)))
1469 org-babel-load-languages
)))
1470 (body (delete-and-extract-region
1471 (if (region-active-p) (mark) (point)) (point))))
1472 (insert (concat (if (looking-at "^") "" "\n")
1473 (if arg
(concat stars
"\n") "")
1474 "#+begin_src " lang
"\n"
1476 (if (or (= (length body
) 0)
1477 (string-match "[\r\n]$" body
)) "" "\n")
1479 (goto-char start
) (move-end-of-line 1)))))
1481 (defvar org-babel-lob-one-liner-regexp
)
1482 (defun org-babel-where-is-src-block-result (&optional insert info hash indent
)
1483 "Find where the current source block results begin.
1484 Return the point at the beginning of the result of the current
1485 source block. Specifically at the beginning of the results line.
1486 If no result exists for this block then create a results line
1487 following the source block."
1489 (let* ((on-lob-line (save-excursion
1490 (beginning-of-line 1)
1491 (looking-at org-babel-lob-one-liner-regexp
)))
1492 (inlinep (when (org-babel-get-inline-src-block-matches)
1494 (name (if on-lob-line
1495 (nth 0 (org-babel-lob-get-info))
1496 (nth 4 (or info
(org-babel-get-src-block-info 'light
)))))
1497 (head (unless on-lob-line
(org-babel-where-is-src-block-head)))
1499 (when head
(goto-char head
))
1501 found
;; was there a result (before we potentially insert one)
1506 ;; - return t if it is found, else return nil
1507 ;; - if it does not need to be rebuilt, then don't set end
1508 ;; - if it does need to be rebuilt then do set end
1509 name
(setq beg
(org-babel-find-named-result name
))
1511 (when (and hash
(not (string= hash
(match-string 3))))
1512 (goto-char beg
) (setq end beg
) ;; beginning of result
1514 (delete-region end
(org-babel-result-end)) nil
)))
1517 ;; - return t if it is found, else return nil
1518 ;; - if it is found, and the hash doesn't match, delete and set end
1519 (or on-lob-line
(re-search-forward "^[ \t]*#\\+end_src" nil t
))
1520 (progn (end-of-line 1)
1521 (if (eobp) (insert "\n") (forward-char 1))
1524 (progn ;; unnamed results line already exists
1525 (re-search-forward "[^ \f\t\n\r\v]" nil t
)
1526 (beginning-of-line 1)
1528 (concat org-babel-result-regexp
"\n")))
1530 ;; must remove and rebuild if hash!=old-hash
1531 (if (and hash
(not (string= hash
(match-string 3))))
1535 end
(org-babel-result-end)))
1536 (setq end nil
)))))))))
1537 (if (and insert end
)
1541 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1546 (org-number-sequence 1 indent
) "")
1549 (when hash
(concat "["hash
"]"))
1551 (when name
(concat " " name
)) "\n"))
1552 (unless beg
(insert "\n") (backward-char))
1553 (beginning-of-line 0)
1554 (if hash
(org-babel-hide-hash))
1558 (defvar org-block-regexp
)
1559 (defun org-babel-read-result ()
1560 "Read the result at `point' into emacs-lisp."
1561 (let ((case-fold-search t
) result-string
)
1563 ((org-at-table-p) (org-babel-read-table))
1564 ((org-at-item-p) (org-babel-read-list))
1565 ((looking-at org-bracket-link-regexp
) (org-babel-read-link))
1566 ((looking-at org-block-regexp
) (org-babel-trim (match-string 4)))
1567 ((looking-at "^[ \t]*: ")
1570 (mapconcat (lambda (line)
1571 (if (and (> (length line
) 1)
1572 (string-match "^[ \t]*: \\(.+\\)" line
))
1573 (match-string 1 line
)
1577 (point) (org-babel-result-end)) "[\r\n]+")
1579 (or (org-babel-number-p result-string
) result-string
))
1580 ((looking-at org-babel-result-regexp
)
1581 (save-excursion (forward-line 1) (org-babel-read-result))))))
1583 (defun org-babel-read-table ()
1584 "Read the table at `point' into emacs-lisp."
1585 (mapcar (lambda (row)
1586 (if (and (symbolp row
) (equal row
'hline
)) row
1587 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
)) row
)))
1588 (org-table-to-lisp)))
1590 (defun org-babel-read-list ()
1591 "Read the list at `point' into emacs-lisp."
1592 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
))
1593 (mapcar #'cadr
(cdr (org-list-parse-list)))))
1595 (defvar org-link-types-re
)
1596 (defun org-babel-read-link ()
1597 "Read the link at `point' into emacs-lisp.
1598 If the path of the link is a file path it is expanded using
1599 `expand-file-name'."
1600 (let* ((case-fold-search t
)
1601 (raw (and (looking-at org-bracket-link-regexp
)
1602 (org-babel-clean-text-properties (match-string 1))))
1603 (type (and (string-match org-link-types-re raw
)
1604 (match-string 1 raw
))))
1606 ((not type
) (expand-file-name raw
))
1607 ((string= type
"file")
1608 (and (string-match "file\\(.*\\):\\(.+\\)" raw
)
1609 (expand-file-name (match-string 2 raw
))))
1612 (defun org-babel-format-result (result &optional sep
)
1613 "Format RESULT for writing to file."
1614 (flet ((echo-res (result)
1615 (if (stringp result
) result
(format "%S" result
))))
1624 (echo-res result
))))
1626 (defun org-babel-insert-result
1627 (result &optional result-params info hash indent lang
)
1628 "Insert RESULT into the current buffer.
1629 By default RESULT is inserted after the end of the
1630 current source block. With optional argument RESULT-PARAMS
1631 controls insertion of results in the org-mode file.
1632 RESULT-PARAMS can take the following values...
1634 replace - (default option) insert results after the source block
1635 replacing any previously inserted results
1637 silent -- no results are inserted
1639 file ---- the results are interpreted as a file path, and are
1640 inserted into the buffer using the Org-mode file syntax
1642 list ---- the results are interpreted as an Org-mode list.
1644 raw ----- results are added directly to the Org-mode file. This
1645 is a good option if you code block will output org-mode
1648 wrap ---- results are added directly to the Org-mode file as with
1649 \"raw\", but are wrapped in a RESULTS drawer, allowing
1650 them to later be replaced or removed automatically.
1652 org ----- similar in effect to raw, only the results are wrapped
1653 in an org code block. Similar to the raw option, on
1654 export the results will be interpreted as org-formatted
1655 text, however by wrapping the results in an org code
1656 block they can be replaced upon re-execution of the
1659 html ---- results are added inside of a #+BEGIN_HTML block. This
1660 is a good option if you code block will output html
1663 latex --- results are added inside of a #+BEGIN_LATEX block.
1664 This is a good option if you code block will output
1665 latex formatted text.
1667 code ---- the results are extracted in the syntax of the source
1668 code of the language being evaluated and are added
1669 inside of a #+BEGIN_SRC block with the source-code
1670 language set appropriately. Note this relies on the
1671 optional LANG argument."
1672 (if (stringp result
)
1674 (setq result
(org-babel-clean-text-properties result
))
1675 (when (member "file" result-params
)
1676 (setq result
(org-babel-result-to-file result
))))
1677 (unless (listp result
) (setq result
(format "%S" result
))))
1678 (if (and result-params
(member "silent" result-params
))
1680 (message (replace-regexp-in-string "%" "%%" (format "%S" result
)))
1685 (when (or (org-babel-get-inline-src-block-matches)
1686 (org-babel-get-lob-one-liner-matches))
1687 (goto-char (match-end 0))
1688 (insert (if (listp result
) "\n" " "))
1690 (existing-result (unless inlinep
1691 (org-babel-where-is-src-block-result
1692 t info hash indent
)))
1694 (cdr (assoc :results_switches
(nth 2 info
))))
1696 (when (and (stringp result
) ; ensure results end in a newline
1698 (> (length result
) 0)
1699 (not (or (string-equal (substring result -
1) "\n")
1700 (string-equal (substring result -
1) "\r"))))
1701 (setq result
(concat result
"\n")))
1702 (if (not existing-result
)
1703 (setq beg
(or inlinep
(point)))
1704 (goto-char existing-result
)
1706 (re-search-forward "#" nil t
)
1707 (setq indent
(- (current-column) 1)))
1711 ((member "replace" result-params
)
1712 (delete-region (point) (org-babel-result-end)))
1713 ((member "append" result-params
)
1714 (goto-char (org-babel-result-end)) (setq beg
(point-marker)))
1715 ((member "prepend" result-params
)))) ; already there
1716 (setq results-switches
1717 (if results-switches
(concat " " results-switches
) ""))
1718 (flet ((wrap (start finish
)
1719 (goto-char beg
) (insert (concat start
"\n"))
1720 (goto-char end
) (insert (concat finish
"\n"))
1721 (setq end
(point-marker)))
1722 (proper-list-p (it) (and (listp it
) (null (cdr (last it
))))))
1723 ;; insert results based on type
1725 ;; do nothing for an empty result
1727 ;; insert a list if preferred
1728 ((member "list" result-params
)
1731 (org-list-to-generic
1734 (lambda (el) (list nil
(if (stringp el
) el
(format "%S" el
))))
1735 (if (listp result
) result
(list result
))))
1736 '(:splicep nil
:istart
"- " :iend
"\n")))
1738 ;; assume the result is a table if it's not a string
1739 ((proper-list-p result
)
1741 (insert (concat (orgtbl-to-orgtbl
1742 (if (or (eq 'hline
(car result
))
1743 (and (listp (car result
))
1744 (listp (cdr (car result
)))))
1745 result
(list result
))
1746 '(:fmt
(lambda (cell) (format "%s" cell
)))) "\n"))
1747 (goto-char beg
) (when (org-at-table-p) (org-table-align)))
1748 ((and (listp result
) (not (proper-list-p result
)))
1749 (insert (format "%s\n" result
)))
1750 ((member "file" result-params
)
1751 (when inlinep
(goto-char inlinep
))
1753 (t (goto-char beg
) (insert result
)))
1754 (when (proper-list-p result
) (goto-char (org-table-end)))
1755 (setq end
(point-marker))
1756 ;; possibly wrap result
1758 ((assoc :wrap
(nth 2 info
))
1759 (let ((name (or (cdr (assoc :wrap
(nth 2 info
))) "results")))
1760 (wrap (concat "#+BEGIN_" name
) (concat "#+END_" name
))))
1761 ((member "html" result-params
)
1762 (wrap "#+BEGIN_HTML" "#+END_HTML"))
1763 ((member "latex" result-params
)
1764 (wrap "#+BEGIN_LaTeX" "#+END_LaTeX"))
1765 ((member "code" result-params
)
1766 (wrap (format "#+BEGIN_SRC %s%s" (or lang
"none") results-switches
)
1768 ((member "org" result-params
)
1769 (wrap "#+BEGIN_ORG" "#+END_ORG"))
1770 ((member "raw" result-params
)
1771 (goto-char beg
) (if (org-at-table-p) (org-cycle)))
1772 ((member "wrap" result-params
)
1773 (wrap ":RESULTS:" ":END:"))
1774 ((and (not (proper-list-p result
))
1775 (not (member "file" result-params
)))
1776 (org-babel-examplize-region beg end results-switches
)
1777 (setq end
(point)))))
1778 ;; possibly indent the results to match the #+results line
1779 (when (and (not inlinep
) (numberp indent
) indent
(> indent
0)
1780 ;; in this case `table-align' does the work for us
1781 (not (and (listp result
)
1782 (member "append" result-params
))))
1783 (indent-rigidly beg end indent
))))
1785 (if (member "value" result-params
)
1786 (message "Code block returned no value.")
1787 (message "Code block produced no output."))
1788 (message "Code block evaluation complete."))))
1790 (defun org-babel-remove-result (&optional info
)
1791 "Remove the result of the current source block."
1793 (let ((location (org-babel-where-is-src-block-result nil info
)) start
)
1795 (setq start
(- location
1))
1797 (goto-char location
) (forward-line 1)
1798 (delete-region start
(org-babel-result-end))))))
1800 (defun org-babel-result-end ()
1801 "Return the point at the end of the current set of results"
1804 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
1805 ((org-at-item-p) (let* ((struct (org-list-struct))
1806 (prvs (org-list-prevs-alist struct
)))
1807 (org-list-get-list-end (point-at-bol) struct prvs
)))
1808 ((looking-at "^\\([ \t]*\\):RESULTS:")
1809 (re-search-forward (concat "^" (match-string 1) ":END:")))
1811 (let ((case-fold-search t
))
1812 (if (looking-at (concat "[ \t]*#\\+begin_\\([^ \t\n\r]+\\)"))
1813 (progn (re-search-forward (concat "[ \t]*#\\+end_" (match-string 1))
1816 (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
1820 (defun org-babel-result-to-file (result)
1821 "Convert RESULT into an `org-mode' link.
1822 If the `default-directory' is different from the containing
1823 file's directory then expand relative links."
1824 (flet ((cond-exp (file)
1825 (if (and default-directory
1827 (not (string= (expand-file-name default-directory
)
1829 (file-name-directory buffer-file-name
)))))
1830 (expand-file-name file default-directory
)
1832 (if (stringp result
)
1833 (format "[[file:%s]]" (cond-exp result
))
1834 (when (and (listp result
) (= 2 (length result
))
1835 (stringp (car result
)) (stringp (cadr result
)))
1836 (format "[[file:%s][%s]]" (car result
) (cadr result
))))))
1838 (defun org-babel-examplize-region (beg end
&optional results-switches
)
1839 "Comment out region using the inline '==' or ': ' org example quote."
1841 (flet ((chars-between (b e
) (string-match "[\\S]" (buffer-substring b e
))))
1842 (if (or (chars-between (save-excursion (goto-char beg
) (point-at-bol)) beg
)
1843 (chars-between end
(save-excursion (goto-char end
) (point-at-eol))))
1846 (insert (format "=%s=" (prog1 (buffer-substring beg end
)
1847 (delete-region beg end
)))))
1848 (let ((size (count-lines beg end
)))
1850 (cond ((= size
0)) ; do nothing for an empty result
1851 ((< size org-babel-min-lines-for-block-output
)
1854 (beginning-of-line 1) (insert ": ") (forward-line 1)))
1857 (insert (if results-switches
1858 (format "#+begin_example%s\n" results-switches
)
1859 "#+begin_example\n"))
1860 (if (markerp end
) (goto-char end
) (forward-char (- end beg
)))
1861 (insert "#+end_example\n"))))))))
1863 (defun org-babel-update-block-body (new-body)
1864 "Update the body of the current code block to NEW-BODY."
1865 (if (not (org-babel-where-is-src-block-head))
1866 (error "not in source block")
1868 (replace-match (concat (org-babel-trim new-body
) "\n") nil t nil
5))
1869 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
1871 (defun org-babel-merge-params (&rest plists
)
1872 "Combine all parameter association lists in PLISTS.
1873 Later elements of PLISTS override the values of previous elements.
1874 This takes into account some special considerations for certain
1875 parameters when merging lists."
1876 (let ((results-exclusive-groups
1877 (mapcar (lambda (group) (mapcar #'symbol-name group
))
1878 (cdr (assoc 'results org-babel-common-header-args-w-values
))))
1879 (exports-exclusive-groups
1880 (mapcar (lambda (group) (mapcar #'symbol-name group
))
1881 (cdr (assoc 'exports org-babel-common-header-args-w-values
))))
1883 params results exports tangle noweb cache vars shebang comments padline
)
1884 (flet ((e-merge (exclusive-groups &rest result-params
)
1885 ;; maintain exclusivity of mutually exclusive parameters
1887 (mapc (lambda (new-params)
1888 (mapc (lambda (new-param)
1889 (mapc (lambda (exclusive-group)
1890 (when (member new-param exclusive-group
)
1891 (mapcar (lambda (excluded-param)
1898 (setq output
(org-uniquify
1899 (cons new-param output
))))
1909 (let ((name (if (listp (cdr pair
))
1911 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
1913 (intern (match-string 1 (cdr pair
)))))))
1917 (if (member name
(mapcar #'car vars
))
1921 (unless (equal (car p
) name
) p
))
1924 (list (cons name pair
))))
1925 ;; if no name is given and we already have named variables
1926 ;; then assign to named variables in order
1927 (if (and vars
(nth variable-index vars
))
1928 (prog1 (setf (cddr (nth variable-index vars
))
1929 (concat (symbol-name
1930 (car (nth variable-index vars
)))
1932 (incf variable-index
))
1933 (error "variable \"%s\" must be assigned a default value"
1936 (setq results
(e-merge results-exclusive-groups
1939 (let ((r (cdr pair
)))
1940 (if (stringp r
) r
(eval r
)))))))
1943 (setq results
(e-merge results-exclusive-groups
1945 (unless (or (member "both" exports
)
1946 (member "none" exports
)
1947 (member "code" exports
))
1948 (setq exports
(e-merge exports-exclusive-groups
1949 exports
'("results"))))
1950 (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))
1952 (setq exports
(e-merge exports-exclusive-groups
1953 exports
(split-string (cdr pair
)))))
1954 (:tangle
;; take the latest -- always overwrite
1955 (setq tangle
(or (list (cdr pair
)) tangle
)))
1957 (setq noweb
(e-merge '(("yes" "no" "tangle")) noweb
1958 (split-string (or (cdr pair
) "")))))
1960 (setq cache
(e-merge '(("yes" "no")) cache
1961 (split-string (or (cdr pair
) "")))))
1963 (setq padline
(e-merge '(("yes" "no")) padline
1964 (split-string (or (cdr pair
) "")))))
1965 (:shebang
;; take the latest -- always overwrite
1966 (setq shebang
(or (list (cdr pair
)) shebang
)))
1968 (setq comments
(e-merge '(("yes" "no")) comments
1969 (split-string (or (cdr pair
) "")))))
1970 (t ;; replace: this covers e.g. :session
1971 (setq params
(cons pair
(assq-delete-all (car pair
) params
))))))
1974 (setq vars
(reverse vars
))
1975 (while vars
(setq params
(cons (cons :var
(cddr (pop vars
))) params
)))
1978 (let ((key (intern (concat ":" (symbol-name hd
))))
1980 (setf params
(cons (cons key
(mapconcat 'identity val
" ")) params
))))
1981 '(results exports tangle noweb padline cache shebang comments
))
1984 (defvar *org-babel-use-quick-and-dirty-noweb-expansion
* nil
1985 "Set to true to use regular expressions to expand noweb references.
1986 This results in much faster noweb reference expansion but does
1987 not properly allow code blocks to inherit the \":noweb-ref\"
1988 header argument from buffer or subtree wide properties.")
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 (rx-prefix (concat "\\(" org-babel-src-name-regexp
"\\|"
2026 ":noweb-ref[ \t]+" "\\)"))
2027 (new-body "") index source-name evaluate prefix blocks-in-buffer
)
2028 (flet ((nb-add (text) (setq new-body
(concat new-body text
)))
2031 (funcall (intern (concat lang
"-mode")))
2032 (comment-region (point) (progn (insert text
) (point)))
2033 (org-babel-trim (buffer-string)))))
2035 (insert body
) (goto-char (point-min))
2036 (setq index
(point))
2037 (while (and (re-search-forward "<<\\(.+?\\)>>" nil t
))
2038 (save-match-data (setf source-name
(match-string 1)))
2039 (save-match-data (setq evaluate
(string-match "\(.*\)" source-name
)))
2042 (buffer-substring (match-beginning 0)
2044 (beginning-of-line 1) (point)))))
2045 ;; add interval to new-body (removing noweb reference)
2046 (goto-char (match-beginning 0))
2047 (nb-add (buffer-substring index
(point)))
2048 (goto-char (match-end 0))
2049 (setq index
(point))
2051 (with-current-buffer parent-buffer
2052 (mapconcat ;; interpose PREFIX between every line
2056 (let ((raw (org-babel-ref-resolve source-name
)))
2057 (if (stringp raw
) raw
(format "%S" raw
)))
2059 ;; retrieve from the library of babel
2060 (nth 2 (assoc (intern source-name
)
2061 org-babel-library-of-babel
))
2062 ;; return the contents of headlines literally
2064 (when (org-babel-ref-goto-headline-id source-name
)
2065 (org-babel-ref-headline-body)))
2066 ;; find the expansion of reference in this buffer
2067 (let ((rx (concat rx-prefix source-name
))
2070 (goto-char (point-min))
2071 (if *org-babel-use-quick-and-dirty-noweb-expansion
*
2072 (while (re-search-forward rx nil t
)
2073 (let* ((i (org-babel-get-src-block-info 'light
))
2074 (body (org-babel-expand-noweb-references i
))
2077 (concat (c-wrap (car cs
)) "\n"
2079 (c-wrap (cadr cs
))))
2080 (org-babel-tangle-comment-links i
))
2082 (setq expansion
(concat expansion full
))))
2083 (org-babel-map-src-blocks nil
2084 (let ((i (org-babel-get-src-block-info 'light
)))
2085 (when (equal (or (cdr (assoc :noweb-ref
(nth 2 i
)))
2088 (let* ((body (org-babel-expand-noweb-references i
))
2091 (concat (c-wrap (car cs
)) "\n"
2093 (c-wrap (cadr cs
))))
2094 (org-babel-tangle-comment-links i
))
2096 (setq expansion
(concat expansion full
))))))))
2098 ;; possibly raise an error if named block doesn't exist
2099 (if (member lang org-babel-noweb-error-langs
)
2101 "<<" source-name
">> "
2102 "could not be resolved (see "
2103 "`org-babel-noweb-error-langs')"))
2105 "[\n\r]") (concat "\n" prefix
)))))
2106 (nb-add (buffer-substring index
(point-max)))))
2109 (defun org-babel-clean-text-properties (text)
2110 "Strip all properties from text return."
2112 (set-text-properties 0 (length text
) nil text
) text
))
2114 (defun org-babel-strip-protective-commas (body)
2115 "Strip protective commas from bodies of source blocks."
2117 (replace-regexp-in-string "^,#" "#" body
)))
2119 (defun org-babel-script-escape (str &optional force
)
2120 "Safely convert tables into elisp lists."
2121 (let (in-single in-double out
)
2122 ((lambda (escaped) (condition-case nil
(org-babel-read escaped
) (error escaped
)))
2126 (or (and (string-equal "[" (substring str
0 1))
2127 (string-equal "]" (substring str -
1)))
2128 (and (string-equal "{" (substring str
0 1))
2129 (string-equal "}" (substring str -
1)))
2130 (and (string-equal "(" (substring str
0 1))
2131 (string-equal ")" (substring str -
1))))))
2141 (91 (if (or in-double in-single
) ; [
2144 (93 (if (or in-double in-single
) ; ]
2147 (123 (if (or in-double in-single
) ; {
2150 (125 (if (or in-double in-single
) ; }
2153 (44 (if (or in-double in-single
) ; ,
2154 (cons 44 out
) (cons 32 out
)))
2155 (39 (if in-double
; '
2157 (setq in-single
(not in-single
)) (cons 34 out
)))
2158 (34 (if in-single
; "
2159 (append (list 34 32) out
)
2160 (setq in-double
(not in-double
)) (cons 34 out
)))
2161 (t (cons ch out
)))))
2162 (string-to-list str
))
2163 (apply #'string
(reverse out
)))))
2166 (defun org-babel-read (cell &optional inhibit-lisp-eval
)
2167 "Convert the string value of CELL to a number if appropriate.
2168 Otherwise if cell looks like lisp (meaning it starts with a
2169 \"(\", \"'\", \"`\" or a \"[\") then read it as lisp, otherwise
2170 return it unmodified as a string. Optional argument NO-LISP-EVAL
2171 inhibits lisp evaluation for situations in which is it not
2173 (if (and (stringp cell
) (not (equal cell
"")))
2174 (or (org-babel-number-p cell
)
2175 (if (and (not inhibit-lisp-eval
)
2176 (member (substring cell
0 1) '("(" "'" "`" "[")))
2178 (if (string= (substring cell
0 1) "\"")
2180 (progn (set-text-properties 0 (length cell
) nil cell
) cell
))))
2183 (defun org-babel-number-p (string)
2184 "If STRING represents a number return its value."
2185 (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string
)
2186 (= (length (substring string
(match-beginning 0)
2189 (string-to-number string
)))
2191 (defun org-babel-import-elisp-from-file (file-name &optional separator
)
2192 "Read the results located at FILE-NAME into an elisp table.
2193 If the table is trivial, then return it as a scalar."
2195 (save-window-excursion
2199 (org-table-import file-name separator
)
2200 (delete-file file-name
)
2201 (setq result
(mapcar (lambda (row)
2202 (mapcar #'org-babel-string-read row
))
2203 (org-table-to-lisp))))
2205 (if (null (cdr result
)) ;; if result is trivial vector, then scalarize it
2206 (if (consp (car result
))
2207 (if (null (cdr (car result
)))
2213 (defun org-babel-string-read (cell)
2214 "Strip nested \"s from around strings."
2215 (org-babel-read (or (and (stringp cell
)
2216 (string-match "\\\"\\(.+\\)\\\"" cell
)
2217 (match-string 1 cell
))
2220 (defun org-babel-reverse-string (string)
2221 "Return the reverse of STRING."
2222 (apply 'string
(reverse (string-to-list string
))))
2224 (defun org-babel-chomp (string &optional regexp
)
2225 "Strip trailing spaces and carriage returns from STRING.
2226 Default regexp used is \"[ \f\t\n\r\v]\" but can be
2227 overwritten by specifying a regexp as a second argument."
2228 (let ((regexp (or regexp
"[ \f\t\n\r\v]")))
2229 (while (and (> (length string
) 0)
2230 (string-match regexp
(substring string -
1)))
2231 (setq string
(substring string
0 -
1)))
2234 (defun org-babel-trim (string &optional regexp
)
2235 "Strip leading and trailing spaces and carriage returns from STRING.
2236 Like `org-babel-chomp' only it runs on both the front and back
2238 (org-babel-chomp (org-babel-reverse-string
2239 (org-babel-chomp (org-babel-reverse-string string
) regexp
))
2242 (defvar org-babel-org-babel-call-process-region-original nil
)
2243 (defun org-babel-tramp-handle-call-process-region
2244 (start end program
&optional delete buffer display
&rest args
)
2245 "Use tramp to handle call-process-region.
2246 Fixes a bug in `tramp-handle-call-process-region'."
2247 (if (and (featurep 'tramp
) (file-remote-p default-directory
))
2248 (let ((tmpfile (tramp-compat-make-temp-file "")))
2249 (write-region start end tmpfile
)
2250 (when delete
(delete-region start end
))
2252 ;; (apply 'call-process program tmpfile buffer display args)
2254 (apply 'process-file program tmpfile buffer display args
)
2255 (delete-file tmpfile
)))
2256 ;; org-babel-call-process-region-original is the original emacs
2257 ;; definition. It is in scope from the let binding in
2258 ;; org-babel-execute-src-block
2259 (apply org-babel-call-process-region-original
2260 start end program delete buffer display args
)))
2262 (defun org-babel-local-file-name (file)
2263 "Return the local name component of FILE."
2264 (if (file-remote-p file
)
2266 (with-parsed-tramp-file-name file nil
2270 (defun org-babel-process-file-name (name &optional no-quote-p
)
2271 "Prepare NAME to be used in an external process.
2272 If NAME specifies a remote location, the remote portion of the
2273 name is removed, since in that case the process will be executing
2274 remotely. The file name is then processed by
2275 `expand-file-name'. Unless second argument NO-QUOTE-P is non-nil,
2276 the file name is additionally processed by
2277 `shell-quote-argument'"
2278 ((lambda (f) (if no-quote-p f
(shell-quote-argument f
)))
2279 (expand-file-name (org-babel-local-file-name name
))))
2281 (defvar org-babel-temporary-directory
)
2282 (unless (or noninteractive
(boundp 'org-babel-temporary-directory
))
2283 (defvar org-babel-temporary-directory
2284 (or (and (boundp 'org-babel-temporary-directory
)
2285 (file-exists-p org-babel-temporary-directory
)
2286 org-babel-temporary-directory
)
2287 (make-temp-file "babel-" t
))
2288 "Directory to hold temporary files created to execute code blocks.
2289 Used by `org-babel-temp-file'. This directory will be removed on
2292 (defun org-babel-temp-file (prefix &optional suffix
)
2293 "Create a temporary file in the `org-babel-temporary-directory'.
2294 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2295 value of `temporary-file-directory' temporarily set to the value
2296 of `org-babel-temporary-directory'."
2297 (if (file-remote-p default-directory
)
2299 (concat (file-remote-p default-directory
)
2301 prefix temporary-file-directory
)
2303 (let ((temporary-file-directory
2304 (or (and (boundp 'org-babel-temporary-directory
)
2305 (file-exists-p org-babel-temporary-directory
)
2306 org-babel-temporary-directory
)
2307 temporary-file-directory
)))
2308 (make-temp-file prefix nil suffix
))))
2310 (defun org-babel-remove-temporary-directory ()
2311 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2312 (when (and (boundp 'org-babel-temporary-directory
)
2313 (file-exists-p org-babel-temporary-directory
))
2314 ;; taken from `delete-directory' in files.el
2317 (mapc (lambda (file)
2318 ;; This test is equivalent to
2319 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2320 ;; but more efficient
2321 (if (eq t
(car (file-attributes file
)))
2322 (delete-directory file
)
2323 (delete-file file
)))
2324 ;; We do not want to delete "." and "..".
2325 (directory-files org-babel-temporary-directory
'full
2326 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2327 (delete-directory org-babel-temporary-directory
))
2329 (message "Failed to remove temporary Org-babel directory %s"
2330 (if (boundp 'org-babel-temporary-directory
)
2331 org-babel-temporary-directory
2332 "[directory not defined]"))))))
2334 (add-hook 'kill-emacs-hook
'org-babel-remove-temporary-directory
)