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."
108 :type
'(choice boolean function
))
109 ;; don't allow this variable to be changed through file settings
110 (put 'org-confirm-babel-evaluate
'safe-local-variable
(lambda (x) (eq x t
)))
112 (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
113 "Remove code block evaluation from the C-c C-c key binding."
118 (defcustom org-babel-results-keyword
"RESULTS"
119 "Keyword used to name results generated by code blocks.
120 Should be either RESULTS or NAME however any capitalization may
125 (defcustom org-babel-noweb-wrap-start
"<<"
126 "String used to begin a noweb reference in a code block.
127 See also `org-babel-noweb-wrap-end'."
131 (defcustom org-babel-noweb-wrap-end
">>"
132 "String used to end a noweb reference in a code block.
133 See also `org-babel-noweb-wrap-start'."
137 (defun org-babel-noweb-wrap (&optional regexp
)
138 (concat org-babel-noweb-wrap-start
139 (or regexp
"\\([^ \t\n].+?[^ \t]\\|[^ \t\n]\\)")
140 org-babel-noweb-wrap-end
))
142 (defvar org-babel-src-name-regexp
143 "^[ \t]*#\\+name:[ \t]*"
144 "Regular expression used to match a source name line.")
146 (defvar org-babel-multi-line-header-regexp
147 "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
148 "Regular expression used to match multi-line header arguments.")
150 (defvar org-babel-src-name-w-name-regexp
151 (concat org-babel-src-name-regexp
153 org-babel-multi-line-header-regexp
155 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)")
156 "Regular expression matching source name lines with a name.")
158 (defvar org-babel-src-block-regexp
160 ;; (1) indentation (2) lang
161 "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
163 "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
164 ;; (4) header arguments
167 "\\([^\000]*?\n\\)?[ \t]*#\\+end_src")
168 "Regexp used to identify code blocks.")
170 (defvar org-babel-inline-src-block-regexp
172 ;; (1) replacement target (2) lang
173 "\\(?:^\\|[^-[:alnum:]]\\)\\(src_\\([^ \f\t\n\r\v]+\\)"
174 ;; (3,4) (unused, headers)
175 "\\(\\|\\[\\(.*?\\)\\]\\)"
177 "{\\([^\f\n\r\v]+?\\)}\\)")
178 "Regexp used to identify inline src-blocks.")
180 (defun org-babel-get-header (params key
&optional others
)
181 "Select only header argument of type KEY from a list.
182 Optional argument OTHERS indicates that only the header that do
183 not match KEY should be returned."
186 (lambda (p) (when (funcall (if others
#'not
#'identity
) (eq (car p
) key
)) p
))
189 (defun org-babel-get-inline-src-block-matches()
190 "Set match data if within body of an inline source block.
191 Returns non-nil if match-data set"
192 (let ((src-at-0-p (save-excursion
193 (beginning-of-line 1)
194 (string= "src" (thing-at-point 'word
))))
195 (first-line-p (= 1 (line-number-at-pos)))
197 (let ((search-for (cond ((and src-at-0-p first-line-p
"src_"))
198 (first-line-p "[[:punct:] \t]src_")
199 (t "[[:punct:] \f\t\n\r\v]src_")))
200 (lower-limit (if first-line-p
202 (- (point-at-bol) 1))))
204 (when (or (and src-at-0-p
(bobp))
205 (and (re-search-forward "}" (point-at-eol) t
)
206 (re-search-backward search-for lower-limit t
)
208 (when (looking-at org-babel-inline-src-block-regexp
)
211 (defvar org-babel-inline-lob-one-liner-regexp
)
212 (defun org-babel-get-lob-one-liner-matches()
213 "Set match data if on line of an lob one liner.
214 Returns non-nil if match-data set"
216 (unless (= (point) (point-at-bol)) ;; move before inline block
217 (re-search-backward "[ \f\t\n\r\v]" nil t
))
218 (if (looking-at org-babel-inline-lob-one-liner-regexp
)
222 (defun org-babel-get-src-block-info (&optional light
)
223 "Get information on the current source block.
225 Optional argument LIGHT does not resolve remote variable
226 references; a process which could likely result in the execution
227 of other code blocks.
230 (language body header-arguments-alist switches name indent)."
231 (let ((case-fold-search t
) head info name indent
)
233 (if (setq head
(org-babel-where-is-src-block-head))
236 (setq info
(org-babel-parse-src-block-match))
237 (setq indent
(car (last info
)))
238 (setq info
(butlast info
))
239 (while (and (forward-line -
1)
240 (looking-at org-babel-multi-line-header-regexp
))
242 (org-babel-merge-params
244 (org-babel-parse-header-arguments (match-string 1)))))
245 (when (looking-at org-babel-src-name-w-name-regexp
)
246 (setq name
(org-babel-clean-text-properties (match-string 3)))
247 (when (and (match-string 5) (> (length (match-string 5)) 0))
248 (setf (nth 2 info
) ;; merge functional-syntax vars and header-args
249 (org-babel-merge-params
251 (lambda (ref) (cons :var ref
))
253 (lambda (var) ;; check that each variable is initialized
254 (if (string-match ".+=.+" var
)
257 "variable \"%s\"%s must be assigned a default value"
258 var
(if name
(format " in block \"%s\"" name
) ""))))
259 (org-babel-ref-split-args (match-string 5))))
261 ;; inline source block
262 (when (org-babel-get-inline-src-block-matches)
263 (setq info
(org-babel-parse-inline-src-block-match))))
264 ;; resolve variable references and add summary parameters
265 (when (and info
(not light
))
266 (setf (nth 2 info
) (org-babel-process-params (nth 2 info
))))
267 (when info
(append info
(list name indent
)))))
269 (defvar org-current-export-file
) ; dynamically bound
270 (defun org-babel-confirm-evaluate (info)
271 "Confirm evaluation of the code block INFO.
272 This behavior can be suppressed by setting the value of
273 `org-confirm-babel-evaluate' to nil, in which case all future
274 interactive code block evaluations will proceed without any
275 confirmation from the user.
277 Note disabling confirmation may result in accidental evaluation
278 of potentially harmful code."
279 (let* ((eval (or (cdr (assoc :eval
(nth 2 info
)))
280 (when (assoc :noeval
(nth 2 info
)) "no")))
281 (query (cond ((equal eval
"query") t
)
282 ((and org-current-export-file
283 (equal eval
"query-export")) t
)
284 ((functionp org-confirm-babel-evaluate
)
285 (funcall org-confirm-babel-evaluate
286 (nth 0 info
) (nth 1 info
)))
287 (t org-confirm-babel-evaluate
))))
288 (if (or (equal eval
"never") (equal eval
"no")
289 (and org-current-export-file
(or (equal eval
"no-export")
290 (equal eval
"never-export")))
293 (format "Evaluate this%scode block%son your system? "
294 (if info
(format " %s " (nth 0 info
)) " ")
296 (format " (%s) " (nth 4 info
)) " "))))))
297 (prog1 nil
(message "Evaluation %s"
298 (if (or (equal eval
"never") (equal eval
"no")
299 (equal eval
"no-export")
300 (equal eval
"never-export"))
301 "Disabled" "Aborted")))
305 (defun org-babel-execute-safely-maybe ()
306 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
307 (org-babel-execute-maybe)))
309 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-execute-safely-maybe
)
312 (defun org-babel-execute-maybe ()
314 (or (org-babel-execute-src-block-maybe)
315 (org-babel-lob-execute-maybe)))
317 (defun org-babel-execute-src-block-maybe ()
318 "Conditionally execute a source block.
319 Detect if this is context for a Babel src-block and if so
320 then run `org-babel-execute-src-block'."
322 (let ((info (org-babel-get-src-block-info)))
324 (progn (org-babel-eval-wipe-error-buffer)
325 (org-babel-execute-src-block current-prefix-arg info
) t
) nil
)))
328 (defun org-babel-view-src-block-info ()
329 "Display information on the current source block.
330 This includes header arguments, language and name, and is largely
331 a window into the `org-babel-get-src-block-info' function."
333 (let ((info (org-babel-get-src-block-info 'light
)))
334 (flet ((full (it) (> (length it
) 0))
335 (printf (fmt &rest args
) (princ (apply #'format fmt args
))))
337 (with-help-window (help-buffer)
338 (let ((name (nth 4 info
))
340 (switches (nth 3 info
))
341 (header-args (nth 2 info
)))
342 (when name
(printf "Name: %s\n" name
))
343 (when lang
(printf "Lang: %s\n" lang
))
344 (when (full switches
) (printf "Switches: %s\n" switches
))
345 (printf "Header Arguments:\n")
346 (dolist (pair (sort header-args
347 (lambda (a b
) (string< (symbol-name (car a
))
348 (symbol-name (car b
))))))
349 (when (full (cdr pair
))
350 (printf "\t%S%s\t%s\n"
352 (if (> (length (format "%S" (car pair
))) 7) "" "\t")
356 (defun org-babel-expand-src-block-maybe ()
357 "Conditionally expand a source block.
358 Detect if this is context for a org-babel src-block and if so
359 then run `org-babel-expand-src-block'."
361 (let ((info (org-babel-get-src-block-info)))
363 (progn (org-babel-expand-src-block current-prefix-arg info
) t
)
367 (defun org-babel-load-in-session-maybe ()
368 "Conditionally load a source block in a session.
369 Detect if this is context for a org-babel src-block and if so
370 then run `org-babel-load-in-session'."
372 (let ((info (org-babel-get-src-block-info)))
374 (progn (org-babel-load-in-session current-prefix-arg info
) t
)
377 (add-hook 'org-metaup-hook
'org-babel-load-in-session-maybe
)
380 (defun org-babel-pop-to-session-maybe ()
381 "Conditionally pop to a session.
382 Detect if this is context for a org-babel src-block and if so
383 then run `org-babel-pop-to-session'."
385 (let ((info (org-babel-get-src-block-info)))
386 (if info
(progn (org-babel-pop-to-session current-prefix-arg info
) t
) nil
)))
388 (add-hook 'org-metadown-hook
'org-babel-pop-to-session-maybe
)
390 (defconst org-babel-common-header-args-w-values
391 '((cache .
((no yes
)))
393 (colnames .
((nil no yes
)))
394 (comments .
((no link yes org both noweb
)))
396 (eval .
((never query
)))
397 (exports .
((code results both none
)))
399 (hlines .
((no yes
)))
400 (mkdirp .
((yes no
)))
403 (noweb .
((yes no tangle no-export strip-export
)))
406 (padline .
((yes no
)))
407 (results .
((file list vector table scalar verbatim
)
408 (raw org html latex code pp wrap
)
409 (replace silent append prepend
)
411 (rownames .
((no yes
)))
415 (tangle .
((tangle yes no
:any
)))
419 (defconst org-babel-header-arg-names
420 (mapcar #'car org-babel-common-header-args-w-values
)
421 "Common header arguments used by org-babel.
422 Note that individual languages may define their own language
423 specific header arguments as well.")
425 (defvar org-babel-default-header-args
426 '((:session .
"none") (:results .
"replace") (:exports .
"code")
427 (:cache .
"no") (:noweb .
"no") (:hlines .
"no") (:tangle .
"no")
428 (:padnewline .
"yes"))
429 "Default arguments to use when evaluating a source block.")
431 (defvar org-babel-default-inline-header-args
432 '((:session .
"none") (:results .
"replace") (:exports .
"results"))
433 "Default arguments to use when evaluating an inline source block.")
435 (defvar org-babel-data-names
'("TBLNAME" "RESULTS" "NAME"))
437 (defvar org-babel-result-regexp
438 (concat "^[ \t]*#\\+"
439 (regexp-opt org-babel-data-names t
)
440 "\\(\\[\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*")
441 "Regular expression used to match result lines.
442 If the results are associated with a hash key then the hash will
443 be saved in the second match data.")
445 (defvar org-babel-result-w-name-regexp
446 (concat org-babel-result-regexp
447 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
449 (defvar org-babel-min-lines-for-block-output
10
450 "The minimum number of lines for block output.
451 If number of lines of output is equal to or exceeds this
452 value, the output is placed in a #+begin_example...#+end_example
453 block. Otherwise the output is marked as literal by inserting
454 colons at the starts of the lines. This variable only takes
455 effect if the :results output option is in effect.")
457 (defvar org-babel-noweb-error-langs nil
458 "Languages for which Babel will raise literate programming errors.
459 List of languages for which errors should be raised when the
460 source code block satisfying a noweb reference in this language
461 can not be resolved.")
463 (defvar org-babel-hash-show
4
464 "Number of initial characters to show of a hidden results hash.")
466 (defvar org-babel-after-execute-hook nil
467 "Hook for functions to be called after `org-babel-execute-src-block'")
469 (defun org-babel-named-src-block-regexp-for-name (name)
470 "This generates a regexp used to match a src block named NAME."
471 (concat org-babel-src-name-regexp
(regexp-quote name
)
472 "\\([ \t]\\|$\\|(\\)" ".*[\r\n]"
473 (substring org-babel-src-block-regexp
1)))
475 (defun org-babel-named-data-regexp-for-name (name)
476 "This generates a regexp used to match data named NAME."
477 (concat org-babel-result-regexp
(regexp-quote name
) "\\([ \t]\\|$\\)"))
480 (defvar call-process-region
)
483 (defun org-babel-execute-src-block (&optional arg info params
)
484 "Execute the current source code block.
485 Insert the results of execution into the buffer. Source code
486 execution and the collection and formatting of results can be
487 controlled through a variety of header arguments.
489 With prefix argument ARG, force re-execution even if an existing
490 result cached in the buffer would otherwise have been returned.
492 Optionally supply a value for INFO in the form returned by
493 `org-babel-get-src-block-info'.
495 Optionally supply a value for PARAMS which will be merged with
496 the header arguments specified at the front of the source code
499 (let ((info (or info
(org-babel-get-src-block-info))))
500 (when (org-babel-confirm-evaluate
502 (setf (nth 2 i
) (org-babel-merge-params (nth 2 info
) params
))
504 (let* ((lang (nth 0 info
))
506 (org-babel-process-params
507 (org-babel-merge-params (nth 2 info
) params
))
509 (cache?
(and (not arg
) (cdr (assoc :cache params
))
510 (string= "yes" (cdr (assoc :cache params
)))))
511 (result-params (cdr (assoc :result-params params
)))
512 (new-hash (when cache?
(org-babel-sha1-hash info
)))
513 (old-hash (when cache?
(org-babel-current-result-hash)))
514 (body (setf (nth 1 info
)
515 (if (org-babel-noweb-p params
:eval
)
516 (org-babel-expand-noweb-references info
)
518 (dir (cdr (assoc :dir params
)))
520 (or (and dir
(file-name-as-directory dir
)) default-directory
))
521 (org-babel-call-process-region-original
522 (if (boundp 'org-babel-call-process-region-original
)
523 org-babel-call-process-region-original
524 (symbol-function 'call-process-region
)))
525 (indent (car (last info
)))
528 (flet ((call-process-region (&rest args
)
529 (apply 'org-babel-tramp-handle-call-process-region args
)))
530 (flet ((lang-check (f)
531 (let ((f (intern (concat "org-babel-execute:" f
))))
532 (when (fboundp f
) f
))))
534 (or (lang-check lang
)
535 (lang-check (symbol-name
536 (cdr (assoc lang org-src-lang-modes
))))
537 (error "No org-babel-execute function for %s!" lang
))))
538 (if (and (not arg
) new-hash
(equal new-hash old-hash
))
539 (save-excursion ;; return cached result
540 (goto-char (org-babel-where-is-src-block-result nil info
))
541 (end-of-line 1) (forward-char 1)
542 (setq result
(org-babel-read-result))
543 (message (replace-regexp-in-string
544 "%" "%%" (format "%S" result
))) result
)
545 (message "executing %s code block%s..."
547 (if (nth 4 info
) (format " (%s)" (nth 4 info
)) ""))
550 (if (and (eq (cdr (assoc :result-type params
)) 'value
)
551 (or (member "vector" result-params
)
552 (member "table" result-params
))
553 (not (listp result
)))
554 (list (list result
)) result
))
555 (funcall cmd body params
)))
556 ;; if non-empty result and :file then write to :file
557 (when (cdr (assoc :file params
))
559 (with-temp-file (cdr (assoc :file params
))
561 (org-babel-format-result
562 result
(cdr (assoc :sep
(nth 2 info
)))))))
563 (setq result
(cdr (assoc :file params
))))
564 (org-babel-insert-result
565 result result-params info new-hash indent lang
)
566 (run-hooks 'org-babel-after-execute-hook
)
568 (setq call-process-region
'org-babel-call-process-region-original
))))))
570 (defun org-babel-expand-body:generic
(body params
&optional var-lines
)
571 "Expand BODY with PARAMS.
572 Expand a block of code with org-babel according to its header
573 arguments. This generic implementation of body expansion is
574 called for languages which have not defined their own specific
575 org-babel-expand-body:lang function."
576 (mapconcat #'identity
(append var-lines
(list body
)) "\n"))
579 (defun org-babel-expand-src-block (&optional arg info params
)
580 "Expand the current source code block.
581 Expand according to the source code block's header
582 arguments and pop open the results in a preview buffer."
584 (let* ((info (or info
(org-babel-get-src-block-info)))
586 (params (setf (nth 2 info
)
587 (sort (org-babel-merge-params (nth 2 info
) params
)
588 (lambda (el1 el2
) (string< (symbol-name (car el1
))
589 (symbol-name (car el2
)))))))
590 (body (setf (nth 1 info
)
591 (if (org-babel-noweb-p params
:eval
)
592 (org-babel-expand-noweb-references info
) (nth 1 info
))))
593 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
594 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
597 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
598 (org-babel-expand-body:generic
599 body params
(and (fboundp assignments-cmd
)
600 (funcall assignments-cmd params
))))))
602 nil expanded
(concat "*Org-Babel Preview " (buffer-name) "[ " lang
" ]*"))))
604 (defun org-babel-edit-distance (s1 s2
)
605 "Return the edit (levenshtein) distance between strings S1 S2."
606 (let* ((l1 (length s1
))
608 (dist (map 'vector
(lambda (_) (make-vector (1+ l2
) nil
))
609 (number-sequence 1 (1+ l1
)))))
610 (flet ((in (i j
) (aref (aref dist i
) j
))
611 (mmin (&rest lst
) (apply #'min
(remove nil lst
))))
612 (setf (aref (aref dist
0) 0) 0)
613 (dolist (i (number-sequence 1 l1
))
614 (dolist (j (number-sequence 1 l2
))
615 (setf (aref (aref dist i
) j
)
616 (+ (if (equal (aref s1
(1- i
)) (aref s2
(1- j
))) 0 1)
617 (mmin (in (1- i
) j
) (in i
(1- j
)) (in (1- i
) (1- j
)))))))
621 (defun org-babel-check-src-block ()
622 "Check for misspelled header arguments in the current code block."
624 ;; TODO: report malformed code block
625 ;; TODO: report incompatible combinations of header arguments
626 ;; TODO: report uninitialized variables
627 (let ((too-close 2) ;; <- control closeness to report potential match
628 (names (mapcar #'symbol-name org-babel-header-arg-names
)))
629 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg
)) 1))
630 (and (org-babel-where-is-src-block-head)
631 (org-babel-parse-header-arguments
632 (org-babel-clean-text-properties
633 (match-string 4))))))
635 (when (and (not (string= header name
))
636 (<= (org-babel-edit-distance header name
) too-close
)
637 (not (member header names
)))
638 (error "supplied header \"%S\" is suspiciously close to \"%S\""
640 (message "No suspicious header arguments found.")))
643 (defun org-babel-insert-header-arg ()
644 "Insert a header argument selecting from lists of common args and values."
646 (let* ((lang (car (org-babel-get-src-block-info 'light
)))
647 (lang-headers (intern (concat "org-babel-header-arg-names:" lang
)))
648 (headers (append (if (boundp lang-headers
)
649 (mapcar (lambda (h) (cons h
:any
))
652 org-babel-common-header-args-w-values
))
653 (arg (org-icompleting-read
656 (lambda (header-spec) (symbol-name (car header-spec
)))
659 (let ((vals (cdr (assoc (intern arg
) headers
))))
665 (read-from-minibuffer "value: "))
669 (let ((arg (org-icompleting-read
671 (cons "default" (mapcar #'symbol-name group
)))))
672 (if (and arg
(not (string= "default" arg
)))
678 (defun org-babel-load-in-session (&optional arg info
)
679 "Load the body of the current source-code block.
680 Evaluate the header arguments for the source block before
681 entering the session. After loading the body this pops open the
684 (let* ((info (or info
(org-babel-get-src-block-info)))
686 (params (nth 2 info
))
687 (body (setf (nth 1 info
)
688 (if (org-babel-noweb-p params
:eval
)
689 (org-babel-expand-noweb-references info
)
691 (session (cdr (assoc :session params
)))
692 (dir (cdr (assoc :dir params
)))
694 (or (and dir
(file-name-as-directory dir
)) default-directory
))
695 (cmd (intern (concat "org-babel-load-session:" lang
))))
696 (unless (fboundp cmd
)
697 (error "No org-babel-load-session function for %s!" lang
))
698 (pop-to-buffer (funcall cmd session body params
))
702 (defun org-babel-initiate-session (&optional arg info
)
703 "Initiate session for current code block.
704 If called with a prefix argument then resolve any variable
705 references in the header arguments and assign these variables in
706 the session. Copy the body of the code block to the kill ring."
708 (let* ((info (or info
(org-babel-get-src-block-info (not arg
))))
711 (params (nth 2 info
))
712 (session (cdr (assoc :session params
)))
713 (dir (cdr (assoc :dir params
)))
715 (or (and dir
(file-name-as-directory dir
)) default-directory
))
716 (init-cmd (intern (format "org-babel-%s-initiate-session" lang
)))
717 (prep-cmd (intern (concat "org-babel-prep-session:" lang
))))
718 (if (and (stringp session
) (string= session
"none"))
719 (error "This block is not using a session!"))
720 (unless (fboundp init-cmd
)
721 (error "No org-babel-initiate-session function for %s!" lang
))
722 (with-temp-buffer (insert (org-babel-trim body
))
723 (copy-region-as-kill (point-min) (point-max)))
725 (unless (fboundp prep-cmd
)
726 (error "No org-babel-prep-session function for %s!" lang
))
727 (funcall prep-cmd session params
))
728 (funcall init-cmd session params
)))
731 (defun org-babel-switch-to-session (&optional arg info
)
732 "Switch to the session of the current code block.
733 Uses `org-babel-initiate-session' to start the session. If called
734 with a prefix argument then this is passed on to
735 `org-babel-initiate-session'."
737 (pop-to-buffer (org-babel-initiate-session arg info
))
740 (defalias 'org-babel-pop-to-session
'org-babel-switch-to-session
)
743 (defun org-babel-switch-to-session-with-code (&optional arg info
)
744 "Switch to code buffer and display session."
748 (let ((other-window-buffer (window-buffer (next-window))))
749 (set-window-buffer (next-window) (current-buffer))
750 (set-window-buffer (selected-window) other-window-buffer
))
752 (let ((info (org-babel-get-src-block-info))
753 (org-src-window-setup 'reorganize-frame
))
755 (org-babel-switch-to-session arg info
))
759 (defmacro org-babel-do-in-edit-buffer
(&rest body
)
760 "Evaluate BODY in edit buffer if there is a code block at point.
761 Return t if a code block was found at point, nil otherwise."
762 `(let ((org-src-window-setup 'switch-invisibly
))
763 (when (and (org-babel-where-is-src-block-head)
764 (org-edit-src-code nil nil nil
))
765 (unwind-protect (progn ,@body
)
766 (if (org-bound-and-true-p org-edit-src-from-org-mode
)
767 (org-edit-src-exit)))
769 (def-edebug-spec org-babel-do-in-edit-buffer
(body))
771 (defun org-babel-do-key-sequence-in-edit-buffer (key)
772 "Read key sequence and execute the command in edit buffer.
773 Enter a key sequence to be executed in the language major-mode
774 edit buffer. For example, TAB will alter the contents of the
775 Org-mode code block according to the effect of TAB in the
776 language major-mode buffer. For languages that support
777 interactive sessions, this can be used to send code from the Org
778 buffer to the session for evaluation using the native major-mode
779 evaluation mechanisms."
780 (interactive "kEnter key-sequence to execute in edit buffer: ")
781 (org-babel-do-in-edit-buffer
783 (key-binding (or key
(read-key-sequence nil
))))))
785 (defvar org-bracket-link-regexp
)
787 (defun org-babel-open-src-block-result (&optional re-run
)
788 "If `point' is on a src block then open the results of the
789 source code block, otherwise return nil. With optional prefix
790 argument RE-RUN the source-code block is evaluated even if
791 results already exist."
793 (let ((info (org-babel-get-src-block-info)))
796 ;; go to the results, if there aren't any then run the block
797 (goto-char (or (and (not re-run
) (org-babel-where-is-src-block-result))
798 (progn (org-babel-execute-src-block)
799 (org-babel-where-is-src-block-result))))
801 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
803 (if (looking-at org-bracket-link-regexp
)
806 (let ((r (org-babel-format-result
807 (org-babel-read-result) (cdr (assoc :sep
(nth 2 info
))))))
808 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
809 (delete-region (point-min) (point-max))
814 (defmacro org-babel-map-src-blocks
(file &rest body
)
815 "Evaluate BODY forms on each source-block in FILE.
816 If FILE is nil evaluate BODY forms on source blocks in current
817 buffer. During evaluation of BODY the following local variables
818 are set relative to the currently matched code block.
820 full-block ------- string holding the entirety of the code block
821 beg-block -------- point at the beginning of the code block
822 end-block -------- point at the end of the matched code block
823 lang ------------- string holding the language of the code block
824 beg-lang --------- point at the beginning of the lang
825 end-lang --------- point at the end of the lang
826 switches --------- string holding the switches
827 beg-switches ----- point at the beginning of the switches
828 end-switches ----- point at the end of the switches
829 header-args ------ string holding the header-args
830 beg-header-args -- point at the beginning of the header-args
831 end-header-args -- point at the end of the header-args
832 body ------------- string holding the body of the code block
833 beg-body --------- point at the beginning of the body
834 end-body --------- point at the end of the body"
836 (let ((tempvar (make-symbol "file")))
837 `(let* ((,tempvar
,file
)
838 (visited-p (or (null ,tempvar
)
839 (get-file-buffer (expand-file-name ,tempvar
))))
840 (point (point)) to-be-removed
)
841 (save-window-excursion
842 (when ,tempvar
(find-file ,tempvar
))
843 (setq to-be-removed
(current-buffer))
844 (goto-char (point-min))
845 (while (re-search-forward org-babel-src-block-regexp nil t
)
846 (goto-char (match-beginning 0))
847 (let ((full-block (match-string 0))
848 (beg-block (match-beginning 0))
849 (end-block (match-end 0))
850 (lang (match-string 2))
851 (beg-lang (match-beginning 2))
852 (end-lang (match-end 2))
853 (switches (match-string 3))
854 (beg-switches (match-beginning 3))
855 (end-switches (match-end 3))
856 (header-args (match-string 4))
857 (beg-header-args (match-beginning 4))
858 (end-header-args (match-end 4))
859 (body (match-string 5))
860 (beg-body (match-beginning 5))
861 (end-body (match-end 5)))
863 (goto-char end-block
))))
864 (unless visited-p
(kill-buffer to-be-removed
))
866 (def-edebug-spec org-babel-map-src-blocks
(form body
))
869 (defmacro org-babel-map-inline-src-blocks
(file &rest body
)
870 "Evaluate BODY forms on each inline source-block in FILE.
871 If FILE is nil evaluate BODY forms on source blocks in current
874 (let ((tempvar (make-symbol "file")))
875 `(let* ((,tempvar
,file
)
876 (visited-p (or (null ,tempvar
)
877 (get-file-buffer (expand-file-name ,tempvar
))))
878 (point (point)) to-be-removed
)
879 (save-window-excursion
880 (when ,tempvar
(find-file ,tempvar
))
881 (setq to-be-removed
(current-buffer))
882 (goto-char (point-min))
883 (while (re-search-forward org-babel-inline-src-block-regexp nil t
)
884 (goto-char (match-beginning 1))
885 (save-match-data ,@body
)
886 (goto-char (match-end 0))))
887 (unless visited-p
(kill-buffer to-be-removed
))
889 (def-edebug-spec org-babel-map-inline-src-blocks
(form body
))
891 (defvar org-babel-lob-one-liner-regexp
)
893 (defmacro org-babel-map-call-lines
(file &rest body
)
894 "Evaluate BODY forms on each call line in FILE.
895 If FILE is nil evaluate BODY forms on source blocks in current
898 (let ((tempvar (make-symbol "file")))
899 `(let* ((,tempvar
,file
)
900 (visited-p (or (null ,tempvar
)
901 (get-file-buffer (expand-file-name ,tempvar
))))
902 (point (point)) to-be-removed
)
903 (save-window-excursion
904 (when ,tempvar
(find-file ,tempvar
))
905 (setq to-be-removed
(current-buffer))
906 (goto-char (point-min))
907 (while (re-search-forward org-babel-lob-one-liner-regexp nil t
)
908 (goto-char (match-beginning 1))
909 (save-match-data ,@body
)
910 (goto-char (match-end 0))))
911 (unless visited-p
(kill-buffer to-be-removed
))
913 (def-edebug-spec org-babel-map-call-lines
(form body
))
916 (defmacro org-babel-map-executables
(file &rest body
)
918 (let ((tempvar (make-symbol "file"))
919 (rx (make-symbol "rx")))
920 `(let* ((,tempvar
,file
)
921 (,rx
(concat "\\(" org-babel-src-block-regexp
922 "\\|" org-babel-inline-src-block-regexp
923 "\\|" org-babel-lob-one-liner-regexp
"\\)"))
924 (visited-p (or (null ,tempvar
)
925 (get-file-buffer (expand-file-name ,tempvar
))))
926 (point (point)) to-be-removed
)
927 (save-window-excursion
928 (when ,tempvar
(find-file ,tempvar
))
929 (setq to-be-removed
(current-buffer))
930 (goto-char (point-min))
931 (while (re-search-forward ,rx nil t
)
932 (goto-char (match-beginning 1))
933 (when (looking-at org-babel-inline-src-block-regexp
)(forward-char 1))
934 (save-match-data ,@body
)
935 (goto-char (match-end 0))))
936 (unless visited-p
(kill-buffer to-be-removed
))
938 (def-edebug-spec org-babel-map-executables
(form body
))
941 (defun org-babel-execute-buffer (&optional arg
)
942 "Execute source code blocks in a buffer.
943 Call `org-babel-execute-src-block' on every source block in
946 (org-babel-eval-wipe-error-buffer)
947 (org-save-outline-visibility t
948 (org-babel-map-executables nil
949 (if (looking-at org-babel-lob-one-liner-regexp
)
950 (org-babel-lob-execute-maybe)
951 (org-babel-execute-src-block arg
)))))
954 (defun org-babel-execute-subtree (&optional arg
)
955 "Execute source code blocks in a subtree.
956 Call `org-babel-execute-src-block' on every source block in
957 the current subtree."
961 (org-narrow-to-subtree)
962 (org-babel-execute-buffer arg
)
966 (defun org-babel-sha1-hash (&optional info
)
967 "Generate an sha1 hash based on the value of info."
969 (let ((print-level nil
)
970 (info (or info
(org-babel-get-src-block-info))))
972 (sort (copy-sequence (nth 2 info
))
973 (lambda (a b
) (string< (car a
) (car b
)))))
975 (dolist (p '("replace" "silent" "append" "prepend"))
976 (setq lst
(remove p lst
)))
979 (let ((v (if (and (listp (cdr arg
)) (null (cddr arg
)))
980 (copy-sequence (cdr arg
))
982 (when (and v
(not (and (sequencep v
)
986 ((and (listp v
) ; lists are sorted
987 (member (car arg
) '(:result-params
)))
988 (sort (rm v
) #'string
<))
989 ((and (stringp v
) ; strings are sorted
990 (member (car arg
) '(:results
:exports
)))
991 (mapconcat #'identity
(sort (rm (split-string v
))
995 (when (org-called-interactively-p 'interactive
) (message hash
)) hash
)
996 (let ((it (format "%s-%s"
999 (delq nil
(mapcar (lambda (arg)
1000 (let ((normalized (norm arg
)))
1002 (format "%S" normalized
))))
1007 (defun org-babel-current-result-hash ()
1008 "Return the in-buffer hash associated with INFO."
1009 (org-babel-where-is-src-block-result)
1010 (org-babel-clean-text-properties (match-string 3)))
1012 (defun org-babel-hide-hash ()
1013 "Hide the hash in the current results line.
1014 Only the initial `org-babel-hash-show' characters of the hash
1015 will remain visible."
1016 (add-to-invisibility-spec '(org-babel-hide-hash . t
))
1018 (when (and (re-search-forward org-babel-result-regexp nil t
)
1020 (let* ((start (match-beginning 3))
1021 (hide-start (+ org-babel-hash-show start
))
1023 (hash (match-string 3))
1025 (setq ov1
(make-overlay start hide-start
))
1026 (setq ov2
(make-overlay hide-start end
))
1027 (overlay-put ov2
'invisible
'org-babel-hide-hash
)
1028 (overlay-put ov1
'babel-hash hash
)))))
1030 (defun org-babel-hide-all-hashes ()
1031 "Hide the hash in the current buffer.
1032 Only the initial `org-babel-hash-show' characters of each hash
1033 will remain visible. This function should be called as part of
1034 the `org-mode-hook'."
1036 (while (re-search-forward org-babel-result-regexp nil t
)
1037 (goto-char (match-beginning 0))
1038 (org-babel-hide-hash)
1039 (goto-char (match-end 0)))))
1040 (add-hook 'org-mode-hook
'org-babel-hide-all-hashes
)
1042 (defun org-babel-hash-at-point (&optional point
)
1043 "Return the value of the hash at POINT.
1044 The hash is also added as the last element of the kill ring.
1045 This can be called with C-c C-c."
1047 (let ((hash (car (delq nil
(mapcar
1048 (lambda (ol) (overlay-get ol
'babel-hash
))
1049 (overlays-at (or point
(point))))))))
1050 (when hash
(kill-new hash
) (message hash
))))
1051 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-hash-at-point
)
1053 (defun org-babel-result-hide-spec ()
1054 "Hide portions of results lines.
1055 Add `org-babel-hide-result' as an invisibility spec for hiding
1056 portions of results lines."
1057 (add-to-invisibility-spec '(org-babel-hide-result . t
)))
1058 (add-hook 'org-mode-hook
'org-babel-result-hide-spec
)
1060 (defvar org-babel-hide-result-overlays nil
1061 "Overlays hiding results.")
1063 (defun org-babel-result-hide-all ()
1064 "Fold all results in the current buffer."
1066 (org-babel-show-result-all)
1068 (while (re-search-forward org-babel-result-regexp nil t
)
1069 (save-excursion (goto-char (match-beginning 0))
1070 (org-babel-hide-result-toggle-maybe)))))
1072 (defun org-babel-show-result-all ()
1073 "Unfold all results in the current buffer."
1074 (mapc 'delete-overlay org-babel-hide-result-overlays
)
1075 (setq org-babel-hide-result-overlays nil
))
1078 (defun org-babel-hide-result-toggle-maybe ()
1079 "Toggle visibility of result at point."
1081 (let ((case-fold-search t
))
1083 (beginning-of-line 1)
1084 (looking-at org-babel-result-regexp
))
1085 (progn (org-babel-hide-result-toggle)
1086 t
) ;; to signal that we took action
1087 nil
))) ;; to signal that we did not
1089 (defun org-babel-hide-result-toggle (&optional force
)
1090 "Toggle the visibility of the current result."
1094 (if (re-search-forward org-babel-result-regexp nil t
)
1095 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
1097 (while (looking-at org-babel-multi-line-header-regexp
)
1099 (goto-char (- (org-babel-result-end) 1)) (point)))
1101 (if (memq t
(mapcar (lambda (overlay)
1102 (eq (overlay-get overlay
'invisible
)
1103 'org-babel-hide-result
))
1104 (overlays-at start
)))
1105 (if (or (not force
) (eq force
'off
))
1107 (when (member ov org-babel-hide-result-overlays
)
1108 (setq org-babel-hide-result-overlays
1109 (delq ov org-babel-hide-result-overlays
)))
1110 (when (eq (overlay-get ov
'invisible
)
1111 'org-babel-hide-result
)
1112 (delete-overlay ov
)))
1113 (overlays-at start
)))
1114 (setq ov
(make-overlay start end
))
1115 (overlay-put ov
'invisible
'org-babel-hide-result
)
1116 ;; make the block accessible to isearch
1118 ov
'isearch-open-invisible
1120 (when (member ov org-babel-hide-result-overlays
)
1121 (setq org-babel-hide-result-overlays
1122 (delq ov org-babel-hide-result-overlays
)))
1123 (when (eq (overlay-get ov
'invisible
)
1124 'org-babel-hide-result
)
1125 (delete-overlay ov
))))
1126 (push ov org-babel-hide-result-overlays
)))
1127 (error "Not looking at a result line"))))
1129 ;; org-tab-after-check-for-cycling-hook
1130 (add-hook 'org-tab-first-hook
'org-babel-hide-result-toggle-maybe
)
1131 ;; Remove overlays when changing major mode
1132 (add-hook 'org-mode-hook
1133 (lambda () (org-add-hook 'change-major-mode-hook
1134 'org-babel-show-result-all
'append
'local
)))
1136 (defvar org-file-properties
)
1137 (defun org-babel-params-from-properties (&optional lang
)
1138 "Retrieve parameters specified as properties.
1139 Return an association list of any source block params which
1140 may be specified in the properties of the current outline entry."
1143 (org-babel-parse-multiple-vars
1146 (lambda (header-arg)
1147 (and (setq val
(org-entry-get (point) header-arg t
))
1148 (cons (intern (concat ":" header-arg
))
1149 (org-babel-read val
))))
1153 org-babel-header-arg-names
1155 (setq sym
(intern (concat "org-babel-header-arg-names:"
1157 (and (boundp sym
) (eval sym
)))))))))))
1159 (defvar org-src-preserve-indentation
)
1160 (defun org-babel-parse-src-block-match ()
1161 "Parse the results from a match of the `org-babel-src-block-regexp'."
1162 (let* ((block-indentation (length (match-string 1)))
1163 (lang (org-babel-clean-text-properties (match-string 2)))
1164 (lang-headers (intern (concat "org-babel-default-header-args:" lang
)))
1165 (switches (match-string 3))
1166 (body (org-babel-clean-text-properties
1167 (let* ((body (match-string 5))
1168 (sub-length (- (length body
) 1)))
1169 (if (and (> sub-length
0)
1170 (string= "\n" (substring body sub-length
)))
1171 (substring body
0 sub-length
)
1173 (preserve-indentation (or org-src-preserve-indentation
1174 (string-match "-i\\>" switches
))))
1176 ;; get block body less properties, protective commas, and indentation
1179 (insert (org-babel-strip-protective-commas body
))
1180 (unless preserve-indentation
(org-do-remove-indentation))
1182 (org-babel-merge-params
1183 org-babel-default-header-args
1184 (org-babel-params-from-properties lang
)
1185 (if (boundp lang-headers
) (eval lang-headers
) nil
)
1186 (org-babel-parse-header-arguments
1187 (org-babel-clean-text-properties (or (match-string 4) ""))))
1189 block-indentation
)))
1191 (defun org-babel-parse-inline-src-block-match ()
1192 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
1193 (let* ((lang (org-babel-clean-text-properties (match-string 2)))
1194 (lang-headers (intern (concat "org-babel-default-header-args:" lang
))))
1196 (org-babel-strip-protective-commas
1197 (org-babel-clean-text-properties (match-string 5)))
1198 (org-babel-merge-params
1199 org-babel-default-inline-header-args
1200 (org-babel-params-from-properties lang
)
1201 (if (boundp lang-headers
) (eval lang-headers
) nil
)
1202 (org-babel-parse-header-arguments
1203 (org-babel-clean-text-properties (or (match-string 4) "")))))))
1205 (defun org-babel-balanced-split (string alts
)
1206 "Split STRING on instances of ALTS.
1207 ALTS is a cons of two character options where each option may be
1208 either the numeric code of a single character or a list of
1209 character alternatives. For example to split on balanced
1210 instances of \"[ \t]:\" set ALTS to '((32 9) . 58)."
1211 (flet ((matches (ch spec
) (if (listp spec
) (member ch spec
) (equal spec ch
)))
1214 (and (matches ch
(cdr alts
))
1215 (matches last
(car alts
)))
1216 (matches ch alts
))))
1217 (let ((balance 0) (quote nil
) (partial nil
) (lst nil
) (last 0))
1218 (mapc (lambda (ch) ; split on [], (), "" balanced instances of [ \t]:
1219 (setq balance
(+ balance
1220 (cond ((or (equal 91 ch
) (equal 40 ch
)) 1)
1221 ((or (equal 93 ch
) (equal 41 ch
)) -
1)
1223 (when (and (equal 34 ch
) (not (equal 92 last
)))
1224 (setq quote
(not quote
)))
1225 (setq partial
(cons ch partial
))
1226 (when (and (= balance
0) (not quote
) (matched ch last
))
1227 (setq lst
(cons (apply #'string
(nreverse
1234 (string-to-list string
))
1235 (nreverse (cons (apply #'string
(nreverse partial
)) lst
)))))
1237 (defun org-babel-join-splits-near-ch (ch list
)
1238 "Join splits where \"=\" is on either end of the split."
1239 (flet ((last= (str) (= ch
(aref str
(1- (length str
)))))
1240 (first= (str) (= ch
(aref str
0))))
1242 (org-reduce (lambda (acc el
)
1243 (let ((head (car acc
)))
1244 (if (and head
(or (last= head
) (first= el
)))
1245 (cons (concat head el
) (cdr acc
))
1247 list
:initial-value nil
))))
1249 (defun org-babel-parse-header-arguments (arg-string)
1250 "Parse a string of header arguments returning an alist."
1251 (when (> (length arg-string
) 0)
1252 (org-babel-parse-multiple-vars
1257 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1259 (cons (intern (match-string 1 arg
))
1260 (org-babel-read (org-babel-chomp (match-string 2 arg
))))
1261 (cons (intern (org-babel-chomp arg
)) nil
)))
1263 (cons (car raw
) (mapcar (lambda (r) (concat ":" r
)) (cdr raw
))))
1264 (org-babel-balanced-split arg-string
'((32 9) .
58))))))))
1266 (defun org-babel-parse-multiple-vars (header-arguments)
1267 "Expand multiple variable assignments behind a single :var keyword.
1269 This allows expression of multiple variables with one :var as
1272 #+PROPERTY: var foo=1, bar=2"
1274 (mapc (lambda (pair)
1275 (if (eq (car pair
) :var
)
1276 (mapcar (lambda (v) (push (cons :var
(org-babel-trim v
)) results
))
1277 (org-babel-join-splits-near-ch
1278 61 (org-babel-balanced-split (cdr pair
) 32)))
1279 (push pair results
)))
1281 (nreverse results
)))
1283 (defun org-babel-process-params (params)
1284 "Expand variables in PARAMS and add summary parameters."
1285 (let* ((processed-vars (mapcar (lambda (el)
1286 (if (consp (cdr el
))
1288 (org-babel-ref-parse (cdr el
))))
1289 (org-babel-get-header params
:var
)))
1290 (vars-and-names (if (and (assoc :colname-names params
)
1291 (assoc :rowname-names params
))
1292 (list processed-vars
)
1293 (org-babel-disassemble-tables
1295 (cdr (assoc :hlines params
))
1296 (cdr (assoc :colnames params
))
1297 (cdr (assoc :rownames params
)))))
1298 (raw-result (or (cdr (assoc :results params
)) ""))
1299 (result-params (append
1300 (split-string (if (stringp raw-result
)
1303 (cdr (assoc :result-params params
)))))
1305 (mapcar (lambda (var) (cons :var var
)) (car vars-and-names
))
1307 (cons :colname-names
(or (cdr (assoc :colname-names params
))
1308 (cadr vars-and-names
)))
1309 (cons :rowname-names
(or (cdr (assoc :rowname-names params
))
1310 (caddr vars-and-names
)))
1311 (cons :result-params result-params
)
1312 (cons :result-type
(cond ((member "output" result-params
) 'output
)
1313 ((member "value" result-params
) 'value
)
1315 (org-babel-get-header params
:var
'other
))))
1317 ;; row and column names
1318 (defun org-babel-del-hlines (table)
1319 "Remove all 'hlines from TABLE."
1320 (remove 'hline table
))
1322 (defun org-babel-get-colnames (table)
1323 "Return the column names of TABLE.
1324 Return a cons cell, the `car' of which contains the TABLE less
1325 colnames, and the `cdr' of which contains a list of the column
1327 (if (equal 'hline
(nth 1 table
))
1328 (cons (cddr table
) (car table
))
1329 (cons (cdr table
) (car table
))))
1331 (defun org-babel-get-rownames (table)
1332 "Return the row names of TABLE.
1333 Return a cons cell, the `car' of which contains the TABLE less
1334 colnames, and the `cdr' of which contains a list of the column
1335 names. Note: this function removes any hlines in TABLE."
1336 (flet ((trans (table) (apply #'mapcar
* #'list table
)))
1337 (let* ((width (apply 'max
1338 (mapcar (lambda (el) (if (listp el
) (length el
) 0)) table
)))
1339 (table (trans (mapcar (lambda (row)
1340 (if (not (equal row
'hline
))
1344 (setq row
(cons 'hline row
)))
1347 (cons (mapcar (lambda (row) (if (equal (car row
) 'hline
) 'hline row
))
1348 (trans (cdr table
)))
1349 (remove 'hline
(car table
))))))
1351 (defun org-babel-put-colnames (table colnames
)
1352 "Add COLNAMES to TABLE if they exist."
1353 (if colnames
(apply 'list colnames
'hline table
) table
))
1355 (defun org-babel-put-rownames (table rownames
)
1356 "Add ROWNAMES to TABLE if they exist."
1358 (mapcar (lambda (row)
1360 (cons (or (pop rownames
) "") row
)
1364 (defun org-babel-pick-name (names selector
)
1365 "Select one out of an alist of row or column names.
1366 SELECTOR can be either a list of names in which case those names
1367 will be returned directly, or an index into the list NAMES in
1368 which case the indexed names will be return."
1369 (if (listp selector
)
1372 (if (and selector
(symbolp selector
) (not (equal t selector
)))
1373 (cdr (assoc selector names
))
1374 (if (integerp selector
)
1375 (nth (- selector
1) names
)
1376 (cdr (car (last names
))))))))
1378 (defun org-babel-disassemble-tables (vars hlines colnames rownames
)
1379 "Parse tables for further processing.
1380 Process the variables in VARS according to the HLINES,
1381 ROWNAMES and COLNAMES header arguments. Return a list consisting
1382 of the vars, cnames and rnames."
1383 (let (cnames rnames
)
1387 (when (listp (cdr var
))
1388 (when (and (not (equal colnames
"no"))
1389 (or colnames
(and (equal (nth 1 (cdr var
)) 'hline
)
1390 (not (member 'hline
(cddr (cdr var
)))))))
1391 (let ((both (org-babel-get-colnames (cdr var
))))
1392 (setq cnames
(cons (cons (car var
) (cdr both
))
1394 (setq var
(cons (car var
) (car both
)))))
1395 (when (and rownames
(not (equal rownames
"no")))
1396 (let ((both (org-babel-get-rownames (cdr var
))))
1397 (setq rnames
(cons (cons (car var
) (cdr both
))
1399 (setq var
(cons (car var
) (car both
)))))
1400 (when (and hlines
(not (equal hlines
"yes")))
1401 (setq var
(cons (car var
) (org-babel-del-hlines (cdr var
))))))
1404 (reverse cnames
) (reverse rnames
))))
1406 (defun org-babel-reassemble-table (table colnames rownames
)
1407 "Add column and row names to a table.
1408 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1409 to the table for reinsertion to org-mode."
1412 (if (and colnames
(listp (car table
)) (= (length (car table
))
1414 (org-babel-put-colnames table colnames
) table
))
1415 (if (and rownames
(= (length table
) (length rownames
)))
1416 (org-babel-put-rownames table rownames
) table
))
1419 (defun org-babel-where-is-src-block-head ()
1420 "Find where the current source block begins.
1421 Return the point at the beginning of the current source
1422 block. Specifically at the beginning of the #+BEGIN_SRC line.
1423 If the point is not on a source block then return nil."
1424 (let ((initial (point)) top bottom
)
1426 (save-excursion ;; on a source name line or a #+header line
1427 (beginning-of-line 1)
1428 (and (or (looking-at org-babel-src-name-regexp
)
1429 (looking-at org-babel-multi-line-header-regexp
))
1431 (while (and (forward-line 1)
1432 (looking-at org-babel-multi-line-header-regexp
)))
1433 (looking-at org-babel-src-block-regexp
))
1435 (save-excursion ;; on a #+begin_src line
1436 (beginning-of-line 1)
1437 (and (looking-at org-babel-src-block-regexp
)
1439 (save-excursion ;; inside a src block
1441 (re-search-backward "^[ \t]*#\\+begin_src" nil t
) (setq top
(point))
1442 (re-search-forward "^[ \t]*#\\+end_src" nil t
) (setq bottom
(point))
1443 (< top initial
) (< initial bottom
)
1444 (progn (goto-char top
) (beginning-of-line 1)
1445 (looking-at org-babel-src-block-regexp
))
1449 (defun org-babel-goto-src-block-head ()
1450 "Go to the beginning of the current code block."
1453 (if head
(goto-char head
) (error "not currently in a code block")))
1454 (org-babel-where-is-src-block-head)))
1457 (defun org-babel-goto-named-src-block (name)
1458 "Go to a named source-code block."
1460 (let ((completion-ignore-case t
))
1461 (list (org-icompleting-read "source-block name: "
1462 (org-babel-src-block-names) nil t
))))
1463 (let ((point (org-babel-find-named-block name
)))
1465 ;; taken from `org-open-at-point'
1466 (progn (goto-char point
) (org-show-context))
1467 (message "source-code block '%s' not found in this buffer" name
))))
1469 (defun org-babel-find-named-block (name)
1470 "Find a named source-code block.
1471 Return the location of the source block identified by source
1472 NAME, or nil if no such block exists. Set match data according to
1473 org-babel-named-src-block-regexp."
1475 (let ((case-fold-search t
)
1476 (regexp (org-babel-named-src-block-regexp-for-name name
)) msg
)
1477 (goto-char (point-min))
1478 (when (or (re-search-forward regexp nil t
)
1479 (re-search-backward regexp nil t
))
1480 (match-beginning 0)))))
1482 (defun org-babel-src-block-names (&optional file
)
1483 "Returns the names of source blocks in FILE or the current buffer."
1485 (when file
(find-file file
)) (goto-char (point-min))
1487 (while (re-search-forward org-babel-src-name-w-name-regexp nil t
)
1488 (setq names
(cons (match-string 3) names
)))
1492 (defun org-babel-goto-named-result (name)
1493 "Go to a named result."
1495 (let ((completion-ignore-case t
))
1496 (list (org-icompleting-read "source-block name: "
1497 (org-babel-result-names) nil t
))))
1498 (let ((point (org-babel-find-named-result name
)))
1500 ;; taken from `org-open-at-point'
1501 (progn (goto-char point
) (org-show-context))
1502 (message "result '%s' not found in this buffer" name
))))
1504 (defun org-babel-find-named-result (name &optional point
)
1505 "Find a named result.
1506 Return the location of the result named NAME in the current
1507 buffer or nil if no such result exists."
1509 (goto-char (or point
(point-min)))
1510 (catch 'is-a-code-block
1511 (when (re-search-forward
1512 (concat org-babel-result-regexp
1513 "[ \t]" (regexp-quote name
) "[ \t\n\f\v\r]") nil t
)
1514 (when (and (string= "name" (downcase (match-string 1)))
1515 (or (looking-at org-babel-src-block-regexp
)
1516 (looking-at org-babel-multi-line-header-regexp
)))
1517 (throw 'is-a-code-block
(org-babel-find-named-result name
(point))))
1518 (beginning-of-line 0) (point)))))
1520 (defun org-babel-result-names (&optional file
)
1521 "Returns the names of results in FILE or the current buffer."
1523 (when file
(find-file file
)) (goto-char (point-min))
1525 (while (re-search-forward org-babel-result-w-name-regexp nil t
)
1526 (setq names
(cons (match-string 4) names
)))
1530 (defun org-babel-next-src-block (&optional arg
)
1531 "Jump to the next source block.
1532 With optional prefix argument ARG, jump forward ARG many source blocks."
1534 (when (looking-at org-babel-src-block-regexp
) (forward-char 1))
1536 (re-search-forward org-babel-src-block-regexp nil nil
(or arg
1))
1537 (error (error "No further code blocks")))
1538 (goto-char (match-beginning 0)) (org-show-context))
1541 (defun org-babel-previous-src-block (&optional arg
)
1542 "Jump to the previous source block.
1543 With optional prefix argument ARG, jump backward ARG many source blocks."
1546 (re-search-backward org-babel-src-block-regexp nil nil
(or arg
1))
1547 (error (error "No previous code blocks")))
1548 (goto-char (match-beginning 0)) (org-show-context))
1550 (defvar org-babel-load-languages
)
1553 (defun org-babel-mark-block ()
1554 "Mark current src block"
1560 (looking-at org-babel-src-block-regexp
))
1561 (push-mark (match-end 5) nil t
)
1562 (goto-char (match-beginning 5))))
1563 (org-babel-where-is-src-block-head)))
1565 (defun org-babel-demarcate-block (&optional arg
)
1566 "Wrap or split the code in the region or on the point.
1567 When called from inside of a code block the current block is
1568 split. When called from outside of a code block a new code block
1569 is created. In both cases if the region is demarcated and if the
1570 region is not active then the point is demarcated."
1572 (let ((info (org-babel-get-src-block-info 'light
))
1573 (headers (progn (org-babel-where-is-src-block-head)
1575 (stars (concat (make-string (or (org-current-level) 1) ?
*) " ")))
1581 (let ((lang (nth 0 info
))
1582 (indent (make-string (nth 5 info
) ?
)))
1583 (when (string-match "^[[:space:]]*$"
1584 (buffer-substring (point-at-bol)
1586 (delete-region (point-at-bol) (point-at-eol)))
1588 (if (looking-at "^") "" "\n")
1589 indent
"#+end_src\n"
1590 (if arg stars indent
) "\n"
1591 indent
"#+begin_src " lang
1592 (if (> (length headers
) 1)
1593 (concat " " headers
) headers
)
1594 (if (looking-at "[\n\r]")
1596 (concat "\n" (make-string (current-column) ?
)))))))
1597 (move-end-of-line 2))
1598 (sort (if (region-active-p) (list (mark) (point)) (list (point))) #'>))
1599 (let ((start (point))
1600 (lang (org-icompleting-read "Lang: "
1601 (mapcar (lambda (el) (symbol-name (car el
)))
1602 org-babel-load-languages
)))
1603 (body (delete-and-extract-region
1604 (if (region-active-p) (mark) (point)) (point))))
1605 (insert (concat (if (looking-at "^") "" "\n")
1606 (if arg
(concat stars
"\n") "")
1607 "#+begin_src " lang
"\n"
1609 (if (or (= (length body
) 0)
1610 (string-match "[\r\n]$" body
)) "" "\n")
1612 (goto-char start
) (move-end-of-line 1)))))
1614 (defvar org-babel-lob-one-liner-regexp
)
1615 (defun org-babel-where-is-src-block-result (&optional insert info hash indent
)
1616 "Find where the current source block results begin.
1617 Return the point at the beginning of the result of the current
1618 source block. Specifically at the beginning of the results line.
1619 If no result exists for this block then create a results line
1620 following the source block."
1622 (let* ((on-lob-line (save-excursion
1623 (beginning-of-line 1)
1624 (looking-at org-babel-lob-one-liner-regexp
)))
1625 (inlinep (when (org-babel-get-inline-src-block-matches)
1627 (name (if on-lob-line
1628 (nth 0 (org-babel-lob-get-info))
1629 (nth 4 (or info
(org-babel-get-src-block-info 'light
)))))
1630 (head (unless on-lob-line
(org-babel-where-is-src-block-head)))
1632 (when head
(goto-char head
))
1634 found
;; was there a result (before we potentially insert one)
1639 ;; - return t if it is found, else return nil
1640 ;; - if it does not need to be rebuilt, then don't set end
1641 ;; - if it does need to be rebuilt then do set end
1642 name
(setq beg
(org-babel-find-named-result name
))
1644 (when (and hash
(not (string= hash
(match-string 3))))
1645 (goto-char beg
) (setq end beg
) ;; beginning of result
1647 (delete-region end
(org-babel-result-end)) nil
)))
1650 ;; - return t if it is found, else return nil
1651 ;; - if it is found, and the hash doesn't match, delete and set end
1652 (or on-lob-line
(re-search-forward "^[ \t]*#\\+end_src" nil t
))
1653 (progn (end-of-line 1)
1654 (if (eobp) (insert "\n") (forward-char 1))
1657 (progn ;; unnamed results line already exists
1658 (re-search-forward "[^ \f\t\n\r\v]" nil t
)
1659 (beginning-of-line 1)
1661 (concat org-babel-result-regexp
"\n")))
1663 ;; must remove and rebuild if hash!=old-hash
1664 (if (and hash
(not (string= hash
(match-string 3))))
1668 end
(org-babel-result-end)))
1669 (setq end nil
)))))))))
1670 (if (and insert end
)
1674 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1679 (org-number-sequence 1 indent
) "")
1681 "#+" org-babel-results-keyword
1682 (when hash
(concat "["hash
"]"))
1684 (when name
(concat " " name
)) "\n"))
1685 (unless beg
(insert "\n") (backward-char))
1686 (beginning-of-line 0)
1687 (if hash
(org-babel-hide-hash))
1691 (defvar org-block-regexp
)
1692 (defun org-babel-read-result ()
1693 "Read the result at `point' into emacs-lisp."
1694 (let ((case-fold-search t
) result-string
)
1696 ((org-at-table-p) (org-babel-read-table))
1697 ((org-at-item-p) (org-babel-read-list))
1698 ((looking-at org-bracket-link-regexp
) (org-babel-read-link))
1699 ((looking-at org-block-regexp
) (org-babel-trim (match-string 4)))
1700 ((looking-at "^[ \t]*: ")
1703 (mapconcat (lambda (line)
1704 (if (and (> (length line
) 1)
1705 (string-match "^[ \t]*: \\(.+\\)" line
))
1706 (match-string 1 line
)
1710 (point) (org-babel-result-end)) "[\r\n]+")
1712 (or (org-babel-number-p result-string
) result-string
))
1713 ((looking-at org-babel-result-regexp
)
1714 (save-excursion (forward-line 1) (org-babel-read-result))))))
1716 (defun org-babel-read-table ()
1717 "Read the table at `point' into emacs-lisp."
1718 (mapcar (lambda (row)
1719 (if (and (symbolp row
) (equal row
'hline
)) row
1720 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
)) row
)))
1721 (org-table-to-lisp)))
1723 (defun org-babel-read-list ()
1724 "Read the list at `point' into emacs-lisp."
1725 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
))
1726 (mapcar #'cadr
(cdr (org-list-parse-list)))))
1728 (defvar org-link-types-re
)
1729 (defun org-babel-read-link ()
1730 "Read the link at `point' into emacs-lisp.
1731 If the path of the link is a file path it is expanded using
1732 `expand-file-name'."
1733 (let* ((case-fold-search t
)
1734 (raw (and (looking-at org-bracket-link-regexp
)
1735 (org-babel-clean-text-properties (match-string 1))))
1736 (type (and (string-match org-link-types-re raw
)
1737 (match-string 1 raw
))))
1739 ((not type
) (expand-file-name raw
))
1740 ((string= type
"file")
1741 (and (string-match "file\\(.*\\):\\(.+\\)" raw
)
1742 (expand-file-name (match-string 2 raw
))))
1745 (defun org-babel-format-result (result &optional sep
)
1746 "Format RESULT for writing to file."
1747 (flet ((echo-res (result)
1748 (if (stringp result
) result
(format "%S" result
))))
1757 (echo-res result
))))
1759 (defun org-babel-insert-result
1760 (result &optional result-params info hash indent lang
)
1761 "Insert RESULT into the current buffer.
1762 By default RESULT is inserted after the end of the
1763 current source block. With optional argument RESULT-PARAMS
1764 controls insertion of results in the org-mode file.
1765 RESULT-PARAMS can take the following values...
1767 replace - (default option) insert results after the source block
1768 replacing any previously inserted results
1770 silent -- no results are inserted
1772 file ---- the results are interpreted as a file path, and are
1773 inserted into the buffer using the Org-mode file syntax
1775 list ---- the results are interpreted as an Org-mode list.
1777 raw ----- results are added directly to the Org-mode file. This
1778 is a good option if you code block will output org-mode
1781 wrap ---- results are added directly to the Org-mode file as with
1782 \"raw\", but are wrapped in a RESULTS drawer, allowing
1783 them to later be replaced or removed automatically.
1785 org ----- similar in effect to raw, only the results are wrapped
1786 in an org code block. Similar to the raw option, on
1787 export the results will be interpreted as org-formatted
1788 text, however by wrapping the results in an org code
1789 block they can be replaced upon re-execution of the
1792 html ---- results are added inside of a #+BEGIN_HTML block. This
1793 is a good option if you code block will output html
1796 latex --- results are added inside of a #+BEGIN_LATEX block.
1797 This is a good option if you code block will output
1798 latex formatted text.
1800 code ---- the results are extracted in the syntax of the source
1801 code of the language being evaluated and are added
1802 inside of a #+BEGIN_SRC block with the source-code
1803 language set appropriately. Note this relies on the
1804 optional LANG argument."
1805 (if (stringp result
)
1807 (setq result
(org-babel-clean-text-properties result
))
1808 (when (member "file" result-params
)
1809 (setq result
(org-babel-result-to-file result
))))
1810 (unless (listp result
) (setq result
(format "%S" result
))))
1811 (if (and result-params
(member "silent" result-params
))
1813 (message (replace-regexp-in-string "%" "%%" (format "%S" result
)))
1818 (when (or (org-babel-get-inline-src-block-matches)
1819 (org-babel-get-lob-one-liner-matches))
1820 (goto-char (match-end 0))
1821 (insert (if (listp result
) "\n" " "))
1823 (existing-result (unless inlinep
1824 (org-babel-where-is-src-block-result
1825 t info hash indent
)))
1827 (cdr (assoc :results_switches
(nth 2 info
))))
1829 (when (and (stringp result
) ; ensure results end in a newline
1831 (> (length result
) 0)
1832 (not (or (string-equal (substring result -
1) "\n")
1833 (string-equal (substring result -
1) "\r"))))
1834 (setq result
(concat result
"\n")))
1835 (if (not existing-result
)
1836 (setq beg
(or inlinep
(point)))
1837 (goto-char existing-result
)
1839 (re-search-forward "#" nil t
)
1840 (setq indent
(- (current-column) 1)))
1844 ((member "replace" result-params
)
1845 (delete-region (point) (org-babel-result-end)))
1846 ((member "append" result-params
)
1847 (goto-char (org-babel-result-end)) (setq beg
(point-marker)))
1848 ((member "prepend" result-params
)))) ; already there
1849 (setq results-switches
1850 (if results-switches
(concat " " results-switches
) ""))
1851 (flet ((wrap (start finish
)
1852 (goto-char beg
) (insert (concat start
"\n"))
1853 (goto-char end
) (insert (concat finish
"\n"))
1854 (setq end
(point-marker)))
1855 (proper-list-p (it) (and (listp it
) (null (cdr (last it
))))))
1856 ;; insert results based on type
1858 ;; do nothing for an empty result
1860 ;; insert a list if preferred
1861 ((member "list" result-params
)
1864 (org-list-to-generic
1867 (lambda (el) (list nil
(if (stringp el
) el
(format "%S" el
))))
1868 (if (listp result
) result
(list result
))))
1869 '(:splicep nil
:istart
"- " :iend
"\n")))
1871 ;; assume the result is a table if it's not a string
1872 ((proper-list-p result
)
1874 (insert (concat (orgtbl-to-orgtbl
1875 (if (or (eq 'hline
(car result
))
1876 (and (listp (car result
))
1877 (listp (cdr (car result
)))))
1878 result
(list result
))
1879 '(:fmt
(lambda (cell) (format "%s" cell
)))) "\n"))
1880 (goto-char beg
) (when (org-at-table-p) (org-table-align)))
1881 ((and (listp result
) (not (proper-list-p result
)))
1882 (insert (format "%s\n" result
)))
1883 ((member "file" result-params
)
1884 (when inlinep
(goto-char inlinep
))
1886 (t (goto-char beg
) (insert result
)))
1887 (when (proper-list-p result
) (goto-char (org-table-end)))
1888 (setq end
(point-marker))
1889 ;; possibly wrap result
1891 ((assoc :wrap
(nth 2 info
))
1892 (let ((name (or (cdr (assoc :wrap
(nth 2 info
))) "RESULTS")))
1893 (wrap (concat "#+BEGIN_" name
) (concat "#+END_" name
))))
1894 ((member "html" result-params
)
1895 (wrap "#+BEGIN_HTML" "#+END_HTML"))
1896 ((member "latex" result-params
)
1897 (wrap "#+BEGIN_LaTeX" "#+END_LaTeX"))
1898 ((member "code" result-params
)
1899 (wrap (format "#+BEGIN_SRC %s%s" (or lang
"none") results-switches
)
1901 ((member "org" result-params
)
1902 (wrap "#+BEGIN_ORG" "#+END_ORG"))
1903 ((member "raw" result-params
)
1904 (goto-char beg
) (if (org-at-table-p) (org-cycle)))
1905 ((member "wrap" result-params
)
1906 (wrap ":RESULTS:" ":END:"))
1907 ((and (not (proper-list-p result
))
1908 (not (member "file" result-params
)))
1909 (org-babel-examplize-region beg end results-switches
)
1910 (setq end
(point)))))
1911 ;; possibly indent the results to match the #+results line
1912 (when (and (not inlinep
) (numberp indent
) indent
(> indent
0)
1913 ;; in this case `table-align' does the work for us
1914 (not (and (listp result
)
1915 (member "append" result-params
))))
1916 (indent-rigidly beg end indent
))))
1918 (if (member "value" result-params
)
1919 (message "Code block returned no value.")
1920 (message "Code block produced no output."))
1921 (message "Code block evaluation complete."))))
1923 (defun org-babel-remove-result (&optional info
)
1924 "Remove the result of the current source block."
1926 (let ((location (org-babel-where-is-src-block-result nil info
)) start
)
1928 (setq start
(- location
1))
1930 (goto-char location
) (forward-line 1)
1931 (delete-region start
(org-babel-result-end))))))
1933 (defun org-babel-result-end ()
1934 "Return the point at the end of the current set of results"
1937 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
1938 ((org-at-item-p) (let* ((struct (org-list-struct))
1939 (prvs (org-list-prevs-alist struct
)))
1940 (org-list-get-list-end (point-at-bol) struct prvs
)))
1941 ((looking-at "^\\([ \t]*\\):RESULTS:")
1942 (progn (re-search-forward (concat "^" (match-string 1) ":END:"))
1943 (forward-char 1) (point)))
1945 (let ((case-fold-search t
))
1946 (if (looking-at (concat "[ \t]*#\\+begin_\\([^ \t\n\r]+\\)"))
1947 (progn (re-search-forward (concat "[ \t]*#\\+end_" (match-string 1))
1950 (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
1954 (defun org-babel-result-to-file (result)
1955 "Convert RESULT into an `org-mode' link.
1956 If the `default-directory' is different from the containing
1957 file's directory then expand relative links."
1958 (flet ((cond-exp (file)
1959 (if (and default-directory
1961 (not (string= (expand-file-name default-directory
)
1963 (file-name-directory buffer-file-name
)))))
1964 (expand-file-name file default-directory
)
1966 (if (stringp result
)
1967 (format "[[file:%s]]" (cond-exp result
))
1968 (when (and (listp result
) (= 2 (length result
))
1969 (stringp (car result
)) (stringp (cadr result
)))
1970 (format "[[file:%s][%s]]" (car result
) (cadr result
))))))
1972 (defun org-babel-examplize-region (beg end
&optional results-switches
)
1973 "Comment out region using the inline '==' or ': ' org example quote."
1975 (flet ((chars-between (b e
) (string-match "[\\S]" (buffer-substring b e
))))
1976 (if (or (chars-between (save-excursion (goto-char beg
) (point-at-bol)) beg
)
1977 (chars-between end
(save-excursion (goto-char end
) (point-at-eol))))
1980 (insert (format "=%s=" (prog1 (buffer-substring beg end
)
1981 (delete-region beg end
)))))
1982 (let ((size (count-lines beg end
)))
1984 (cond ((= size
0)) ; do nothing for an empty result
1985 ((< size org-babel-min-lines-for-block-output
)
1988 (beginning-of-line 1) (insert ": ") (forward-line 1)))
1991 (insert (if results-switches
1992 (format "#+begin_example%s\n" results-switches
)
1993 "#+begin_example\n"))
1994 (if (markerp end
) (goto-char end
) (forward-char (- end beg
)))
1995 (insert "#+end_example\n"))))))))
1997 (defun org-babel-update-block-body (new-body)
1998 "Update the body of the current code block to NEW-BODY."
1999 (if (not (org-babel-where-is-src-block-head))
2000 (error "not in source block")
2002 (replace-match (concat (org-babel-trim new-body
) "\n") nil t nil
5))
2003 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
2005 (defun org-babel-merge-params (&rest plists
)
2006 "Combine all parameter association lists in PLISTS.
2007 Later elements of PLISTS override the values of previous elements.
2008 This takes into account some special considerations for certain
2009 parameters when merging lists."
2010 (let ((results-exclusive-groups
2011 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2012 (cdr (assoc 'results org-babel-common-header-args-w-values
))))
2013 (exports-exclusive-groups
2014 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2015 (cdr (assoc 'exports org-babel-common-header-args-w-values
))))
2017 params results exports tangle noweb cache vars shebang comments padline
)
2018 (flet ((e-merge (exclusive-groups &rest result-params
)
2019 ;; maintain exclusivity of mutually exclusive parameters
2021 (mapc (lambda (new-params)
2022 (mapc (lambda (new-param)
2023 (mapc (lambda (exclusive-group)
2024 (when (member new-param exclusive-group
)
2025 (mapcar (lambda (excluded-param)
2032 (setq output
(org-uniquify
2033 (cons new-param output
))))
2043 (let ((name (if (listp (cdr pair
))
2045 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
2047 (intern (match-string 1 (cdr pair
)))))))
2051 (if (member name
(mapcar #'car vars
))
2055 (unless (equal (car p
) name
) p
))
2058 (list (cons name pair
))))
2059 ;; if no name is given and we already have named variables
2060 ;; then assign to named variables in order
2061 (if (and vars
(nth variable-index vars
))
2062 (prog1 (setf (cddr (nth variable-index vars
))
2063 (concat (symbol-name
2064 (car (nth variable-index vars
)))
2066 (incf variable-index
))
2067 (error "variable \"%s\" must be assigned a default value"
2070 (setq results
(e-merge results-exclusive-groups
2073 (let ((r (cdr pair
)))
2074 (if (stringp r
) r
(eval r
)))))))
2077 (setq results
(e-merge results-exclusive-groups
2079 (unless (or (member "both" exports
)
2080 (member "none" exports
)
2081 (member "code" exports
))
2082 (setq exports
(e-merge exports-exclusive-groups
2083 exports
'("results"))))
2084 (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))
2086 (setq exports
(e-merge exports-exclusive-groups
2087 exports
(split-string (cdr pair
)))))
2088 (:tangle
;; take the latest -- always overwrite
2089 (setq tangle
(or (list (cdr pair
)) tangle
)))
2091 (setq noweb
(e-merge
2092 '(("yes" "no" "tangle" "no-export" "strip-export"))
2094 (split-string (or (cdr pair
) "")))))
2096 (setq cache
(e-merge '(("yes" "no")) cache
2097 (split-string (or (cdr pair
) "")))))
2099 (setq padline
(e-merge '(("yes" "no")) padline
2100 (split-string (or (cdr pair
) "")))))
2101 (:shebang
;; take the latest -- always overwrite
2102 (setq shebang
(or (list (cdr pair
)) shebang
)))
2104 (setq comments
(e-merge '(("yes" "no")) comments
2105 (split-string (or (cdr pair
) "")))))
2106 (t ;; replace: this covers e.g. :session
2107 (setq params
(cons pair
(assq-delete-all (car pair
) params
))))))
2110 (setq vars
(reverse vars
))
2111 (while vars
(setq params
(cons (cons :var
(cddr (pop vars
))) params
)))
2114 (let ((key (intern (concat ":" (symbol-name hd
))))
2116 (setf params
(cons (cons key
(mapconcat 'identity val
" ")) params
))))
2117 '(results exports tangle noweb padline cache shebang comments
))
2120 (defvar *org-babel-use-quick-and-dirty-noweb-expansion
* nil
2121 "Set to true to use regular expressions to expand noweb references.
2122 This results in much faster noweb reference expansion but does
2123 not properly allow code blocks to inherit the \":noweb-ref\"
2124 header argument from buffer or subtree wide properties.")
2126 (defun org-babel-noweb-p (params context
)
2127 "Check if PARAMS require expansion in CONTEXT.
2128 CONTEXT may be one of :tangle, :export or :eval."
2129 (flet ((intersect (as bs
)
2131 (if (member (car as
) bs
)
2133 (intersect (cdr as
) bs
)))))
2134 (intersect (case context
2135 (:tangle
'("yes" "tangle" "no-export" "strip-export"))
2136 (:eval
'("yes" "no-export" "strip-export"))
2138 (split-string (or (cdr (assoc :noweb params
)) "")))))
2140 (defun org-babel-expand-noweb-references (&optional info parent-buffer
)
2141 "Expand Noweb references in the body of the current source code block.
2143 For example the following reference would be replaced with the
2144 body of the source-code block named 'example-block'.
2148 Note that any text preceding the <<foo>> construct on a line will
2149 be interposed between the lines of the replacement text. So for
2150 example if <<foo>> is placed behind a comment, then the entire
2151 replacement text will also be commented.
2153 This function must be called from inside of the buffer containing
2154 the source-code block which holds BODY.
2156 In addition the following syntax can be used to insert the
2157 results of evaluating the source-code block named 'example-block'.
2161 Any optional arguments can be passed to example-block by placing
2162 the arguments inside the parenthesis following the convention
2163 defined by `org-babel-lob'. For example
2165 <<example-block(a=9)>>
2167 would set the value of argument \"a\" equal to \"9\". Note that
2168 these arguments are not evaluated in the current source-code
2169 block but are passed literally to the \"example-block\"."
2170 (let* ((parent-buffer (or parent-buffer
(current-buffer)))
2171 (info (or info
(org-babel-get-src-block-info)))
2174 (comment (string= "noweb" (cdr (assoc :comments
(nth 2 info
)))))
2175 (rx-prefix (concat "\\(" org-babel-src-name-regexp
"\\|"
2176 ":noweb-ref[ \t]+" "\\)"))
2177 (new-body "") index source-name evaluate prefix blocks-in-buffer
)
2178 (flet ((nb-add (text) (setq new-body
(concat new-body text
)))
2181 (funcall (intern (concat lang
"-mode")))
2182 (comment-region (point) (progn (insert text
) (point)))
2183 (org-babel-trim (buffer-string)))))
2185 (insert body
) (goto-char (point-min))
2186 (setq index
(point))
2187 (while (and (re-search-forward (org-babel-noweb-wrap) nil t
))
2188 (save-match-data (setf source-name
(match-string 1)))
2189 (save-match-data (setq evaluate
(string-match "\(.*\)" source-name
)))
2192 (buffer-substring (match-beginning 0)
2194 (beginning-of-line 1) (point)))))
2195 ;; add interval to new-body (removing noweb reference)
2196 (goto-char (match-beginning 0))
2197 (nb-add (buffer-substring index
(point)))
2198 (goto-char (match-end 0))
2199 (setq index
(point))
2201 (with-current-buffer parent-buffer
2202 (mapconcat ;; interpose PREFIX between every line
2206 (let ((raw (org-babel-ref-resolve source-name
)))
2207 (if (stringp raw
) raw
(format "%S" raw
)))
2209 ;; retrieve from the library of babel
2210 (nth 2 (assoc (intern source-name
)
2211 org-babel-library-of-babel
))
2212 ;; return the contents of headlines literally
2214 (when (org-babel-ref-goto-headline-id source-name
)
2215 (org-babel-ref-headline-body)))
2216 ;; find the expansion of reference in this buffer
2217 (let ((rx (concat rx-prefix source-name
))
2220 (goto-char (point-min))
2221 (if *org-babel-use-quick-and-dirty-noweb-expansion
*
2222 (while (re-search-forward rx nil t
)
2223 (let* ((i (org-babel-get-src-block-info 'light
))
2224 (body (org-babel-expand-noweb-references i
))
2225 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2229 (concat (c-wrap (car cs
)) "\n"
2231 (c-wrap (cadr cs
))))
2232 (org-babel-tangle-comment-links i
))
2234 (setq expansion
(cons sep
(cons full expansion
)))))
2235 (org-babel-map-src-blocks nil
2236 (let ((i (org-babel-get-src-block-info 'light
)))
2237 (when (equal (or (cdr (assoc :noweb-ref
(nth 2 i
)))
2240 (let* ((body (org-babel-expand-noweb-references i
))
2241 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2245 (concat (c-wrap (car cs
)) "\n"
2247 (c-wrap (cadr cs
))))
2248 (org-babel-tangle-comment-links i
))
2251 (cons sep
(cons full expansion
)))))))))
2253 (mapconcat #'identity
(nreverse (cdr expansion
)) "")))
2254 ;; possibly raise an error if named block doesn't exist
2255 (if (member lang org-babel-noweb-error-langs
)
2257 (org-babel-noweb-wrap source-name
)
2258 "could not be resolved (see "
2259 "`org-babel-noweb-error-langs')"))
2261 "[\n\r]") (concat "\n" prefix
)))))
2262 (nb-add (buffer-substring index
(point-max)))))
2265 (defun org-babel-clean-text-properties (text)
2266 "Strip all properties from text return."
2268 (set-text-properties 0 (length text
) nil text
) text
))
2270 (defun org-babel-strip-protective-commas (body)
2271 "Strip protective commas from bodies of source blocks."
2273 (replace-regexp-in-string "^,#" "#" body
)))
2275 (defun org-babel-script-escape (str &optional force
)
2276 "Safely convert tables into elisp lists."
2277 (let (in-single in-double out
)
2278 ((lambda (escaped) (condition-case nil
(org-babel-read escaped
) (error escaped
)))
2282 (or (and (string-equal "[" (substring str
0 1))
2283 (string-equal "]" (substring str -
1)))
2284 (and (string-equal "{" (substring str
0 1))
2285 (string-equal "}" (substring str -
1)))
2286 (and (string-equal "(" (substring str
0 1))
2287 (string-equal ")" (substring str -
1))))))
2297 (91 (if (or in-double in-single
) ; [
2300 (93 (if (or in-double in-single
) ; ]
2303 (123 (if (or in-double in-single
) ; {
2306 (125 (if (or in-double in-single
) ; }
2309 (44 (if (or in-double in-single
) ; ,
2310 (cons 44 out
) (cons 32 out
)))
2311 (39 (if in-double
; '
2313 (setq in-single
(not in-single
)) (cons 34 out
)))
2314 (34 (if in-single
; "
2315 (append (list 34 32) out
)
2316 (setq in-double
(not in-double
)) (cons 34 out
)))
2317 (t (cons ch out
)))))
2318 (string-to-list str
))
2319 (apply #'string
(reverse out
)))))
2322 (defun org-babel-read (cell &optional inhibit-lisp-eval
)
2323 "Convert the string value of CELL to a number if appropriate.
2324 Otherwise if cell looks like lisp (meaning it starts with a
2325 \"(\", \"'\", \"`\" or a \"[\") then read it as lisp, otherwise
2326 return it unmodified as a string. Optional argument NO-LISP-EVAL
2327 inhibits lisp evaluation for situations in which is it not
2329 (if (and (stringp cell
) (not (equal cell
"")))
2330 (or (org-babel-number-p cell
)
2331 (if (and (not inhibit-lisp-eval
)
2332 (member (substring cell
0 1) '("(" "'" "`" "[")))
2334 (if (string= (substring cell
0 1) "\"")
2336 (progn (set-text-properties 0 (length cell
) nil cell
) cell
))))
2339 (defun org-babel-number-p (string)
2340 "If STRING represents a number return its value."
2341 (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string
)
2342 (= (length (substring string
(match-beginning 0)
2345 (string-to-number string
)))
2347 (defun org-babel-import-elisp-from-file (file-name &optional separator
)
2348 "Read the results located at FILE-NAME into an elisp table.
2349 If the table is trivial, then return it as a scalar."
2351 (save-window-excursion
2355 (org-table-import file-name separator
)
2356 (delete-file file-name
)
2357 (setq result
(mapcar (lambda (row)
2358 (mapcar #'org-babel-string-read row
))
2359 (org-table-to-lisp))))
2361 (if (null (cdr result
)) ;; if result is trivial vector, then scalarize it
2362 (if (consp (car result
))
2363 (if (null (cdr (car result
)))
2369 (defun org-babel-string-read (cell)
2370 "Strip nested \"s from around strings."
2371 (org-babel-read (or (and (stringp cell
)
2372 (string-match "\\\"\\(.+\\)\\\"" cell
)
2373 (match-string 1 cell
))
2376 (defun org-babel-reverse-string (string)
2377 "Return the reverse of STRING."
2378 (apply 'string
(reverse (string-to-list string
))))
2380 (defun org-babel-chomp (string &optional regexp
)
2381 "Strip trailing spaces and carriage returns from STRING.
2382 Default regexp used is \"[ \f\t\n\r\v]\" but can be
2383 overwritten by specifying a regexp as a second argument."
2384 (let ((regexp (or regexp
"[ \f\t\n\r\v]")))
2385 (while (and (> (length string
) 0)
2386 (string-match regexp
(substring string -
1)))
2387 (setq string
(substring string
0 -
1)))
2390 (defun org-babel-trim (string &optional regexp
)
2391 "Strip leading and trailing spaces and carriage returns from STRING.
2392 Like `org-babel-chomp' only it runs on both the front and back
2394 (org-babel-chomp (org-babel-reverse-string
2395 (org-babel-chomp (org-babel-reverse-string string
) regexp
))
2398 (defvar org-babel-org-babel-call-process-region-original nil
)
2399 (defun org-babel-tramp-handle-call-process-region
2400 (start end program
&optional delete buffer display
&rest args
)
2401 "Use tramp to handle call-process-region.
2402 Fixes a bug in `tramp-handle-call-process-region'."
2403 (if (and (featurep 'tramp
) (file-remote-p default-directory
))
2404 (let ((tmpfile (tramp-compat-make-temp-file "")))
2405 (write-region start end tmpfile
)
2406 (when delete
(delete-region start end
))
2408 ;; (apply 'call-process program tmpfile buffer display args)
2410 (apply 'process-file program tmpfile buffer display args
)
2411 (delete-file tmpfile
)))
2412 ;; org-babel-call-process-region-original is the original emacs
2413 ;; definition. It is in scope from the let binding in
2414 ;; org-babel-execute-src-block
2415 (apply org-babel-call-process-region-original
2416 start end program delete buffer display args
)))
2418 (defun org-babel-local-file-name (file)
2419 "Return the local name component of FILE."
2420 (if (file-remote-p file
)
2422 (with-parsed-tramp-file-name file nil
2426 (defun org-babel-process-file-name (name &optional no-quote-p
)
2427 "Prepare NAME to be used in an external process.
2428 If NAME specifies a remote location, the remote portion of the
2429 name is removed, since in that case the process will be executing
2430 remotely. The file name is then processed by
2431 `expand-file-name'. Unless second argument NO-QUOTE-P is non-nil,
2432 the file name is additionally processed by
2433 `shell-quote-argument'"
2434 ((lambda (f) (if no-quote-p f
(shell-quote-argument f
)))
2435 (expand-file-name (org-babel-local-file-name name
))))
2437 (defvar org-babel-temporary-directory
)
2438 (unless (or noninteractive
(boundp 'org-babel-temporary-directory
))
2439 (defvar org-babel-temporary-directory
2440 (or (and (boundp 'org-babel-temporary-directory
)
2441 (file-exists-p org-babel-temporary-directory
)
2442 org-babel-temporary-directory
)
2443 (make-temp-file "babel-" t
))
2444 "Directory to hold temporary files created to execute code blocks.
2445 Used by `org-babel-temp-file'. This directory will be removed on
2448 (defun org-babel-temp-file (prefix &optional suffix
)
2449 "Create a temporary file in the `org-babel-temporary-directory'.
2450 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2451 value of `temporary-file-directory' temporarily set to the value
2452 of `org-babel-temporary-directory'."
2453 (if (file-remote-p default-directory
)
2455 (concat (file-remote-p default-directory
)
2457 prefix temporary-file-directory
)
2459 (let ((temporary-file-directory
2460 (or (and (boundp 'org-babel-temporary-directory
)
2461 (file-exists-p org-babel-temporary-directory
)
2462 org-babel-temporary-directory
)
2463 temporary-file-directory
)))
2464 (make-temp-file prefix nil suffix
))))
2466 (defun org-babel-remove-temporary-directory ()
2467 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2468 (when (and (boundp 'org-babel-temporary-directory
)
2469 (file-exists-p org-babel-temporary-directory
))
2470 ;; taken from `delete-directory' in files.el
2473 (mapc (lambda (file)
2474 ;; This test is equivalent to
2475 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2476 ;; but more efficient
2477 (if (eq t
(car (file-attributes file
)))
2478 (delete-directory file
)
2479 (delete-file file
)))
2480 ;; We do not want to delete "." and "..".
2481 (directory-files org-babel-temporary-directory
'full
2482 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2483 (delete-directory org-babel-temporary-directory
))
2485 (message "Failed to remove temporary Org-babel directory %s"
2486 (if (boundp 'org-babel-temporary-directory
)
2487 org-babel-temporary-directory
2488 "[directory not defined]"))))))
2490 (add-hook 'kill-emacs-hook
'org-babel-remove-temporary-directory
)