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 (under-point (thing-at-point 'line
)))
1462 (list (org-icompleting-read
1463 "source-block name: " (org-babel-src-block-names) nil t
1466 ((string-match (org-babel-noweb-wrap) under-point
)
1467 (let ((block-name (match-string 1 under-point
)))
1468 (string-match "[^(]*" block-name
)
1469 (match-string 0 block-name
)))
1471 ((string-match org-babel-lob-one-liner-regexp under-point
)
1472 (let ((source-info (car (org-babel-lob-get-info))))
1473 (if (string-match "^\\([^\\[]+?\\)\\(\\[.*\\]\\)?(" source-info
)
1474 (let ((source-name (match-string 1 source-info
)))
1477 ((string-match (concat "#\\+" org-babel-results-keyword
1478 "\\:\s+\\([^\\(]*\\)") under-point
)
1479 (match-string 1 under-point
))
1481 ((and (thing-at-point 'symbol
))
1482 (org-babel-find-named-block (thing-at-point 'symbol
))
1483 (thing-at-point 'symbol
))
1485 (let ((point (org-babel-find-named-block name
)))
1487 ;; taken from `org-open-at-point'
1488 (progn (org-mark-ring-push) (goto-char point
) (org-show-context))
1489 (message "source-code block '%s' not found in this buffer" name
))))
1491 (defun org-babel-find-named-block (name)
1492 "Find a named source-code block.
1493 Return the location of the source block identified by source
1494 NAME, or nil if no such block exists. Set match data according to
1495 org-babel-named-src-block-regexp."
1497 (let ((case-fold-search t
)
1498 (regexp (org-babel-named-src-block-regexp-for-name name
)) msg
)
1499 (goto-char (point-min))
1500 (when (or (re-search-forward regexp nil t
)
1501 (re-search-backward regexp nil t
))
1502 (match-beginning 0)))))
1504 (defun org-babel-src-block-names (&optional file
)
1505 "Returns the names of source blocks in FILE or the current buffer."
1507 (when file
(find-file file
)) (goto-char (point-min))
1509 (while (re-search-forward org-babel-src-name-w-name-regexp nil t
)
1510 (setq names
(cons (match-string 3) names
)))
1514 (defun org-babel-goto-named-result (name)
1515 "Go to a named result."
1517 (let ((completion-ignore-case t
))
1518 (list (org-icompleting-read "source-block name: "
1519 (org-babel-result-names) nil t
))))
1520 (let ((point (org-babel-find-named-result name
)))
1522 ;; taken from `org-open-at-point'
1523 (progn (goto-char point
) (org-show-context))
1524 (message "result '%s' not found in this buffer" name
))))
1526 (defun org-babel-find-named-result (name &optional point
)
1527 "Find a named result.
1528 Return the location of the result named NAME in the current
1529 buffer or nil if no such result exists."
1531 (goto-char (or point
(point-min)))
1532 (catch 'is-a-code-block
1533 (when (re-search-forward
1534 (concat org-babel-result-regexp
1535 "[ \t]" (regexp-quote name
) "[ \t\n\f\v\r]") nil t
)
1536 (when (and (string= "name" (downcase (match-string 1)))
1537 (or (looking-at org-babel-src-block-regexp
)
1538 (looking-at org-babel-multi-line-header-regexp
)))
1539 (throw 'is-a-code-block
(org-babel-find-named-result name
(point))))
1540 (beginning-of-line 0) (point)))))
1542 (defun org-babel-result-names (&optional file
)
1543 "Returns the names of results in FILE or the current buffer."
1545 (when file
(find-file file
)) (goto-char (point-min))
1547 (while (re-search-forward org-babel-result-w-name-regexp nil t
)
1548 (setq names
(cons (match-string 4) names
)))
1552 (defun org-babel-next-src-block (&optional arg
)
1553 "Jump to the next source block.
1554 With optional prefix argument ARG, jump forward ARG many source blocks."
1556 (when (looking-at org-babel-src-block-regexp
) (forward-char 1))
1558 (re-search-forward org-babel-src-block-regexp nil nil
(or arg
1))
1559 (error (error "No further code blocks")))
1560 (goto-char (match-beginning 0)) (org-show-context))
1563 (defun org-babel-previous-src-block (&optional arg
)
1564 "Jump to the previous source block.
1565 With optional prefix argument ARG, jump backward ARG many source blocks."
1568 (re-search-backward org-babel-src-block-regexp nil nil
(or arg
1))
1569 (error (error "No previous code blocks")))
1570 (goto-char (match-beginning 0)) (org-show-context))
1572 (defvar org-babel-load-languages
)
1575 (defun org-babel-mark-block ()
1576 "Mark current src block"
1582 (looking-at org-babel-src-block-regexp
))
1583 (push-mark (match-end 5) nil t
)
1584 (goto-char (match-beginning 5))))
1585 (org-babel-where-is-src-block-head)))
1587 (defun org-babel-demarcate-block (&optional arg
)
1588 "Wrap or split the code in the region or on the point.
1589 When called from inside of a code block the current block is
1590 split. When called from outside of a code block a new code block
1591 is created. In both cases if the region is demarcated and if the
1592 region is not active then the point is demarcated."
1594 (let ((info (org-babel-get-src-block-info 'light
))
1595 (headers (progn (org-babel-where-is-src-block-head)
1597 (stars (concat (make-string (or (org-current-level) 1) ?
*) " ")))
1603 (let ((lang (nth 0 info
))
1604 (indent (make-string (nth 5 info
) ?
)))
1605 (when (string-match "^[[:space:]]*$"
1606 (buffer-substring (point-at-bol)
1608 (delete-region (point-at-bol) (point-at-eol)))
1610 (if (looking-at "^") "" "\n")
1611 indent
"#+end_src\n"
1612 (if arg stars indent
) "\n"
1613 indent
"#+begin_src " lang
1614 (if (> (length headers
) 1)
1615 (concat " " headers
) headers
)
1616 (if (looking-at "[\n\r]")
1618 (concat "\n" (make-string (current-column) ?
)))))))
1619 (move-end-of-line 2))
1620 (sort (if (region-active-p) (list (mark) (point)) (list (point))) #'>))
1621 (let ((start (point))
1622 (lang (org-icompleting-read "Lang: "
1623 (mapcar (lambda (el) (symbol-name (car el
)))
1624 org-babel-load-languages
)))
1625 (body (delete-and-extract-region
1626 (if (region-active-p) (mark) (point)) (point))))
1627 (insert (concat (if (looking-at "^") "" "\n")
1628 (if arg
(concat stars
"\n") "")
1629 "#+begin_src " lang
"\n"
1631 (if (or (= (length body
) 0)
1632 (string-match "[\r\n]$" body
)) "" "\n")
1634 (goto-char start
) (move-end-of-line 1)))))
1636 (defvar org-babel-lob-one-liner-regexp
)
1637 (defun org-babel-where-is-src-block-result (&optional insert info hash indent
)
1638 "Find where the current source block results begin.
1639 Return the point at the beginning of the result of the current
1640 source block. Specifically at the beginning of the results line.
1641 If no result exists for this block then create a results line
1642 following the source block."
1644 (let* ((on-lob-line (save-excursion
1645 (beginning-of-line 1)
1646 (looking-at org-babel-lob-one-liner-regexp
)))
1647 (inlinep (when (org-babel-get-inline-src-block-matches)
1649 (name (if on-lob-line
1650 (nth 0 (org-babel-lob-get-info))
1651 (nth 4 (or info
(org-babel-get-src-block-info 'light
)))))
1652 (head (unless on-lob-line
(org-babel-where-is-src-block-head)))
1654 (when head
(goto-char head
))
1656 found
;; was there a result (before we potentially insert one)
1661 ;; - return t if it is found, else return nil
1662 ;; - if it does not need to be rebuilt, then don't set end
1663 ;; - if it does need to be rebuilt then do set end
1664 name
(setq beg
(org-babel-find-named-result name
))
1666 (when (and hash
(not (string= hash
(match-string 3))))
1667 (goto-char beg
) (setq end beg
) ;; beginning of result
1669 (delete-region end
(org-babel-result-end)) nil
)))
1672 ;; - return t if it is found, else return nil
1673 ;; - if it is found, and the hash doesn't match, delete and set end
1674 (or on-lob-line
(re-search-forward "^[ \t]*#\\+end_src" nil t
))
1675 (progn (end-of-line 1)
1676 (if (eobp) (insert "\n") (forward-char 1))
1679 (progn ;; unnamed results line already exists
1680 (re-search-forward "[^ \f\t\n\r\v]" nil t
)
1681 (beginning-of-line 1)
1683 (concat org-babel-result-regexp
"\n")))
1685 ;; must remove and rebuild if hash!=old-hash
1686 (if (and hash
(not (string= hash
(match-string 3))))
1690 end
(org-babel-result-end)))
1691 (setq end nil
)))))))))
1692 (if (and insert end
)
1696 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1701 (org-number-sequence 1 indent
) "")
1703 "#+" org-babel-results-keyword
1704 (when hash
(concat "["hash
"]"))
1706 (when name
(concat " " name
)) "\n"))
1707 (unless beg
(insert "\n") (backward-char))
1708 (beginning-of-line 0)
1709 (if hash
(org-babel-hide-hash))
1713 (defvar org-block-regexp
)
1714 (defun org-babel-read-result ()
1715 "Read the result at `point' into emacs-lisp."
1716 (let ((case-fold-search t
) result-string
)
1718 ((org-at-table-p) (org-babel-read-table))
1719 ((org-at-item-p) (org-babel-read-list))
1720 ((looking-at org-bracket-link-regexp
) (org-babel-read-link))
1721 ((looking-at org-block-regexp
) (org-babel-trim (match-string 4)))
1722 ((looking-at "^[ \t]*: ")
1725 (mapconcat (lambda (line)
1726 (if (and (> (length line
) 1)
1727 (string-match "^[ \t]*: \\(.+\\)" line
))
1728 (match-string 1 line
)
1732 (point) (org-babel-result-end)) "[\r\n]+")
1734 (or (org-babel-number-p result-string
) result-string
))
1735 ((looking-at org-babel-result-regexp
)
1736 (save-excursion (forward-line 1) (org-babel-read-result))))))
1738 (defun org-babel-read-table ()
1739 "Read the table at `point' into emacs-lisp."
1740 (mapcar (lambda (row)
1741 (if (and (symbolp row
) (equal row
'hline
)) row
1742 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
)) row
)))
1743 (org-table-to-lisp)))
1745 (defun org-babel-read-list ()
1746 "Read the list at `point' into emacs-lisp."
1747 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
))
1748 (mapcar #'cadr
(cdr (org-list-parse-list)))))
1750 (defvar org-link-types-re
)
1751 (defun org-babel-read-link ()
1752 "Read the link at `point' into emacs-lisp.
1753 If the path of the link is a file path it is expanded using
1754 `expand-file-name'."
1755 (let* ((case-fold-search t
)
1756 (raw (and (looking-at org-bracket-link-regexp
)
1757 (org-babel-clean-text-properties (match-string 1))))
1758 (type (and (string-match org-link-types-re raw
)
1759 (match-string 1 raw
))))
1761 ((not type
) (expand-file-name raw
))
1762 ((string= type
"file")
1763 (and (string-match "file\\(.*\\):\\(.+\\)" raw
)
1764 (expand-file-name (match-string 2 raw
))))
1767 (defun org-babel-format-result (result &optional sep
)
1768 "Format RESULT for writing to file."
1769 (flet ((echo-res (result)
1770 (if (stringp result
) result
(format "%S" result
))))
1779 (echo-res result
))))
1781 (defun org-babel-insert-result
1782 (result &optional result-params info hash indent lang
)
1783 "Insert RESULT into the current buffer.
1784 By default RESULT is inserted after the end of the
1785 current source block. With optional argument RESULT-PARAMS
1786 controls insertion of results in the org-mode file.
1787 RESULT-PARAMS can take the following values...
1789 replace - (default option) insert results after the source block
1790 replacing any previously inserted results
1792 silent -- no results are inserted
1794 file ---- the results are interpreted as a file path, and are
1795 inserted into the buffer using the Org-mode file syntax
1797 list ---- the results are interpreted as an Org-mode list.
1799 raw ----- results are added directly to the Org-mode file. This
1800 is a good option if you code block will output org-mode
1803 wrap ---- results are added directly to the Org-mode file as with
1804 \"raw\", but are wrapped in a RESULTS drawer, allowing
1805 them to later be replaced or removed automatically.
1807 org ----- similar in effect to raw, only the results are wrapped
1808 in an org code block. Similar to the raw option, on
1809 export the results will be interpreted as org-formatted
1810 text, however by wrapping the results in an org code
1811 block they can be replaced upon re-execution of the
1814 html ---- results are added inside of a #+BEGIN_HTML block. This
1815 is a good option if you code block will output html
1818 latex --- results are added inside of a #+BEGIN_LATEX block.
1819 This is a good option if you code block will output
1820 latex formatted text.
1822 code ---- the results are extracted in the syntax of the source
1823 code of the language being evaluated and are added
1824 inside of a #+BEGIN_SRC block with the source-code
1825 language set appropriately. Note this relies on the
1826 optional LANG argument."
1827 (if (stringp result
)
1829 (setq result
(org-babel-clean-text-properties result
))
1830 (when (member "file" result-params
)
1831 (setq result
(org-babel-result-to-file result
))))
1832 (unless (listp result
) (setq result
(format "%S" result
))))
1833 (if (and result-params
(member "silent" result-params
))
1835 (message (replace-regexp-in-string "%" "%%" (format "%S" result
)))
1840 (when (or (org-babel-get-inline-src-block-matches)
1841 (org-babel-get-lob-one-liner-matches))
1842 (goto-char (match-end 0))
1843 (insert (if (listp result
) "\n" " "))
1845 (existing-result (unless inlinep
1846 (org-babel-where-is-src-block-result
1847 t info hash indent
)))
1849 (cdr (assoc :results_switches
(nth 2 info
))))
1851 (when (and (stringp result
) ; ensure results end in a newline
1853 (> (length result
) 0)
1854 (not (or (string-equal (substring result -
1) "\n")
1855 (string-equal (substring result -
1) "\r"))))
1856 (setq result
(concat result
"\n")))
1857 (if (not existing-result
)
1858 (setq beg
(or inlinep
(point)))
1859 (goto-char existing-result
)
1861 (re-search-forward "#" nil t
)
1862 (setq indent
(- (current-column) 1)))
1866 ((member "replace" result-params
)
1867 (delete-region (point) (org-babel-result-end)))
1868 ((member "append" result-params
)
1869 (goto-char (org-babel-result-end)) (setq beg
(point-marker)))
1870 ((member "prepend" result-params
)))) ; already there
1871 (setq results-switches
1872 (if results-switches
(concat " " results-switches
) ""))
1873 (flet ((wrap (start finish
)
1874 (goto-char beg
) (insert (concat start
"\n"))
1875 (goto-char end
) (insert (concat finish
"\n"))
1876 (setq end
(point-marker)))
1877 (proper-list-p (it) (and (listp it
) (null (cdr (last it
))))))
1878 ;; insert results based on type
1880 ;; do nothing for an empty result
1882 ;; insert a list if preferred
1883 ((member "list" result-params
)
1886 (org-list-to-generic
1889 (lambda (el) (list nil
(if (stringp el
) el
(format "%S" el
))))
1890 (if (listp result
) result
(list result
))))
1891 '(:splicep nil
:istart
"- " :iend
"\n")))
1893 ;; assume the result is a table if it's not a string
1894 ((proper-list-p result
)
1896 (insert (concat (orgtbl-to-orgtbl
1897 (if (or (eq 'hline
(car result
))
1898 (and (listp (car result
))
1899 (listp (cdr (car result
)))))
1900 result
(list result
))
1901 '(:fmt
(lambda (cell) (format "%s" cell
)))) "\n"))
1902 (goto-char beg
) (when (org-at-table-p) (org-table-align)))
1903 ((and (listp result
) (not (proper-list-p result
)))
1904 (insert (format "%s\n" result
)))
1905 ((member "file" result-params
)
1906 (when inlinep
(goto-char inlinep
))
1908 (t (goto-char beg
) (insert result
)))
1909 (when (proper-list-p result
) (goto-char (org-table-end)))
1910 (setq end
(point-marker))
1911 ;; possibly wrap result
1913 ((assoc :wrap
(nth 2 info
))
1914 (let ((name (or (cdr (assoc :wrap
(nth 2 info
))) "RESULTS")))
1915 (wrap (concat "#+BEGIN_" name
) (concat "#+END_" name
))))
1916 ((member "html" result-params
)
1917 (wrap "#+BEGIN_HTML" "#+END_HTML"))
1918 ((member "latex" result-params
)
1919 (wrap "#+BEGIN_LaTeX" "#+END_LaTeX"))
1920 ((member "code" result-params
)
1921 (wrap (format "#+BEGIN_SRC %s%s" (or lang
"none") results-switches
)
1923 ((member "org" result-params
)
1924 (wrap "#+BEGIN_ORG" "#+END_ORG"))
1925 ((member "raw" result-params
)
1926 (goto-char beg
) (if (org-at-table-p) (org-cycle)))
1927 ((member "wrap" result-params
)
1928 (wrap ":RESULTS:" ":END:"))
1929 ((and (not (proper-list-p result
))
1930 (not (member "file" result-params
)))
1931 (org-babel-examplize-region beg end results-switches
)
1932 (setq end
(point)))))
1933 ;; possibly indent the results to match the #+results line
1934 (when (and (not inlinep
) (numberp indent
) indent
(> indent
0)
1935 ;; in this case `table-align' does the work for us
1936 (not (and (listp result
)
1937 (member "append" result-params
))))
1938 (indent-rigidly beg end indent
))))
1940 (if (member "value" result-params
)
1941 (message "Code block returned no value.")
1942 (message "Code block produced no output."))
1943 (message "Code block evaluation complete."))))
1945 (defun org-babel-remove-result (&optional info
)
1946 "Remove the result of the current source block."
1948 (let ((location (org-babel-where-is-src-block-result nil info
)) start
)
1950 (setq start
(- location
1))
1952 (goto-char location
) (forward-line 1)
1953 (delete-region start
(org-babel-result-end))))))
1955 (defun org-babel-result-end ()
1956 "Return the point at the end of the current set of results"
1959 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
1960 ((org-at-item-p) (let* ((struct (org-list-struct))
1961 (prvs (org-list-prevs-alist struct
)))
1962 (org-list-get-list-end (point-at-bol) struct prvs
)))
1963 ((looking-at "^\\([ \t]*\\):RESULTS:")
1964 (progn (re-search-forward (concat "^" (match-string 1) ":END:"))
1965 (forward-char 1) (point)))
1967 (let ((case-fold-search t
))
1968 (if (looking-at (concat "[ \t]*#\\+begin_\\([^ \t\n\r]+\\)"))
1969 (progn (re-search-forward (concat "[ \t]*#\\+end_" (match-string 1))
1972 (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
1976 (defun org-babel-result-to-file (result)
1977 "Convert RESULT into an `org-mode' link.
1978 If the `default-directory' is different from the containing
1979 file's directory then expand relative links."
1980 (flet ((cond-exp (file)
1981 (if (and default-directory
1983 (not (string= (expand-file-name default-directory
)
1985 (file-name-directory buffer-file-name
)))))
1986 (expand-file-name file default-directory
)
1988 (if (stringp result
)
1989 (format "[[file:%s]]" (cond-exp result
))
1990 (when (and (listp result
) (= 2 (length result
))
1991 (stringp (car result
)) (stringp (cadr result
)))
1992 (format "[[file:%s][%s]]" (car result
) (cadr result
))))))
1994 (defun org-babel-examplize-region (beg end
&optional results-switches
)
1995 "Comment out region using the inline '==' or ': ' org example quote."
1997 (flet ((chars-between (b e
) (string-match "[\\S]" (buffer-substring b e
))))
1998 (if (or (chars-between (save-excursion (goto-char beg
) (point-at-bol)) beg
)
1999 (chars-between end
(save-excursion (goto-char end
) (point-at-eol))))
2002 (insert (format "=%s=" (prog1 (buffer-substring beg end
)
2003 (delete-region beg end
)))))
2004 (let ((size (count-lines beg end
)))
2006 (cond ((= size
0)) ; do nothing for an empty result
2007 ((< size org-babel-min-lines-for-block-output
)
2010 (beginning-of-line 1) (insert ": ") (forward-line 1)))
2013 (insert (if results-switches
2014 (format "#+begin_example%s\n" results-switches
)
2015 "#+begin_example\n"))
2016 (if (markerp end
) (goto-char end
) (forward-char (- end beg
)))
2017 (insert "#+end_example\n"))))))))
2019 (defun org-babel-update-block-body (new-body)
2020 "Update the body of the current code block to NEW-BODY."
2021 (if (not (org-babel-where-is-src-block-head))
2022 (error "not in source block")
2024 (replace-match (concat (org-babel-trim new-body
) "\n") nil t nil
5))
2025 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
2027 (defun org-babel-merge-params (&rest plists
)
2028 "Combine all parameter association lists in PLISTS.
2029 Later elements of PLISTS override the values of previous elements.
2030 This takes into account some special considerations for certain
2031 parameters when merging lists."
2032 (let ((results-exclusive-groups
2033 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2034 (cdr (assoc 'results org-babel-common-header-args-w-values
))))
2035 (exports-exclusive-groups
2036 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2037 (cdr (assoc 'exports org-babel-common-header-args-w-values
))))
2039 params results exports tangle noweb cache vars shebang comments padline
)
2040 (flet ((e-merge (exclusive-groups &rest result-params
)
2041 ;; maintain exclusivity of mutually exclusive parameters
2043 (mapc (lambda (new-params)
2044 (mapc (lambda (new-param)
2045 (mapc (lambda (exclusive-group)
2046 (when (member new-param exclusive-group
)
2047 (mapcar (lambda (excluded-param)
2054 (setq output
(org-uniquify
2055 (cons new-param output
))))
2065 (let ((name (if (listp (cdr pair
))
2067 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
2069 (intern (match-string 1 (cdr pair
)))))))
2073 (if (member name
(mapcar #'car vars
))
2077 (unless (equal (car p
) name
) p
))
2080 (list (cons name pair
))))
2081 ;; if no name is given and we already have named variables
2082 ;; then assign to named variables in order
2083 (if (and vars
(nth variable-index vars
))
2084 (prog1 (setf (cddr (nth variable-index vars
))
2085 (concat (symbol-name
2086 (car (nth variable-index vars
)))
2088 (incf variable-index
))
2089 (error "variable \"%s\" must be assigned a default value"
2092 (setq results
(e-merge results-exclusive-groups
2095 (let ((r (cdr pair
)))
2096 (if (stringp r
) r
(eval r
)))))))
2099 (setq results
(e-merge results-exclusive-groups
2101 (unless (or (member "both" exports
)
2102 (member "none" exports
)
2103 (member "code" exports
))
2104 (setq exports
(e-merge exports-exclusive-groups
2105 exports
'("results"))))
2106 (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))
2108 (setq exports
(e-merge exports-exclusive-groups
2109 exports
(split-string (cdr pair
)))))
2110 (:tangle
;; take the latest -- always overwrite
2111 (setq tangle
(or (list (cdr pair
)) tangle
)))
2113 (setq noweb
(e-merge
2114 '(("yes" "no" "tangle" "no-export" "strip-export"))
2116 (split-string (or (cdr pair
) "")))))
2118 (setq cache
(e-merge '(("yes" "no")) cache
2119 (split-string (or (cdr pair
) "")))))
2121 (setq padline
(e-merge '(("yes" "no")) padline
2122 (split-string (or (cdr pair
) "")))))
2123 (:shebang
;; take the latest -- always overwrite
2124 (setq shebang
(or (list (cdr pair
)) shebang
)))
2126 (setq comments
(e-merge '(("yes" "no")) comments
2127 (split-string (or (cdr pair
) "")))))
2128 (t ;; replace: this covers e.g. :session
2129 (setq params
(cons pair
(assq-delete-all (car pair
) params
))))))
2132 (setq vars
(reverse vars
))
2133 (while vars
(setq params
(cons (cons :var
(cddr (pop vars
))) params
)))
2136 (let ((key (intern (concat ":" (symbol-name hd
))))
2138 (setf params
(cons (cons key
(mapconcat 'identity val
" ")) params
))))
2139 '(results exports tangle noweb padline cache shebang comments
))
2142 (defvar *org-babel-use-quick-and-dirty-noweb-expansion
* nil
2143 "Set to true to use regular expressions to expand noweb references.
2144 This results in much faster noweb reference expansion but does
2145 not properly allow code blocks to inherit the \":noweb-ref\"
2146 header argument from buffer or subtree wide properties.")
2148 (defun org-babel-noweb-p (params context
)
2149 "Check if PARAMS require expansion in CONTEXT.
2150 CONTEXT may be one of :tangle, :export or :eval."
2151 (flet ((intersect (as bs
)
2153 (if (member (car as
) bs
)
2155 (intersect (cdr as
) bs
)))))
2156 (intersect (case context
2157 (:tangle
'("yes" "tangle" "no-export" "strip-export"))
2158 (:eval
'("yes" "no-export" "strip-export"))
2160 (split-string (or (cdr (assoc :noweb params
)) "")))))
2162 (defun org-babel-expand-noweb-references (&optional info parent-buffer
)
2163 "Expand Noweb references in the body of the current source code block.
2165 For example the following reference would be replaced with the
2166 body of the source-code block named 'example-block'.
2170 Note that any text preceding the <<foo>> construct on a line will
2171 be interposed between the lines of the replacement text. So for
2172 example if <<foo>> is placed behind a comment, then the entire
2173 replacement text will also be commented.
2175 This function must be called from inside of the buffer containing
2176 the source-code block which holds BODY.
2178 In addition the following syntax can be used to insert the
2179 results of evaluating the source-code block named 'example-block'.
2183 Any optional arguments can be passed to example-block by placing
2184 the arguments inside the parenthesis following the convention
2185 defined by `org-babel-lob'. For example
2187 <<example-block(a=9)>>
2189 would set the value of argument \"a\" equal to \"9\". Note that
2190 these arguments are not evaluated in the current source-code
2191 block but are passed literally to the \"example-block\"."
2192 (let* ((parent-buffer (or parent-buffer
(current-buffer)))
2193 (info (or info
(org-babel-get-src-block-info)))
2196 (comment (string= "noweb" (cdr (assoc :comments
(nth 2 info
)))))
2197 (rx-prefix (concat "\\(" org-babel-src-name-regexp
"\\|"
2198 ":noweb-ref[ \t]+" "\\)"))
2199 (new-body "") index source-name evaluate prefix blocks-in-buffer
)
2200 (flet ((nb-add (text) (setq new-body
(concat new-body text
)))
2203 (funcall (intern (concat lang
"-mode")))
2204 (comment-region (point) (progn (insert text
) (point)))
2205 (org-babel-trim (buffer-string)))))
2207 (insert body
) (goto-char (point-min))
2208 (setq index
(point))
2209 (while (and (re-search-forward (org-babel-noweb-wrap) nil t
))
2210 (save-match-data (setf source-name
(match-string 1)))
2211 (save-match-data (setq evaluate
(string-match "\(.*\)" source-name
)))
2214 (buffer-substring (match-beginning 0)
2216 (beginning-of-line 1) (point)))))
2217 ;; add interval to new-body (removing noweb reference)
2218 (goto-char (match-beginning 0))
2219 (nb-add (buffer-substring index
(point)))
2220 (goto-char (match-end 0))
2221 (setq index
(point))
2223 (with-current-buffer parent-buffer
2224 (mapconcat ;; interpose PREFIX between every line
2228 (let ((raw (org-babel-ref-resolve source-name
)))
2229 (if (stringp raw
) raw
(format "%S" raw
)))
2231 ;; retrieve from the library of babel
2232 (nth 2 (assoc (intern source-name
)
2233 org-babel-library-of-babel
))
2234 ;; return the contents of headlines literally
2236 (when (org-babel-ref-goto-headline-id source-name
)
2237 (org-babel-ref-headline-body)))
2238 ;; find the expansion of reference in this buffer
2239 (let ((rx (concat rx-prefix source-name
))
2242 (goto-char (point-min))
2243 (if *org-babel-use-quick-and-dirty-noweb-expansion
*
2244 (while (re-search-forward rx nil t
)
2245 (let* ((i (org-babel-get-src-block-info 'light
))
2246 (body (org-babel-expand-noweb-references i
))
2247 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2251 (concat (c-wrap (car cs
)) "\n"
2253 (c-wrap (cadr cs
))))
2254 (org-babel-tangle-comment-links i
))
2256 (setq expansion
(cons sep
(cons full expansion
)))))
2257 (org-babel-map-src-blocks nil
2258 (let ((i (org-babel-get-src-block-info 'light
)))
2259 (when (equal (or (cdr (assoc :noweb-ref
(nth 2 i
)))
2262 (let* ((body (org-babel-expand-noweb-references i
))
2263 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2267 (concat (c-wrap (car cs
)) "\n"
2269 (c-wrap (cadr cs
))))
2270 (org-babel-tangle-comment-links i
))
2273 (cons sep
(cons full expansion
)))))))))
2275 (mapconcat #'identity
(nreverse (cdr expansion
)) "")))
2276 ;; possibly raise an error if named block doesn't exist
2277 (if (member lang org-babel-noweb-error-langs
)
2279 (org-babel-noweb-wrap source-name
)
2280 "could not be resolved (see "
2281 "`org-babel-noweb-error-langs')"))
2283 "[\n\r]") (concat "\n" prefix
)))))
2284 (nb-add (buffer-substring index
(point-max)))))
2287 (defun org-babel-clean-text-properties (text)
2288 "Strip all properties from text return."
2290 (set-text-properties 0 (length text
) nil text
) text
))
2292 (defun org-babel-strip-protective-commas (body)
2293 "Strip protective commas from bodies of source blocks."
2296 (org-strip-protective-commas (point-min) (point-max))
2299 (defun org-babel-script-escape (str &optional force
)
2300 "Safely convert tables into elisp lists."
2301 (let (in-single in-double out
)
2302 ((lambda (escaped) (condition-case nil
(org-babel-read escaped
) (error escaped
)))
2306 (or (and (string-equal "[" (substring str
0 1))
2307 (string-equal "]" (substring str -
1)))
2308 (and (string-equal "{" (substring str
0 1))
2309 (string-equal "}" (substring str -
1)))
2310 (and (string-equal "(" (substring str
0 1))
2311 (string-equal ")" (substring str -
1))))))
2321 (91 (if (or in-double in-single
) ; [
2324 (93 (if (or in-double in-single
) ; ]
2327 (123 (if (or in-double in-single
) ; {
2330 (125 (if (or in-double in-single
) ; }
2333 (44 (if (or in-double in-single
) ; ,
2334 (cons 44 out
) (cons 32 out
)))
2335 (39 (if in-double
; '
2337 (setq in-single
(not in-single
)) (cons 34 out
)))
2338 (34 (if in-single
; "
2339 (append (list 34 32) out
)
2340 (setq in-double
(not in-double
)) (cons 34 out
)))
2341 (t (cons ch out
)))))
2342 (string-to-list str
))
2343 (apply #'string
(reverse out
)))))
2346 (defun org-babel-read (cell &optional inhibit-lisp-eval
)
2347 "Convert the string value of CELL to a number if appropriate.
2348 Otherwise if cell looks like lisp (meaning it starts with a
2349 \"(\", \"'\", \"`\" or a \"[\") then read it as lisp, otherwise
2350 return it unmodified as a string. Optional argument NO-LISP-EVAL
2351 inhibits lisp evaluation for situations in which is it not
2353 (if (and (stringp cell
) (not (equal cell
"")))
2354 (or (org-babel-number-p cell
)
2355 (if (and (not inhibit-lisp-eval
)
2356 (member (substring cell
0 1) '("(" "'" "`" "[")))
2358 (if (string= (substring cell
0 1) "\"")
2360 (progn (set-text-properties 0 (length cell
) nil cell
) cell
))))
2363 (defun org-babel-number-p (string)
2364 "If STRING represents a number return its value."
2365 (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string
)
2366 (= (length (substring string
(match-beginning 0)
2369 (string-to-number string
)))
2371 (defun org-babel-import-elisp-from-file (file-name &optional separator
)
2372 "Read the results located at FILE-NAME into an elisp table.
2373 If the table is trivial, then return it as a scalar."
2375 (save-window-excursion
2379 (org-table-import file-name separator
)
2380 (delete-file file-name
)
2381 (setq result
(mapcar (lambda (row)
2382 (mapcar #'org-babel-string-read row
))
2383 (org-table-to-lisp))))
2385 (if (null (cdr result
)) ;; if result is trivial vector, then scalarize it
2386 (if (consp (car result
))
2387 (if (null (cdr (car result
)))
2393 (defun org-babel-string-read (cell)
2394 "Strip nested \"s from around strings."
2395 (org-babel-read (or (and (stringp cell
)
2396 (string-match "\\\"\\(.+\\)\\\"" cell
)
2397 (match-string 1 cell
))
2400 (defun org-babel-reverse-string (string)
2401 "Return the reverse of STRING."
2402 (apply 'string
(reverse (string-to-list string
))))
2404 (defun org-babel-chomp (string &optional regexp
)
2405 "Strip trailing spaces and carriage returns from STRING.
2406 Default regexp used is \"[ \f\t\n\r\v]\" but can be
2407 overwritten by specifying a regexp as a second argument."
2408 (let ((regexp (or regexp
"[ \f\t\n\r\v]")))
2409 (while (and (> (length string
) 0)
2410 (string-match regexp
(substring string -
1)))
2411 (setq string
(substring string
0 -
1)))
2414 (defun org-babel-trim (string &optional regexp
)
2415 "Strip leading and trailing spaces and carriage returns from STRING.
2416 Like `org-babel-chomp' only it runs on both the front and back
2418 (org-babel-chomp (org-babel-reverse-string
2419 (org-babel-chomp (org-babel-reverse-string string
) regexp
))
2422 (defvar org-babel-org-babel-call-process-region-original nil
)
2423 (defun org-babel-tramp-handle-call-process-region
2424 (start end program
&optional delete buffer display
&rest args
)
2425 "Use tramp to handle call-process-region.
2426 Fixes a bug in `tramp-handle-call-process-region'."
2427 (if (and (featurep 'tramp
) (file-remote-p default-directory
))
2428 (let ((tmpfile (tramp-compat-make-temp-file "")))
2429 (write-region start end tmpfile
)
2430 (when delete
(delete-region start end
))
2432 ;; (apply 'call-process program tmpfile buffer display args)
2434 (apply 'process-file program tmpfile buffer display args
)
2435 (delete-file tmpfile
)))
2436 ;; org-babel-call-process-region-original is the original emacs
2437 ;; definition. It is in scope from the let binding in
2438 ;; org-babel-execute-src-block
2439 (apply org-babel-call-process-region-original
2440 start end program delete buffer display args
)))
2442 (defun org-babel-local-file-name (file)
2443 "Return the local name component of FILE."
2444 (if (file-remote-p file
)
2446 (with-parsed-tramp-file-name file nil
2450 (defun org-babel-process-file-name (name &optional no-quote-p
)
2451 "Prepare NAME to be used in an external process.
2452 If NAME specifies a remote location, the remote portion of the
2453 name is removed, since in that case the process will be executing
2454 remotely. The file name is then processed by
2455 `expand-file-name'. Unless second argument NO-QUOTE-P is non-nil,
2456 the file name is additionally processed by
2457 `shell-quote-argument'"
2458 ((lambda (f) (if no-quote-p f
(shell-quote-argument f
)))
2459 (expand-file-name (org-babel-local-file-name name
))))
2461 (defvar org-babel-temporary-directory
)
2462 (unless (or noninteractive
(boundp 'org-babel-temporary-directory
))
2463 (defvar org-babel-temporary-directory
2464 (or (and (boundp 'org-babel-temporary-directory
)
2465 (file-exists-p org-babel-temporary-directory
)
2466 org-babel-temporary-directory
)
2467 (make-temp-file "babel-" t
))
2468 "Directory to hold temporary files created to execute code blocks.
2469 Used by `org-babel-temp-file'. This directory will be removed on
2472 (defun org-babel-temp-file (prefix &optional suffix
)
2473 "Create a temporary file in the `org-babel-temporary-directory'.
2474 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2475 value of `temporary-file-directory' temporarily set to the value
2476 of `org-babel-temporary-directory'."
2477 (if (file-remote-p default-directory
)
2479 (concat (file-remote-p default-directory
)
2481 prefix temporary-file-directory
)
2483 (let ((temporary-file-directory
2484 (or (and (boundp 'org-babel-temporary-directory
)
2485 (file-exists-p org-babel-temporary-directory
)
2486 org-babel-temporary-directory
)
2487 temporary-file-directory
)))
2488 (make-temp-file prefix nil suffix
))))
2490 (defun org-babel-remove-temporary-directory ()
2491 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2492 (when (and (boundp 'org-babel-temporary-directory
)
2493 (file-exists-p org-babel-temporary-directory
))
2494 ;; taken from `delete-directory' in files.el
2497 (mapc (lambda (file)
2498 ;; This test is equivalent to
2499 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2500 ;; but more efficient
2501 (if (eq t
(car (file-attributes file
)))
2502 (delete-directory file
)
2503 (delete-file file
)))
2504 ;; We do not want to delete "." and "..".
2505 (directory-files org-babel-temporary-directory
'full
2506 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2507 (delete-directory org-babel-temporary-directory
))
2509 (message "Failed to remove temporary Org-babel directory %s"
2510 (if (boundp 'org-babel-temporary-directory
)
2511 org-babel-temporary-directory
2512 "[directory not defined]"))))))
2514 (add-hook 'kill-emacs-hook
'org-babel-remove-temporary-directory
)