1 ;;; ob-core.el --- Working with Code Blocks -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2009-2018 Free Software Foundation, Inc.
5 ;; Authors: Eric Schulte
7 ;; Keywords: literate programming, reproducible research
8 ;; Homepage: https://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 <https://www.gnu.org/licenses/>.
31 (defconst org-babel-exeext
32 (if (memq system-type
'(windows-nt cygwin
))
36 (defvar org-babel-library-of-babel
)
37 (defvar org-edit-src-content-indentation
)
38 (defvar org-link-file-path-type
)
39 (defvar org-src-lang-modes
)
40 (defvar org-src-preserve-indentation
)
42 (declare-function org-at-item-p
"org-list" ())
43 (declare-function org-at-table-p
"org" (&optional table-type
))
44 (declare-function org-babel-lob-execute-maybe
"ob-lob" ())
45 (declare-function org-babel-ref-goto-headline-id
"ob-ref" (id))
46 (declare-function org-babel-ref-headline-body
"ob-ref" ())
47 (declare-function org-babel-ref-parse
"ob-ref" (assignment))
48 (declare-function org-babel-ref-resolve
"ob-ref" (ref))
49 (declare-function org-babel-ref-split-args
"ob-ref" (arg-string))
50 (declare-function org-babel-tangle-comment-links
"ob-tangle" (&optional info
))
51 (declare-function org-current-level
"org" ())
52 (declare-function org-cycle
"org" (&optional arg
))
53 (declare-function org-edit-src-code
"org-src" (&optional code edit-buffer-name
))
54 (declare-function org-edit-src-exit
"org-src" ())
55 (declare-function org-element-at-point
"org-element" ())
56 (declare-function org-element-context
"org-element" (&optional element
))
57 (declare-function org-element-normalize-string
"org-element" (s))
58 (declare-function org-element-property
"org-element" (property element
))
59 (declare-function org-element-type
"org-element" (element))
60 (declare-function org-entry-get
"org" (pom property
&optional inherit literal-nil
))
61 (declare-function org-escape-code-in-region
"org-src" (beg end
))
62 (declare-function org-indent-line
"org" ())
63 (declare-function org-list-get-list-end
"org-list" (item struct prevs
))
64 (declare-function org-list-prevs-alist
"org-list" (struct))
65 (declare-function org-list-struct
"org-list" ())
66 (declare-function org-list-to-generic
"org-list" (LIST PARAMS
))
67 (declare-function org-list-to-lisp
"org-list" (&optional delete
))
68 (declare-function org-macro-escape-arguments
"org-macro" (&rest args
))
69 (declare-function org-make-options-regexp
"org" (kwds &optional extra
))
70 (declare-function org-mark-ring-push
"org" (&optional pos buffer
))
71 (declare-function org-narrow-to-subtree
"org" ())
72 (declare-function org-next-block
"org" (arg &optional backward block-regexp
))
73 (declare-function org-open-at-point
"org" (&optional in-emacs reference-buffer
))
74 (declare-function org-previous-block
"org" (arg &optional block-regexp
))
75 (declare-function org-show-context
"org" (&optional key
))
76 (declare-function org-src-coderef-format
"org-src" (&optional element
))
77 (declare-function org-src-coderef-regexp
"org-src" (fmt &optional label
))
78 (declare-function org-table-align
"org-table" ())
79 (declare-function org-table-end
"org-table" (&optional table-type
))
80 (declare-function org-table-import
"org-table" (file arg
))
81 (declare-function org-table-to-lisp
"org-table" (&optional txt
))
82 (declare-function org-unescape-code-in-string
"org-src" (s))
83 (declare-function orgtbl-to-generic
"org-table" (table params
))
84 (declare-function orgtbl-to-orgtbl
"org-table" (table params
))
85 (declare-function tramp-compat-make-temp-file
"tramp-compat" (filename &optional dir-flag
))
87 (defgroup org-babel nil
88 "Code block evaluation and management in `org-mode' documents."
92 (defcustom org-confirm-babel-evaluate t
93 "Confirm before evaluation.
95 Require confirmation before interactively evaluating code
96 blocks in Org buffers. The default value of this variable is t,
97 meaning confirmation is required for any code block evaluation.
98 This variable can be set to nil to inhibit any future
99 confirmation requests. This variable can also be set to a
100 function which takes two arguments the language of the code block
101 and the body of the code block. Such a function should then
102 return a non-nil value if the user should be prompted for
103 execution or nil if no prompt is required.
105 Warning: Disabling confirmation may result in accidental
106 evaluation of potentially harmful code. It may be advisable
107 remove code block execution from `\\[org-ctrl-c-ctrl-c]' \
108 as further protection
109 against accidental code block evaluation. The
110 `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
111 remove code block execution from the `\\[org-ctrl-c-ctrl-c]' keybinding."
114 :type
'(choice boolean function
))
115 ;; don't allow this variable to be changed through file settings
116 (put 'org-confirm-babel-evaluate
'safe-local-variable
(lambda (x) (eq x t
)))
118 (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
120 Remove code block evaluation from the `\\[org-ctrl-c-ctrl-c]' key binding."
125 (defcustom org-babel-results-keyword
"RESULTS"
126 "Keyword used to name results generated by code blocks.
127 It should be \"RESULTS\". However any capitalization may be
131 :package-version
'(Org .
"8.0")
135 (eq (compare-strings "RESULTS" nil nil v nil nil t
)
138 (defcustom org-babel-noweb-wrap-start
"<<"
139 "String used to begin a noweb reference in a code block.
140 See also `org-babel-noweb-wrap-end'."
144 (defcustom org-babel-noweb-wrap-end
">>"
145 "String used to end a noweb reference in a code block.
146 See also `org-babel-noweb-wrap-start'."
150 (defcustom org-babel-inline-result-wrap
"=%s="
151 "Format string used to wrap inline results.
152 This string must include a \"%s\" which will be replaced by the results."
155 (put 'org-babel-inline-result-wrap
159 (string-match-p "%s" value
))))
161 (defcustom org-babel-hash-show-time nil
162 "Non-nil means show the time the code block was evaluated in the result hash."
166 :package-version
'(Org .
"9.0")
169 (defcustom org-babel-uppercase-example-markers nil
170 "When non-nil, begin/end example markers will be inserted in upper case."
174 :package-version
'(Org .
"9.1")
177 (defun org-babel-noweb-wrap (&optional regexp
)
178 (concat org-babel-noweb-wrap-start
179 (or regexp
"\\([^ \t\n].+?[^ \t]\\|[^ \t\n]\\)")
180 org-babel-noweb-wrap-end
))
182 (defvar org-babel-src-name-regexp
183 "^[ \t]*#\\+name:[ \t]*"
184 "Regular expression used to match a source name line.")
186 (defvar org-babel-multi-line-header-regexp
187 "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
188 "Regular expression used to match multi-line header arguments.")
190 (defvar org-babel-src-block-regexp
192 ;; (1) indentation (2) lang
193 "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
195 "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
196 ;; (4) header arguments
199 "\\([^\000]*?\n\\)??[ \t]*#\\+end_src")
200 "Regexp used to identify code blocks.")
202 (defun org-babel--get-vars (params)
203 "Return the babel variable assignments in PARAMS.
205 PARAMS is a quasi-alist of header args, which may contain
206 multiple entries for the key `:var'. This function returns a
207 list of the cdr of all the `:var' entries."
209 (cl-remove-if-not (lambda (x) (eq (car x
) :var
)) params
)))
211 (defvar org-babel-exp-reference-buffer nil
212 "Buffer containing original contents of the exported buffer.
213 This is used by Babel to resolve references in source blocks.
214 Its value is dynamically bound during export.")
216 (defun org-babel-check-confirm-evaluate (info)
217 "Check whether INFO allows code block evaluation.
219 Returns nil if evaluation is disallowed, t if it is
220 unconditionally allowed, and the symbol `query' if the user
221 should be asked whether to allow evaluation."
222 (let* ((headers (nth 2 info
))
223 (eval (or (cdr (assq :eval headers
))
224 (when (assq :noeval headers
) "no")))
225 (eval-no (member eval
'("no" "never")))
226 (export org-babel-exp-reference-buffer
)
227 (eval-no-export (and export
(member eval
'("no-export" "never-export"))))
228 (noeval (or eval-no eval-no-export
))
229 (query (or (equal eval
"query")
230 (and export
(equal eval
"query-export"))
231 (if (functionp org-confirm-babel-evaluate
)
232 (funcall org-confirm-babel-evaluate
233 ;; Language, code block body.
234 (nth 0 info
) (nth 1 info
))
235 org-confirm-babel-evaluate
))))
241 (defun org-babel-check-evaluate (info)
242 "Check if code block INFO should be evaluated.
243 Do not query the user, but do display an informative message if
244 evaluation is blocked. Returns non-nil if evaluation is not blocked."
245 (let ((confirmed (org-babel-check-confirm-evaluate info
)))
247 (message "Evaluation of this %s code block%sis disabled."
249 (let ((name (nth 4 info
)))
250 (if name
(format " (%s) " name
) " "))))
253 ;; Dynamically scoped for asynchronous export.
254 (defvar org-babel-confirm-evaluate-answer-no
)
256 (defun org-babel-confirm-evaluate (info)
257 "Confirm evaluation of the code block INFO.
259 This query can also be suppressed by setting the value of
260 `org-confirm-babel-evaluate' to nil, in which case all future
261 interactive code block evaluations will proceed without any
262 confirmation from the user.
264 Note disabling confirmation may result in accidental evaluation
265 of potentially harmful code.
267 The variable `org-babel-confirm-evaluate-answer-no' is used by
268 the async export process, which requires a non-interactive
269 environment, to override this check."
270 (let* ((evalp (org-babel-check-confirm-evaluate info
))
273 (name-string (if name
(format " (%s) " name
) " ")))
278 (and (not (bound-and-true-p
279 org-babel-confirm-evaluate-answer-no
))
281 (format "Evaluate this %s code block%son your system? "
284 (message "Evaluation of this %s code block%sis aborted."
287 (x (error "Unexpected value `%s' from `org-babel-check-confirm-evaluate'" x
)))))
290 (defun org-babel-execute-safely-maybe ()
291 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
292 (org-babel-execute-maybe)))
295 (defun org-babel-execute-maybe ()
297 (or (org-babel-execute-src-block-maybe)
298 (org-babel-lob-execute-maybe)))
300 (defmacro org-babel-when-in-src-block
(&rest body
)
301 "Execute BODY if point is in a source block and return t.
303 Otherwise do nothing and return nil."
304 `(if (memq (org-element-type (org-element-context))
305 '(inline-src-block src-block
))
311 (defun org-babel-execute-src-block-maybe ()
312 "Conditionally execute a source block.
313 Detect if this is context for a Babel src-block and if so
314 then run `org-babel-execute-src-block'."
316 (org-babel-when-in-src-block
317 (org-babel-eval-wipe-error-buffer)
318 (org-babel-execute-src-block current-prefix-arg
)))
321 (defun org-babel-view-src-block-info ()
322 "Display information on the current source block.
323 This includes header arguments, language and name, and is largely
324 a window into the `org-babel-get-src-block-info' function."
326 (let ((info (org-babel-get-src-block-info 'light
))
327 (full (lambda (it) (> (length it
) 0)))
328 (printf (lambda (fmt &rest args
) (princ (apply #'format fmt args
)))))
330 (with-help-window (help-buffer)
331 (let ((name (nth 4 info
))
333 (switches (nth 3 info
))
334 (header-args (nth 2 info
)))
335 (when name
(funcall printf
"Name: %s\n" name
))
336 (when lang
(funcall printf
"Lang: %s\n" lang
))
337 (funcall printf
"Properties:\n")
338 (funcall printf
"\t:header-args \t%s\n" (org-entry-get (point) "header-args" t
))
339 (funcall printf
"\t:header-args:%s \t%s\n" lang
(org-entry-get (point) (concat "header-args:" lang
) t
))
341 (when (funcall full switches
) (funcall printf
"Switches: %s\n" switches
))
342 (funcall printf
"Header Arguments:\n")
343 (dolist (pair (sort header-args
344 (lambda (a b
) (string< (symbol-name (car a
))
345 (symbol-name (car b
))))))
346 (when (funcall full
(format "%s" (cdr pair
)))
347 (funcall printf
"\t%S%s\t%s\n"
349 (if (> (length (format "%S" (car pair
))) 7) "" "\t")
353 (defun org-babel-expand-src-block-maybe ()
354 "Conditionally expand a source block.
355 Detect if this is context for an org-babel src-block and if so
356 then run `org-babel-expand-src-block'."
358 (org-babel-when-in-src-block
359 (org-babel-expand-src-block current-prefix-arg
)))
362 (defun org-babel-load-in-session-maybe ()
363 "Conditionally load a source block in a session.
364 Detect if this is context for an org-babel src-block and if so
365 then run `org-babel-load-in-session'."
367 (org-babel-when-in-src-block
368 (org-babel-load-in-session current-prefix-arg
)))
370 (add-hook 'org-metaup-hook
'org-babel-load-in-session-maybe
)
373 (defun org-babel-pop-to-session-maybe ()
374 "Conditionally pop to a session.
375 Detect if this is context for an org-babel src-block and if so
376 then run `org-babel-switch-to-session'."
378 (org-babel-when-in-src-block
379 (org-babel-switch-to-session current-prefix-arg
)))
381 (add-hook 'org-metadown-hook
'org-babel-pop-to-session-maybe
)
383 (defconst org-babel-common-header-args-w-values
384 '((cache .
((no yes
)))
386 (colnames .
((nil no yes
)))
387 (comments .
((no link yes org both noweb
)))
389 (eval .
((yes no no-export strip-export never-export eval never
391 (exports .
((code results both none
)))
396 (hlines .
((no yes
)))
397 (mkdirp .
((yes no
)))
400 (noweb .
((yes no tangle no-export strip-export
)))
404 (padline .
((yes no
)))
407 (results .
((file list vector table scalar verbatim
)
408 (raw html latex org code pp drawer link graphics
)
409 (replace silent none append prepend
)
411 (rownames .
((no yes
)))
415 (tangle .
((tangle yes no
:any
)))
416 (tangle-mode .
((#o755
#o555
#o444
:any
)))
420 (defconst org-babel-header-arg-names
421 (mapcar #'car org-babel-common-header-args-w-values
)
422 "Common header arguments used by org-babel.
423 Note that individual languages may define their own language
424 specific header arguments as well.")
426 (defconst org-babel-safe-header-args
427 '(:cache
:colnames
:comments
:exports
:epilogue
:hlines
:noeval
428 :noweb
:noweb-ref
:noweb-sep
:padline
:prologue
:rownames
429 :sep
:session
:tangle
:wrap
430 (:eval .
("never" "query"))
431 (:results .
(lambda (str) (not (string-match "file" str
)))))
432 "A list of safe header arguments for babel source blocks.
434 The list can have entries of the following forms:
435 - :ARG -> :ARG is always a safe header arg
436 - (:ARG . (VAL1 VAL2 ...)) -> :ARG is safe as a header arg if it is
437 `equal' to one of the VALs.
438 - (:ARG . FN) -> :ARG is safe as a header arg if the function FN
439 returns non-nil. FN is passed one
440 argument, the value of the header arg
443 (defmacro org-babel-header-args-safe-fn
(safe-list)
444 "Return a function that determines whether a list of header args are safe.
447 \(put \\='org-babel-default-header-args \\='safe-local-variable
448 (org-babel-header-args-safe-p org-babel-safe-header-args)
450 This allows org-babel languages to extend the list of safe values for
451 their `org-babel-default-header-args:foo' variable.
453 For the format of SAFE-LIST, see `org-babel-safe-header-args'."
459 (org-babel-one-header-arg-safe-p pair
,safe-list
)))
462 (defvar org-babel-default-header-args
463 '((:session .
"none") (:results .
"replace") (:exports .
"code")
464 (:cache .
"no") (:noweb .
"no") (:hlines .
"no") (:tangle .
"no"))
465 "Default arguments to use when evaluating a source block.")
466 (put 'org-babel-default-header-args
'safe-local-variable
467 (org-babel-header-args-safe-fn org-babel-safe-header-args
))
469 (defvar org-babel-default-inline-header-args
470 '((:session .
"none") (:results .
"replace")
471 (:exports .
"results") (:hlines .
"yes"))
472 "Default arguments to use when evaluating an inline source block.")
473 (put 'org-babel-default-inline-header-args
'safe-local-variable
474 (org-babel-header-args-safe-fn org-babel-safe-header-args
))
476 (defconst org-babel-name-regexp
477 (format "^[ \t]*#\\+%s:[ \t]*"
478 ;; FIXME: TBLNAME is for backward compatibility.
479 (regexp-opt '("NAME" "TBLNAME")))
480 "Regexp matching a NAME keyword.")
482 (defconst org-babel-result-regexp
483 (format "^[ \t]*#\\+%s\\(?:\\[\\(?:%s \\)?\\([[:alnum:]]+\\)\\]\\)?:[ \t]*"
484 org-babel-results-keyword
485 ;; <%Y-%m-%d %H:%M:%S>
486 "<\\(?:[0-9]\\{4\\}-[0-1][0-9]-[0-3][0-9] \
487 [0-2][0-9]\\(?::[0-5][0-9]\\)\\{2\\}\\)>")
488 "Regular expression used to match result lines.
489 If the results are associated with a hash key then the hash will
490 be saved in match group 1.")
492 (defconst org-babel-result-w-name-regexp
493 (concat org-babel-result-regexp
"\\(?9:[^ \t\n\r\v\f]+\\)")
494 "Regexp matching a RESULTS keyword with a name.
495 Name is saved in match group 9.")
497 (defvar org-babel-min-lines-for-block-output
10
498 "The minimum number of lines for block output.
499 If number of lines of output is equal to or exceeds this
500 value, the output is placed in a #+begin_example...#+end_example
501 block. Otherwise the output is marked as literal by inserting
502 colons at the starts of the lines. This variable only takes
503 effect if the :results output option is in effect.")
505 (defvar org-babel-noweb-error-all-langs nil
506 "Raise errors when noweb references don't resolve.
507 Also see `org-babel-noweb-error-langs' to control noweb errors on
508 a language by language bases.")
510 (defvar org-babel-noweb-error-langs nil
511 "Languages for which Babel will raise literate programming errors.
512 List of languages for which errors should be raised when the
513 source code block satisfying a noweb reference in this language
514 can not be resolved. Also see `org-babel-noweb-error-all-langs'
515 to raise errors for all languages.")
517 (defvar org-babel-hash-show
4
518 "Number of initial characters to show of a hidden results hash.")
520 (defvar org-babel-after-execute-hook nil
521 "Hook for functions to be called after `org-babel-execute-src-block'")
523 (defun org-babel-named-src-block-regexp-for-name (&optional name
)
524 "This generates a regexp used to match a src block named NAME.
525 If NAME is nil, match any name. Matched name is then put in
526 match group 9. Other match groups are defined in
527 `org-babel-src-block-regexp'."
528 (concat org-babel-src-name-regexp
529 (concat (if name
(regexp-quote name
) "\\(?9:.*?\\)") "[ \t]*" )
530 "\\(?:\n[ \t]*#\\+\\S-+:.*\\)*?"
532 (substring org-babel-src-block-regexp
1)))
534 (defun org-babel-named-data-regexp-for-name (name)
535 "This generates a regexp used to match data named NAME."
536 (concat org-babel-name-regexp
(regexp-quote name
) "[ \t]*$"))
538 (defun org-babel--normalize-body (datum)
539 "Normalize body for element or object DATUM.
540 DATUM is a source block element or an inline source block object.
541 Remove final newline character and spurious indentation."
542 (let* ((value (org-element-property :value datum
))
543 (body (if (string-suffix-p "\n" value
)
544 (substring value
0 -
1)
546 (cond ((eq (org-element-type datum
) 'inline-src-block
)
547 ;; Newline characters and indentation in an inline
548 ;; src-block are not meaningful, since they could come from
549 ;; some paragraph filling. Treat them as a white space.
550 (replace-regexp-in-string "\n[ \t]*" " " body
))
551 ((or org-src-preserve-indentation
552 (org-element-property :preserve-indent datum
))
554 (t (org-remove-indentation body
)))))
557 (defvar org-babel-current-src-block-location nil
558 "Marker pointing to the src block currently being executed.
559 This may also point to a call line or an inline code block. If
560 multiple blocks are being executed (e.g., in chained execution
561 through use of the :var header argument) this marker points to
562 the outer-most code block.")
566 (defun org-babel-get-src-block-info (&optional light datum
)
567 "Extract information from a source block or inline source block.
569 When optional argument LIGHT is non-nil, Babel does not resolve
570 remote variable references; a process which could likely result
571 in the execution of other code blocks, and do not evaluate Lisp
572 values in parameters.
574 By default, consider the block at point. However, when optional
575 argument DATUM is provided, extract information from that parsed
578 Return nil if point is not on a source block. Otherwise, return
579 a list with the following pattern:
581 (language body arguments switches name start coderef)"
582 (let* ((datum (or datum
(org-element-context)))
583 (type (org-element-type datum
))
584 (inline (eq type
'inline-src-block
)))
585 (when (memq type
'(inline-src-block src-block
))
586 (let* ((lang (org-element-property :language datum
))
587 (lang-headers (intern
588 (concat "org-babel-default-header-args:" lang
)))
589 (name (org-element-property :name datum
))
593 (org-babel--normalize-body datum
)
594 (apply #'org-babel-merge-params
595 (if inline org-babel-default-inline-header-args
596 org-babel-default-header-args
)
597 (and (boundp lang-headers
) (eval lang-headers t
))
599 ;; If DATUM is provided, make sure we get node
600 ;; properties applicable to its location within
602 (org-with-point-at (org-element-property :begin datum
)
603 (org-babel-params-from-properties lang light
))
605 (org-babel-parse-header-arguments h light
))
606 (cons (org-element-property :parameters datum
)
607 (org-element-property :header datum
)))))
608 (or (org-element-property :switches datum
) "")
610 (org-element-property (if inline
:begin
:post-affiliated
)
612 (and (not inline
) (org-src-coderef-format datum
)))))
614 (setf (nth 2 info
) (org-babel-process-params (nth 2 info
))))
615 (setf (nth 2 info
) (org-babel-generate-file-param name
(nth 2 info
)))
619 (defun org-babel-execute-src-block (&optional arg info params
)
620 "Execute the current source code block.
621 Insert the results of execution into the buffer. Source code
622 execution and the collection and formatting of results can be
623 controlled through a variety of header arguments.
625 With prefix argument ARG, force re-execution even if an existing
626 result cached in the buffer would otherwise have been returned.
628 Optionally supply a value for INFO in the form returned by
629 `org-babel-get-src-block-info'.
631 Optionally supply a value for PARAMS which will be merged with
632 the header arguments specified at the front of the source code
635 (let* ((org-babel-current-src-block-location
636 (or org-babel-current-src-block-location
638 (org-babel-where-is-src-block-head)))
639 (info (if info
(copy-tree info
) (org-babel-get-src-block-info))))
640 ;; Merge PARAMS with INFO before considering source block
641 ;; evaluation since both could disagree.
642 (cl-callf org-babel-merge-params
(nth 2 info
) params
)
643 (when (org-babel-check-evaluate info
)
644 (cl-callf org-babel-process-params
(nth 2 info
))
645 (let* ((params (nth 2 info
))
646 (cache (let ((c (cdr (assq :cache params
))))
647 (and (not arg
) c
(string= "yes" c
))))
648 (new-hash (and cache
(org-babel-sha1-hash info
)))
649 (old-hash (and cache
(org-babel-current-result-hash)))
650 (current-cache (and new-hash
(equal new-hash old-hash
))))
653 (save-excursion ;Return cached result.
654 (goto-char (org-babel-where-is-src-block-result nil info
))
656 (skip-chars-forward " \t")
657 (let ((result (org-babel-read-result)))
658 (message (replace-regexp-in-string "%" "%%" (format "%S" result
)))
660 ((org-babel-confirm-evaluate info
)
661 (let* ((lang (nth 0 info
))
662 (result-params (cdr (assq :result-params params
)))
663 ;; Expand noweb references in BODY and remove any
666 (let ((coderef (nth 6 info
))
668 (if (org-babel-noweb-p params
:eval
)
669 (org-babel-expand-noweb-references info
)
671 (if (not coderef
) expand
672 (replace-regexp-in-string
673 (org-src-coderef-regexp coderef
) "" expand nil nil
1))))
674 (dir (cdr (assq :dir params
)))
676 (or (and dir
(file-name-as-directory (expand-file-name dir
)))
678 (cmd (intern (concat "org-babel-execute:" lang
)))
680 (unless (fboundp cmd
)
681 (error "No org-babel-execute function for %s!" lang
))
682 (message "executing %s code block%s..."
684 (let ((name (nth 4 info
)))
685 (if name
(format " (%s)" name
) "")))
686 (if (member "none" result-params
)
687 (progn (funcall cmd body params
)
688 (message "result silenced"))
690 (let ((r (funcall cmd body params
)))
691 (if (and (eq (cdr (assq :result-type params
)) 'value
)
692 (or (member "vector" result-params
)
693 (member "table" result-params
))
697 (let ((file (cdr (assq :file params
))))
698 ;; If non-empty result and :file then write to :file.
700 ;; If `:results' are special types like `link' or
701 ;; `graphics', don't write result to `:file'. Only
702 ;; insert a link to `:file'.
704 (not (or (member "link" result-params
)
705 (member "graphics" result-params
))))
707 (insert (org-babel-format-result
709 (cdr (assq :sep params
))))))
711 ;; Possibly perform post process provided its
712 ;; appropriate. Dynamically bind "*this*" to the
713 ;; actual results of the block.
714 (let ((post (cdr (assq :post params
))))
716 (let ((*this
* (if (not file
) result
717 (org-babel-result-to-file
719 (let ((desc (assq :file-desc params
)))
720 (and desc
(or (cdr desc
) result
)))))))
721 (setq result
(org-babel-ref-resolve post
))
723 (setq result-params
(remove "file" result-params
))))))
724 (org-babel-insert-result
725 result result-params info new-hash lang
)))
726 (run-hooks 'org-babel-after-execute-hook
)
729 (defun org-babel-expand-body:generic
(body params
&optional var-lines
)
730 "Expand BODY with PARAMS.
731 Expand a block of code with org-babel according to its header
732 arguments. This generic implementation of body expansion is
733 called for languages which have not defined their own specific
734 org-babel-expand-body:lang function."
735 (let ((pro (cdr (assq :prologue params
)))
736 (epi (cdr (assq :epilogue params
))))
737 (mapconcat #'identity
738 (append (when pro
(list pro
))
741 (when epi
(list epi
)))
745 (defun org-babel-expand-src-block (&optional _arg info params
)
746 "Expand the current source code block.
747 Expand according to the source code block's header
748 arguments and pop open the results in a preview buffer."
750 (let* ((info (or info
(org-babel-get-src-block-info)))
752 (params (setf (nth 2 info
)
753 (sort (org-babel-merge-params (nth 2 info
) params
)
754 (lambda (el1 el2
) (string< (symbol-name (car el1
))
755 (symbol-name (car el2
)))))))
756 (body (setf (nth 1 info
)
757 (if (org-babel-noweb-p params
:eval
)
758 (org-babel-expand-noweb-references info
) (nth 1 info
))))
759 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
760 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
763 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
764 (org-babel-expand-body:generic
765 body params
(and (fboundp assignments-cmd
)
766 (funcall assignments-cmd params
))))))
767 (if (called-interactively-p 'any
)
769 expanded
(concat "*Org-Babel Preview " (buffer-name) "[ " lang
" ]*"))
772 (defun org-babel-edit-distance (s1 s2
)
773 "Return the edit (levenshtein) distance between strings S1 S2."
774 (let* ((l1 (length s1
))
776 (dist (vconcat (mapcar (lambda (_) (make-vector (1+ l2
) nil
))
777 (number-sequence 1 (1+ l1
)))))
778 (in (lambda (i j
) (aref (aref dist i
) j
))))
779 (setf (aref (aref dist
0) 0) 0)
780 (dolist (j (number-sequence 1 l2
))
781 (setf (aref (aref dist
0) j
) j
))
782 (dolist (i (number-sequence 1 l1
))
783 (setf (aref (aref dist i
) 0) i
)
784 (dolist (j (number-sequence 1 l2
))
785 (setf (aref (aref dist i
) j
)
787 (1+ (funcall in
(1- i
) j
))
788 (1+ (funcall in i
(1- j
)))
789 (+ (if (equal (aref s1
(1- i
)) (aref s2
(1- j
))) 0 1)
790 (funcall in
(1- i
) (1- j
)))))))
793 (defun org-babel-combine-header-arg-lists (original &rest others
)
794 "Combine a number of lists of header argument names and arguments."
795 (let ((results (copy-sequence original
)))
796 (dolist (new-list others
)
797 (dolist (arg-pair new-list
)
798 (let ((header (car arg-pair
)))
800 (cons arg-pair
(cl-remove-if
801 (lambda (pair) (equal header
(car pair
)))
806 (defun org-babel-check-src-block ()
807 "Check for misspelled header arguments in the current code block."
809 ;; TODO: report malformed code block
810 ;; TODO: report incompatible combinations of header arguments
811 ;; TODO: report uninitialized variables
812 (let ((too-close 2) ;; <- control closeness to report potential match
813 (names (mapcar #'symbol-name org-babel-header-arg-names
)))
814 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg
)) 1))
815 (and (org-babel-where-is-src-block-head)
816 (org-babel-parse-header-arguments
818 (match-string 4))))))
820 (when (and (not (string= header name
))
821 (<= (org-babel-edit-distance header name
) too-close
)
822 (not (member header names
)))
823 (error "Supplied header \"%S\" is suspiciously close to \"%S\""
825 (message "No suspicious header arguments found.")))
828 (defun org-babel-insert-header-arg (&optional header-arg value
)
829 "Insert a header argument selecting from lists of common args and values."
831 (let* ((info (org-babel-get-src-block-info 'light
))
834 (lang-headers (intern (concat "org-babel-header-args:" lang
)))
835 (headers (org-babel-combine-header-arg-lists
836 org-babel-common-header-args-w-values
837 (when (boundp lang-headers
) (eval lang-headers t
))))
838 (header-arg (or header-arg
842 (lambda (header-spec) (symbol-name (car header-spec
)))
844 (vals (cdr (assoc (intern header-arg
) headers
)))
848 (read-from-minibuffer "value: "))
852 (let ((arg (completing-read
855 (mapcar #'symbol-name group
)))))
856 (if (and arg
(not (string= "default" arg
)))
862 (goto-char (point-at-eol))
863 (unless (= (char-before (point)) ?\
) (insert " "))
864 (insert ":" header-arg
) (when value
(insert " " value
)))))
866 ;; Add support for completing-read insertion of header arguments after ":"
867 (defun org-babel-header-arg-expand ()
868 "Call `org-babel-enter-header-arg-w-completion' in appropriate contexts."
869 (when (and (equal (char-before) ?\
:) (org-babel-where-is-src-block-head))
870 (org-babel-enter-header-arg-w-completion (match-string 2))))
872 (defun org-babel-enter-header-arg-w-completion (&optional lang
)
873 "Insert header argument appropriate for LANG with completion."
874 (let* ((lang-headers-var (intern (concat "org-babel-header-args:" lang
)))
875 (lang-headers (when (boundp lang-headers-var
) (eval lang-headers-var t
)))
876 (headers-w-values (org-babel-combine-header-arg-lists
877 org-babel-common-header-args-w-values lang-headers
))
878 (headers (mapcar #'symbol-name
(mapcar #'car headers-w-values
)))
879 (header (org-completing-read "Header Arg: " headers
))
880 (args (cdr (assoc (intern header
) headers-w-values
)))
881 (arg (when (and args
(listp args
))
883 (format "%s: " header
)
884 (mapcar #'symbol-name
(apply #'append args
))))))
885 (insert (concat header
" " (or arg
"")))
888 (add-hook 'org-tab-first-hook
'org-babel-header-arg-expand
)
891 (defun org-babel-load-in-session (&optional _arg info
)
892 "Load the body of the current source-code block.
893 Evaluate the header arguments for the source block before
894 entering the session. After loading the body this pops open the
897 (let* ((info (or info
(org-babel-get-src-block-info)))
899 (params (nth 2 info
))
901 (user-error "No src code block at point")
903 (if (org-babel-noweb-p params
:eval
)
904 (org-babel-expand-noweb-references info
)
906 (session (cdr (assq :session params
)))
907 (dir (cdr (assq :dir params
)))
909 (or (and dir
(file-name-as-directory dir
)) default-directory
))
910 (cmd (intern (concat "org-babel-load-session:" lang
))))
911 (unless (fboundp cmd
)
912 (error "No org-babel-load-session function for %s!" lang
))
913 (pop-to-buffer (funcall cmd session body params
))
917 (defun org-babel-initiate-session (&optional arg info
)
918 "Initiate session for current code block.
919 If called with a prefix argument then resolve any variable
920 references in the header arguments and assign these variables in
921 the session. Copy the body of the code block to the kill ring."
923 (let* ((info (or info
(org-babel-get-src-block-info (not arg
))))
926 (params (nth 2 info
))
927 (session (cdr (assq :session params
)))
928 (dir (cdr (assq :dir params
)))
930 (or (and dir
(file-name-as-directory dir
)) default-directory
))
931 (init-cmd (intern (format "org-babel-%s-initiate-session" lang
)))
932 (prep-cmd (intern (concat "org-babel-prep-session:" lang
))))
933 (when (and (stringp session
) (string= session
"none"))
934 (error "This block is not using a session!"))
935 (unless (fboundp init-cmd
)
936 (error "No org-babel-initiate-session function for %s!" lang
))
937 (with-temp-buffer (insert (org-trim body
))
938 (copy-region-as-kill (point-min) (point-max)))
940 (unless (fboundp prep-cmd
)
941 (error "No org-babel-prep-session function for %s!" lang
))
942 (funcall prep-cmd session params
))
943 (funcall init-cmd session params
)))
946 (defun org-babel-switch-to-session (&optional arg info
)
947 "Switch to the session of the current code block.
948 Uses `org-babel-initiate-session' to start the session. If called
949 with a prefix argument then this is passed on to
950 `org-babel-initiate-session'."
952 (pop-to-buffer (org-babel-initiate-session arg info
))
955 (defalias 'org-babel-pop-to-session
'org-babel-switch-to-session
)
957 (defvar org-src-window-setup
)
960 (defun org-babel-switch-to-session-with-code (&optional arg _info
)
961 "Switch to code buffer and display session."
965 (let ((other-window-buffer (window-buffer (next-window))))
966 (set-window-buffer (next-window) (current-buffer))
967 (set-window-buffer (selected-window) other-window-buffer
))
969 (info (org-babel-get-src-block-info))
970 (org-src-window-setup 'reorganize-frame
))
972 (org-babel-switch-to-session arg info
))
974 (funcall swap-windows
)))
977 (defmacro org-babel-do-in-edit-buffer
(&rest body
)
978 "Evaluate BODY in edit buffer if there is a code block at point.
979 Return t if a code block was found at point, nil otherwise."
980 (declare (debug (body)))
981 `(let* ((element (org-element-at-point))
982 ;; This function is not supposed to move point. However,
983 ;; `org-edit-src-code' always moves point back into the
984 ;; source block. It is problematic if the point was before
985 ;; the code, e.g., on block's opening line. In this case,
986 ;; we want to restore this location after executing BODY.
988 (and (<= (line-beginning-position)
989 (org-element-property :post-affiliated element
))
991 (org-src-window-setup 'switch-invisibly
))
992 (when (and (org-babel-where-is-src-block-head element
)
994 (unwind-protect (progn ,@body
)
996 (when outside-position
(goto-char outside-position
)))
999 (defun org-babel-do-key-sequence-in-edit-buffer (key)
1000 "Read key sequence and execute the command in edit buffer.
1001 Enter a key sequence to be executed in the language major-mode
1002 edit buffer. For example, TAB will alter the contents of the
1003 Org code block according to the effect of TAB in the language
1004 major mode buffer. For languages that support interactive
1005 sessions, this can be used to send code from the Org buffer
1006 to the session for evaluation using the native major mode
1007 evaluation mechanisms."
1008 (interactive "kEnter key-sequence to execute in edit buffer: ")
1009 (org-babel-do-in-edit-buffer
1011 (key-binding (or key
(read-key-sequence nil
))))))
1013 (defvar org-bracket-link-regexp
)
1015 (defun org-babel-active-location-p ()
1016 (memq (org-element-type (save-match-data (org-element-context)))
1017 '(babel-call inline-babel-call inline-src-block src-block
)))
1020 (defun org-babel-open-src-block-result (&optional re-run
)
1021 "If `point' is on a src block then open the results of the
1022 source code block, otherwise return nil. With optional prefix
1023 argument RE-RUN the source-code block is evaluated even if
1024 results already exist."
1026 (let ((info (org-babel-get-src-block-info 'light
)))
1029 ;; go to the results, if there aren't any then run the block
1030 (goto-char (or (and (not re-run
) (org-babel-where-is-src-block-result))
1031 (progn (org-babel-execute-src-block)
1032 (org-babel-where-is-src-block-result))))
1034 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
1036 (if (looking-at org-bracket-link-regexp
)
1039 (let ((r (org-babel-format-result
1040 (org-babel-read-result) (cdr (assq :sep
(nth 2 info
))))))
1041 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
1042 (delete-region (point-min) (point-max))
1047 (defmacro org-babel-map-src-blocks
(file &rest body
)
1048 "Evaluate BODY forms on each source-block in FILE.
1049 If FILE is nil evaluate BODY forms on source blocks in current
1050 buffer. During evaluation of BODY the following local variables
1051 are set relative to the currently matched code block.
1053 full-block ------- string holding the entirety of the code block
1054 beg-block -------- point at the beginning of the code block
1055 end-block -------- point at the end of the matched code block
1056 lang ------------- string holding the language of the code block
1057 beg-lang --------- point at the beginning of the lang
1058 end-lang --------- point at the end of the lang
1059 switches --------- string holding the switches
1060 beg-switches ----- point at the beginning of the switches
1061 end-switches ----- point at the end of the switches
1062 header-args ------ string holding the header-args
1063 beg-header-args -- point at the beginning of the header-args
1064 end-header-args -- point at the end of the header-args
1065 body ------------- string holding the body of the code block
1066 beg-body --------- point at the beginning of the body
1067 end-body --------- point at the end of the body"
1068 (declare (indent 1))
1069 (let ((tempvar (make-symbol "file")))
1070 `(let* ((case-fold-search t
)
1072 (visited-p (or (null ,tempvar
)
1073 (get-file-buffer (expand-file-name ,tempvar
))))
1074 (point (point)) to-be-removed
)
1075 (save-window-excursion
1076 (when ,tempvar
(find-file ,tempvar
))
1077 (setq to-be-removed
(current-buffer))
1078 (goto-char (point-min))
1079 (while (re-search-forward org-babel-src-block-regexp nil t
)
1080 (when (org-babel-active-location-p)
1081 (goto-char (match-beginning 0))
1082 (let ((full-block (match-string 0))
1083 (beg-block (match-beginning 0))
1084 (end-block (match-end 0))
1085 (lang (match-string 2))
1086 (beg-lang (match-beginning 2))
1087 (end-lang (match-end 2))
1088 (switches (match-string 3))
1089 (beg-switches (match-beginning 3))
1090 (end-switches (match-end 3))
1091 (header-args (match-string 4))
1092 (beg-header-args (match-beginning 4))
1093 (end-header-args (match-end 4))
1094 (body (match-string 5))
1095 (beg-body (match-beginning 5))
1096 (end-body (match-end 5)))
1097 ;; Silence byte-compiler in case `body' doesn't use all
1099 (ignore full-block beg-block end-block lang
1100 beg-lang end-lang switches beg-switches
1101 end-switches header-args beg-header-args
1102 end-header-args body beg-body end-body
)
1104 (goto-char end-block
)))))
1105 (unless visited-p
(kill-buffer to-be-removed
))
1106 (goto-char point
))))
1107 (def-edebug-spec org-babel-map-src-blocks
(form body
))
1110 (defmacro org-babel-map-inline-src-blocks
(file &rest body
)
1111 "Evaluate BODY forms on each inline source block in FILE.
1112 If FILE is nil evaluate BODY forms on source blocks in current
1114 (declare (indent 1) (debug (form body
)))
1115 (org-with-gensyms (datum end point tempvar to-be-removed visitedp
)
1116 `(let* ((case-fold-search t
)
1118 (,visitedp
(or (null ,tempvar
)
1119 (get-file-buffer (expand-file-name ,tempvar
))))
1122 (save-window-excursion
1123 (when ,tempvar
(find-file ,tempvar
))
1124 (setq ,to-be-removed
(current-buffer))
1125 (goto-char (point-min))
1126 (while (re-search-forward "src_\\S-" nil t
)
1127 (let ((,datum
(save-match-data (org-element-context))))
1128 (when (eq (org-element-type ,datum
) 'inline-src-block
)
1129 (goto-char (match-beginning 0))
1130 (let ((,end
(copy-marker (org-element-property :end
,datum
))))
1133 (set-marker ,end nil
))))))
1134 (unless ,visitedp
(kill-buffer ,to-be-removed
))
1135 (goto-char ,point
))))
1138 (defmacro org-babel-map-call-lines
(file &rest body
)
1139 "Evaluate BODY forms on each call line in FILE.
1140 If FILE is nil evaluate BODY forms on source blocks in current
1142 (declare (indent 1) (debug (form body
)))
1143 (org-with-gensyms (datum end point tempvar to-be-removed visitedp
)
1144 `(let* ((case-fold-search t
)
1146 (,visitedp
(or (null ,tempvar
)
1147 (get-file-buffer (expand-file-name ,tempvar
))))
1150 (save-window-excursion
1151 (when ,tempvar
(find-file ,tempvar
))
1152 (setq ,to-be-removed
(current-buffer))
1153 (goto-char (point-min))
1154 (while (re-search-forward "call_\\S-\\|^[ \t]*#\\+CALL:" nil t
)
1155 (let ((,datum
(save-match-data (org-element-context))))
1156 (when (memq (org-element-type ,datum
)
1157 '(babel-call inline-babel-call
))
1158 (goto-char (match-beginning 0))
1159 (let ((,end
(copy-marker (org-element-property :end
,datum
))))
1162 (set-marker ,end nil
))))))
1163 (unless ,visitedp
(kill-buffer ,to-be-removed
))
1164 (goto-char ,point
))))
1167 (defmacro org-babel-map-executables
(file &rest body
)
1168 "Evaluate BODY forms on each active Babel code in FILE.
1169 If FILE is nil evaluate BODY forms on source blocks in current
1171 (declare (indent 1) (debug (form body
)))
1172 (org-with-gensyms (datum end point tempvar to-be-removed visitedp
)
1173 `(let* ((case-fold-search t
)
1175 (,visitedp
(or (null ,tempvar
)
1176 (get-file-buffer (expand-file-name ,tempvar
))))
1179 (save-window-excursion
1180 (when ,tempvar
(find-file ,tempvar
))
1181 (setq ,to-be-removed
(current-buffer))
1182 (goto-char (point-min))
1183 (while (re-search-forward
1184 "\\(call\\|src\\)_\\|^[ \t]*#\\+\\(BEGIN_SRC\\|CALL:\\)" nil t
)
1185 (let ((,datum
(save-match-data (org-element-context))))
1186 (when (memq (org-element-type ,datum
)
1187 '(babel-call inline-babel-call inline-src-block
1189 (goto-char (match-beginning 0))
1190 (let ((,end
(copy-marker (org-element-property :end
,datum
))))
1193 (set-marker ,end nil
))))))
1194 (unless ,visitedp
(kill-buffer ,to-be-removed
))
1195 (goto-char ,point
))))
1198 (defun org-babel-execute-buffer (&optional arg
)
1199 "Execute source code blocks in a buffer.
1200 Call `org-babel-execute-src-block' on every source block in
1201 the current buffer."
1203 (org-babel-eval-wipe-error-buffer)
1204 (org-save-outline-visibility t
1205 (org-babel-map-executables nil
1206 (if (memq (org-element-type (org-element-context))
1207 '(babel-call inline-babel-call
))
1208 (org-babel-lob-execute-maybe)
1209 (org-babel-execute-src-block arg
)))))
1212 (defun org-babel-execute-subtree (&optional arg
)
1213 "Execute source code blocks in a subtree.
1214 Call `org-babel-execute-src-block' on every source block in
1215 the current subtree."
1219 (org-narrow-to-subtree)
1220 (org-babel-execute-buffer arg
)
1224 (defun org-babel-sha1-hash (&optional info
)
1225 "Generate an sha1 hash based on the value of info."
1227 (let ((print-level nil
)
1228 (info (or info
(org-babel-get-src-block-info))))
1230 (sort (copy-sequence (nth 2 info
))
1231 (lambda (a b
) (string< (car a
) (car b
)))))
1232 (let* ((rm (lambda (lst)
1233 (dolist (p '("replace" "silent" "none"
1234 "append" "prepend"))
1235 (setq lst
(remove p lst
)))
1238 (let ((v (if (and (listp (cdr arg
)) (null (cddr arg
)))
1239 (copy-sequence (cdr arg
))
1241 (when (and v
(not (and (sequencep v
)
1245 ((and (listp v
) ; lists are sorted
1246 (member (car arg
) '(:result-params
)))
1247 (sort (funcall rm v
) #'string
<))
1248 ((and (stringp v
) ; strings are sorted
1249 (member (car arg
) '(:results
:exports
)))
1250 (mapconcat #'identity
(sort (funcall rm
(split-string v
))
1255 (params (nth 2 info
))
1256 (body (if (org-babel-noweb-p params
:eval
)
1257 (org-babel-expand-noweb-references info
) (nth 1 info
)))
1258 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
1259 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
1262 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
1263 (org-babel-expand-body:generic
1264 body params
(and (fboundp assignments-cmd
)
1265 (funcall assignments-cmd params
))))))
1266 (let* ((it (format "%s-%s"
1269 (delq nil
(mapcar (lambda (arg)
1270 (let ((normalized (funcall norm arg
)))
1272 (format "%S" normalized
))))
1276 (when (called-interactively-p 'interactive
) (message hash
))
1279 (defun org-babel-current-result-hash (&optional info
)
1280 "Return the current in-buffer hash."
1281 (let ((result (org-babel-where-is-src-block-result nil info
)))
1283 (org-with-wide-buffer
1285 (looking-at org-babel-result-regexp
)
1286 (match-string-no-properties 1)))))
1288 (defun org-babel-set-current-result-hash (hash info
)
1289 "Set the current in-buffer hash to HASH."
1290 (org-with-wide-buffer
1291 (goto-char (org-babel-where-is-src-block-result nil info
))
1292 (looking-at org-babel-result-regexp
)
1293 (goto-char (match-beginning 1))
1294 (mapc #'delete-overlay
(overlays-at (point)))
1295 (forward-char org-babel-hash-show
)
1296 (mapc #'delete-overlay
(overlays-at (point)))
1297 (replace-match hash nil nil nil
1)
1299 (org-babel-hide-hash)))
1301 (defun org-babel-hide-hash ()
1302 "Hide the hash in the current results line.
1303 Only the initial `org-babel-hash-show' characters of the hash
1304 will remain visible."
1305 (add-to-invisibility-spec '(org-babel-hide-hash . t
))
1307 (when (and (re-search-forward org-babel-result-regexp nil t
)
1309 (let* ((start (match-beginning 1))
1310 (hide-start (+ org-babel-hash-show start
))
1312 (hash (match-string 1))
1314 (setq ov1
(make-overlay start hide-start
))
1315 (setq ov2
(make-overlay hide-start end
))
1316 (overlay-put ov2
'invisible
'org-babel-hide-hash
)
1317 (overlay-put ov1
'babel-hash hash
)))))
1319 (defun org-babel-hide-all-hashes ()
1320 "Hide the hash in the current buffer.
1321 Only the initial `org-babel-hash-show' characters of each hash
1322 will remain visible. This function should be called as part of
1323 the `org-mode-hook'."
1325 (while (and (not org-babel-hash-show-time
)
1326 (re-search-forward org-babel-result-regexp nil t
))
1327 (goto-char (match-beginning 0))
1328 (org-babel-hide-hash)
1329 (goto-char (match-end 0)))))
1330 (add-hook 'org-mode-hook
'org-babel-hide-all-hashes
)
1332 (defun org-babel-hash-at-point (&optional point
)
1333 "Return the value of the hash at POINT.
1335 The hash is also added as the last element of the kill ring.
1336 This can be called with `\\[org-ctrl-c-ctrl-c]'."
1338 (let ((hash (car (delq nil
(mapcar
1339 (lambda (ol) (overlay-get ol
'babel-hash
))
1340 (overlays-at (or point
(point))))))))
1341 (when hash
(kill-new hash
) (message hash
))))
1343 (defun org-babel-result-hide-spec ()
1344 "Hide portions of results lines.
1345 Add `org-babel-hide-result' as an invisibility spec for hiding
1346 portions of results lines."
1347 (add-to-invisibility-spec '(org-babel-hide-result . t
)))
1348 (add-hook 'org-mode-hook
'org-babel-result-hide-spec
)
1350 (defvar org-babel-hide-result-overlays nil
1351 "Overlays hiding results.")
1353 (defun org-babel-result-hide-all ()
1354 "Fold all results in the current buffer."
1356 (org-babel-show-result-all)
1358 (while (re-search-forward org-babel-result-regexp nil t
)
1359 (save-excursion (goto-char (match-beginning 0))
1360 (org-babel-hide-result-toggle-maybe)))))
1362 (defun org-babel-show-result-all ()
1363 "Unfold all results in the current buffer."
1364 (mapc 'delete-overlay org-babel-hide-result-overlays
)
1365 (setq org-babel-hide-result-overlays nil
))
1368 (defun org-babel-hide-result-toggle-maybe ()
1369 "Toggle visibility of result at point."
1371 (let ((case-fold-search t
))
1373 (beginning-of-line 1)
1374 (looking-at org-babel-result-regexp
))
1375 (progn (org-babel-hide-result-toggle)
1376 t
) ;; to signal that we took action
1377 nil
))) ;; to signal that we did not
1379 (defun org-babel-hide-result-toggle (&optional force
)
1380 "Toggle the visibility of the current result."
1384 (if (re-search-forward org-babel-result-regexp nil t
)
1385 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
1387 (while (looking-at org-babel-multi-line-header-regexp
)
1389 (goto-char (- (org-babel-result-end) 1)) (point)))
1391 (if (memq t
(mapcar (lambda (overlay)
1392 (eq (overlay-get overlay
'invisible
)
1393 'org-babel-hide-result
))
1394 (overlays-at start
)))
1395 (when (or (not force
) (eq force
'off
))
1397 (when (member ov org-babel-hide-result-overlays
)
1398 (setq org-babel-hide-result-overlays
1399 (delq ov org-babel-hide-result-overlays
)))
1400 (when (eq (overlay-get ov
'invisible
)
1401 'org-babel-hide-result
)
1402 (delete-overlay ov
)))
1403 (overlays-at start
)))
1404 (setq ov
(make-overlay start end
))
1405 (overlay-put ov
'invisible
'org-babel-hide-result
)
1406 ;; make the block accessible to isearch
1408 ov
'isearch-open-invisible
1410 (when (member ov org-babel-hide-result-overlays
)
1411 (setq org-babel-hide-result-overlays
1412 (delq ov org-babel-hide-result-overlays
)))
1413 (when (eq (overlay-get ov
'invisible
)
1414 'org-babel-hide-result
)
1415 (delete-overlay ov
))))
1416 (push ov org-babel-hide-result-overlays
)))
1417 (error "Not looking at a result line"))))
1419 ;; org-tab-after-check-for-cycling-hook
1420 (add-hook 'org-tab-first-hook
'org-babel-hide-result-toggle-maybe
)
1421 ;; Remove overlays when changing major mode
1422 (add-hook 'org-mode-hook
1423 (lambda () (add-hook 'change-major-mode-hook
1424 'org-babel-show-result-all
'append
'local
)))
1426 (defun org-babel-params-from-properties (&optional lang no-eval
)
1427 "Retrieve source block parameters specified as properties.
1429 LANG is the language of the source block, as a string. When
1430 optional argument NO-EVAL is non-nil, do not evaluate Lisp values
1433 Return a list of association lists of source block parameters
1434 specified in the properties of the current outline entry."
1437 ;; Header arguments specified with the header-args property at
1439 (org-babel-parse-header-arguments
1440 (org-entry-get (point) "header-args" 'inherit
)
1442 ;; Language-specific header arguments at point of call.
1444 (org-babel-parse-header-arguments
1445 (org-entry-get (point) (concat "header-args:" lang
) 'inherit
)
1448 (defun org-babel-balanced-split (string alts
)
1449 "Split STRING on instances of ALTS.
1450 ALTS is a character, or cons of two character options where each
1451 option may be either the numeric code of a single character or
1452 a list of character alternatives. For example, to split on
1453 balanced instances of \"[ \t]:\", set ALTS to ((32 9) . 58)."
1456 (goto-char (point-min))
1457 (let ((splitp (lambda (past next
)
1458 ;; Non-nil when there should be a split after NEXT
1459 ;; character. PAST is the character before NEXT.
1461 (`(,(and first
(pred consp
)) .
,(and second
(pred consp
)))
1462 (and (memq past first
) (memq next second
)))
1463 (`(,first .
,(and second
(pred consp
)))
1464 (and (eq past first
) (memq next second
)))
1465 (`(,(and first
(pred consp
)) .
,second
)
1466 (and (memq past first
) (eq next second
)))
1467 (`(,first .
,second
)
1468 (and (eq past first
) (eq next second
)))
1469 ((pred (eq next
)) t
)
1475 ((funcall splitp
(char-before) (char-after))
1476 ;; There is a split after point. If ALTS is two-folds,
1477 ;; remove last parsed character as it belongs to ALTS.
1478 (when (consp alts
) (pop partial
))
1479 ;; Include elements parsed so far in RESULTS and flush
1482 (push (apply #'string
(nreverse partial
)) result
)
1485 ((memq (char-after) '(?\
( ?\
[))
1486 ;; Include everything between balanced brackets.
1487 (let* ((origin (point))
1488 (after (char-after))
1489 (openings (list after
)))
1491 (while (and openings
(re-search-forward "[]()]" nil t
))
1492 (pcase (char-before)
1493 ((and match
(or ?\
[ ?\
()) (push match openings
))
1494 (?\
] (when (eq ?\
[ (car openings
)) (pop openings
)))
1495 (_ (when (eq ?\
( (car openings
)) (pop openings
)))))
1498 (nconc (nreverse (string-to-list
1499 (buffer-substring origin
(point))))
1501 ;; Un-balanced bracket. Backtrack.
1502 (push after partial
)
1503 (goto-char (1+ origin
)))))
1504 ((and (eq ?
\" (char-after)) (not (eq ?
\\ (char-before))))
1505 ;; Include everything from current double quote to next
1506 ;; non-escaped double quote.
1507 (let ((origin (point)))
1508 (if (re-search-forward "[^\\]\"" nil t
)
1510 (nconc (nreverse (string-to-list
1511 (buffer-substring origin
(point))))
1513 ;; No closing double quote. Backtrack.
1516 (t (push (char-after) partial
)
1518 ;; Add pending parsing and return result.
1519 (when partial
(push (apply #'string
(nreverse partial
)) result
))
1520 (nreverse result
))))
1522 (defun org-babel-join-splits-near-ch (ch list
)
1523 "Join splits where \"=\" is on either end of the split."
1524 (let ((last= (lambda (str) (= ch
(aref str
(1- (length str
))))))
1525 (first= (lambda (str) (= ch
(aref str
0)))))
1527 (cl-reduce (lambda (acc el
)
1528 (let ((head (car acc
)))
1529 (if (and head
(or (funcall last
= head
) (funcall first
= el
)))
1530 (cons (concat head el
) (cdr acc
))
1532 list
:initial-value nil
))))
1534 (defun org-babel-parse-header-arguments (string &optional no-eval
)
1535 "Parse header arguments in STRING.
1536 When optional argument NO-EVAL is non-nil, do not evaluate Lisp
1537 in parameters. Return an alist."
1538 (when (org-string-nw-p string
)
1539 (org-babel-parse-multiple-vars
1544 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1546 (cons (intern (match-string 1 arg
))
1547 (org-babel-read (org-babel-chomp (match-string 2 arg
))
1549 (cons (intern (org-babel-chomp arg
)) nil
)))
1550 (let ((raw (org-babel-balanced-split string
'((32 9) .
58))))
1552 (mapcar (lambda (r) (concat ":" r
)) (cdr raw
)))))))))
1554 (defun org-babel-parse-multiple-vars (header-arguments)
1555 "Expand multiple variable assignments behind a single :var keyword.
1557 This allows expression of multiple variables with one :var as
1560 #+PROPERTY: var foo=1, bar=2"
1562 (mapc (lambda (pair)
1563 (if (eq (car pair
) :var
)
1564 (mapcar (lambda (v) (push (cons :var
(org-trim v
)) results
))
1565 (org-babel-join-splits-near-ch
1566 61 (org-babel-balanced-split (cdr pair
) 32)))
1567 (push pair results
)))
1569 (nreverse results
)))
1571 (defun org-babel-process-params (params)
1572 "Expand variables in PARAMS and add summary parameters."
1573 (let* ((processed-vars (mapcar (lambda (el)
1576 (org-babel-ref-parse el
)))
1577 (org-babel--get-vars params
)))
1578 (vars-and-names (if (and (assq :colname-names params
)
1579 (assq :rowname-names params
))
1580 (list processed-vars
)
1581 (org-babel-disassemble-tables
1583 (cdr (assq :hlines params
))
1584 (cdr (assq :colnames params
))
1585 (cdr (assq :rownames params
)))))
1586 (raw-result (or (cdr (assq :results params
)) ""))
1587 (result-params (delete-dups
1589 (split-string (if (stringp raw-result
)
1591 (eval raw-result t
)))
1592 (cdr (assq :result-params params
))))))
1594 (mapcar (lambda (var) (cons :var var
)) (car vars-and-names
))
1596 (cons :colname-names
(or (cdr (assq :colname-names params
))
1597 (cadr vars-and-names
)))
1598 (cons :rowname-names
(or (cdr (assq :rowname-names params
))
1599 (cl-caddr vars-and-names
)))
1600 (cons :result-params result-params
)
1601 (cons :result-type
(cond ((member "output" result-params
) 'output
)
1602 ((member "value" result-params
) 'value
)
1605 (lambda (x) (memq (car x
) '(:colname-names
:rowname-names
:result-params
1606 :result-type
:var
)))
1609 ;; row and column names
1610 (defun org-babel-del-hlines (table)
1611 "Remove all `hline's from TABLE."
1612 (remq 'hline table
))
1614 (defun org-babel-get-colnames (table)
1615 "Return the column names of TABLE.
1616 Return a cons cell, the `car' of which contains the TABLE less
1617 colnames, and the `cdr' of which contains a list of the column
1619 (if (eq 'hline
(nth 1 table
))
1620 (cons (cddr table
) (car table
))
1621 (cons (cdr table
) (car table
))))
1623 (defun org-babel-get-rownames (table)
1624 "Return the row names of TABLE.
1625 Return a cons cell, the `car' of which contains the TABLE less
1626 rownames, and the `cdr' of which contains a list of the rownames.
1627 Note: this function removes any hlines in TABLE."
1628 (let* ((table (org-babel-del-hlines table
))
1629 (rownames (funcall (lambda ()
1635 (setq tp
(cdr tp
))))
1637 (cons table rownames
)))
1639 (defun org-babel-put-colnames (table colnames
)
1640 "Add COLNAMES to TABLE if they exist."
1641 (if colnames
(apply 'list colnames
'hline table
) table
))
1643 (defun org-babel-put-rownames (table rownames
)
1644 "Add ROWNAMES to TABLE if they exist."
1646 (mapcar (lambda (row)
1648 (cons (or (pop rownames
) "") row
)
1652 (defun org-babel-pick-name (names selector
)
1653 "Select one out of an alist of row or column names.
1654 SELECTOR can be either a list of names in which case those names
1655 will be returned directly, or an index into the list NAMES in
1656 which case the indexed names will be return."
1657 (if (listp selector
)
1660 (if (and selector
(symbolp selector
) (not (equal t selector
)))
1661 (cdr (assoc selector names
))
1662 (if (integerp selector
)
1663 (nth (- selector
1) names
)
1664 (cdr (car (last names
))))))))
1666 (defun org-babel-disassemble-tables (vars hlines colnames rownames
)
1667 "Parse tables for further processing.
1668 Process the variables in VARS according to the HLINES,
1669 ROWNAMES and COLNAMES header arguments. Return a list consisting
1670 of the vars, cnames and rnames."
1671 (let (cnames rnames
)
1675 (when (listp (cdr var
))
1676 (when (and (not (equal colnames
"no"))
1677 (or colnames
(and (eq (nth 1 (cdr var
)) 'hline
)
1678 (not (member 'hline
(cddr (cdr var
)))))))
1679 (let ((both (org-babel-get-colnames (cdr var
))))
1680 (setq cnames
(cons (cons (car var
) (cdr both
))
1682 (setq var
(cons (car var
) (car both
)))))
1683 (when (and rownames
(not (equal rownames
"no")))
1684 (let ((both (org-babel-get-rownames (cdr var
))))
1685 (setq rnames
(cons (cons (car var
) (cdr both
))
1687 (setq var
(cons (car var
) (car both
)))))
1688 (when (and hlines
(not (equal hlines
"yes")))
1689 (setq var
(cons (car var
) (org-babel-del-hlines (cdr var
))))))
1692 (reverse cnames
) (reverse rnames
))))
1694 (defun org-babel-reassemble-table (table colnames rownames
)
1695 "Add column and row names to a table.
1696 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1697 to the table for reinsertion to org-mode."
1699 (let ((table (if (and rownames
(= (length table
) (length rownames
)))
1700 (org-babel-put-rownames table rownames
) table
)))
1701 (if (and colnames
(listp (car table
)) (= (length (car table
))
1703 (org-babel-put-colnames table colnames
) table
))
1706 (defun org-babel-where-is-src-block-head (&optional src-block
)
1707 "Find where the current source block begins.
1709 If optional argument SRC-BLOCK is `src-block' type element, find
1710 its current beginning instead.
1712 Return the point at the beginning of the current source block.
1713 Specifically at the beginning of the #+BEGIN_SRC line. Also set
1714 match-data relatively to `org-babel-src-block-regexp', which see.
1715 If the point is not on a source block then return nil."
1716 (let ((element (or src-block
(org-element-at-point))))
1717 (when (eq (org-element-type element
) 'src-block
)
1718 (let ((end (org-element-property :end element
)))
1719 (org-with-wide-buffer
1720 ;; Ensure point is not on a blank line after the block.
1722 (skip-chars-forward " \r\t\n" end
)
1723 (when (< (point) end
)
1724 (prog1 (goto-char (org-element-property :post-affiliated element
))
1725 (looking-at org-babel-src-block-regexp
))))))))
1728 (defun org-babel-goto-src-block-head ()
1729 "Go to the beginning of the current code block."
1731 (let ((head (org-babel-where-is-src-block-head)))
1732 (if head
(goto-char head
) (error "Not currently in a code block"))))
1735 (defun org-babel-goto-named-src-block (name)
1736 "Go to a named source-code block."
1738 (let ((completion-ignore-case t
)
1739 (case-fold-search t
)
1740 (all-block-names (org-babel-src-block-names)))
1741 (list (completing-read
1742 "source-block name: " all-block-names nil t
1743 (let* ((context (org-element-context))
1744 (type (org-element-type context
))
1746 (and (memq type
'(inline-src-block src-block
))
1747 (org-in-regexp (org-babel-noweb-wrap)))))
1751 (+ (car noweb-ref
) (length org-babel-noweb-wrap-start
))
1752 (- (cdr noweb-ref
) (length org-babel-noweb-wrap-end
))))
1753 ((memq type
'(babel-call inline-babel-call
)) ;#+CALL:
1754 (org-element-property :call context
))
1755 ((car (org-element-property :results context
))) ;#+RESULTS:
1756 ((let ((symbol (thing-at-point 'symbol
))) ;Symbol.
1758 (member-ignore-case symbol all-block-names
)
1761 (let ((point (org-babel-find-named-block name
)))
1763 ;; Taken from `org-open-at-point'.
1764 (progn (org-mark-ring-push) (goto-char point
) (org-show-context))
1765 (message "source-code block `%s' not found in this buffer" name
))))
1767 (defun org-babel-find-named-block (name)
1768 "Find a named source-code block.
1769 Return the location of the source block identified by source
1770 NAME, or nil if no such block exists. Set match data according
1771 to `org-babel-named-src-block-regexp'."
1773 (goto-char (point-min))
1774 (let ((regexp (org-babel-named-src-block-regexp-for-name name
)))
1775 (or (and (looking-at regexp
)
1776 (progn (goto-char (match-beginning 1))
1777 (line-beginning-position)))
1778 (ignore-errors (org-next-block 1 nil regexp
))))))
1780 (defun org-babel-src-block-names (&optional file
)
1781 "Returns the names of source blocks in FILE or the current buffer."
1782 (with-current-buffer (if file
(find-file-noselect file
) (current-buffer))
1783 (org-with-point-at 1
1784 (let ((regexp "^[ \t]*#\\+begin_src ")
1785 (case-fold-search t
)
1787 (while (re-search-forward regexp nil t
)
1788 (let ((element (org-element-at-point)))
1789 (when (eq 'src-block
(org-element-type element
))
1790 (let ((name (org-element-property :name element
)))
1791 (when name
(push name names
))))))
1795 (defun org-babel-goto-named-result (name)
1796 "Go to a named result."
1798 (let ((completion-ignore-case t
))
1799 (list (completing-read "Source-block name: "
1800 (org-babel-result-names) nil t
))))
1801 (let ((point (org-babel-find-named-result name
)))
1803 ;; taken from `org-open-at-point'
1804 (progn (goto-char point
) (org-show-context))
1805 (message "result `%s' not found in this buffer" name
))))
1807 (defun org-babel-find-named-result (name)
1808 "Find a named result.
1809 Return the location of the result named NAME in the current
1810 buffer or nil if no such result exists."
1812 (goto-char (point-min))
1813 (let ((case-fold-search t
)
1814 (re (format "^[ \t]*#\\+%s.*?:[ \t]*%s[ \t]*$"
1815 org-babel-results-keyword
1816 (regexp-quote name
))))
1818 (while (re-search-forward re nil t
)
1819 (let ((element (org-element-at-point)))
1820 (when (or (eq (org-element-type element
) 'keyword
)
1822 (org-element-property :post-affiliated element
)))
1823 (throw :found
(line-beginning-position)))))))))
1825 (defun org-babel-result-names (&optional file
)
1826 "Returns the names of results in FILE or the current buffer."
1828 (when file
(find-file file
)) (goto-char (point-min))
1829 (let ((case-fold-search t
) names
)
1830 (while (re-search-forward org-babel-result-w-name-regexp nil t
)
1831 (setq names
(cons (match-string-no-properties 9) names
)))
1835 (defun org-babel-next-src-block (&optional arg
)
1836 "Jump to the next source block.
1837 With optional prefix argument ARG, jump forward ARG many source blocks."
1839 (org-next-block arg nil org-babel-src-block-regexp
))
1842 (defun org-babel-previous-src-block (&optional arg
)
1843 "Jump to the previous source block.
1844 With optional prefix argument ARG, jump backward ARG many source blocks."
1846 (org-previous-block arg org-babel-src-block-regexp
))
1848 (defvar org-babel-load-languages
)
1851 (defun org-babel-mark-block ()
1852 "Mark current src block."
1854 (let ((head (org-babel-where-is-src-block-head)))
1858 (looking-at org-babel-src-block-regexp
))
1859 (push-mark (match-end 5) nil t
)
1860 (goto-char (match-beginning 5)))))
1862 (defun org-babel-demarcate-block (&optional arg
)
1863 "Wrap or split the code in the region or on the point.
1864 When called from inside of a code block the current block is
1865 split. When called from outside of a code block a new code block
1866 is created. In both cases if the region is demarcated and if the
1867 region is not active then the point is demarcated."
1869 (let* ((info (org-babel-get-src-block-info 'light
))
1870 (start (org-babel-where-is-src-block-head))
1871 (block (and start
(match-string 0)))
1872 (headers (and start
(match-string 4)))
1873 (stars (concat (make-string (or (org-current-level) 1) ?
*) " "))
1874 (lower-case-p (and block
1875 (let (case-fold-search)
1876 (string-match-p "#\\+begin_src" block
)))))
1882 (let ((lang (nth 0 info
))
1883 (indent (make-string (current-indentation) ?\s
)))
1884 (when (string-match "^[[:space:]]*$"
1885 (buffer-substring (point-at-bol)
1887 (delete-region (point-at-bol) (point-at-eol)))
1889 (if (looking-at "^") "" "\n")
1890 indent
(funcall (if lower-case-p
'downcase
'upcase
) "#+end_src\n")
1891 (if arg stars indent
) "\n"
1892 indent
(funcall (if lower-case-p
'downcase
'upcase
) "#+begin_src ")
1894 (if (> (length headers
) 1)
1895 (concat " " headers
) headers
)
1896 (if (looking-at "[\n\r]")
1898 (concat "\n" (make-string (current-column) ?
)))))))
1899 (move-end-of-line 2))
1900 (sort (if (org-region-active-p) (list (mark) (point)) (list (point))) #'>))
1901 (let ((start (point))
1902 (lang (completing-read
1904 (mapcar #'symbol-name
1906 (append (mapcar #'car org-babel-load-languages
)
1907 (mapcar (lambda (el) (intern (car el
)))
1908 org-src-lang-modes
))))))
1909 (body (delete-and-extract-region
1910 (if (org-region-active-p) (mark) (point)) (point))))
1911 (insert (concat (if (looking-at "^") "" "\n")
1912 (if arg
(concat stars
"\n") "")
1913 (funcall (if lower-case-p
'downcase
'upcase
) "#+begin_src ")
1916 (if (or (= (length body
) 0)
1917 (string-suffix-p "\r" body
)
1918 (string-suffix-p "\n" body
)) "" "\n")
1919 (funcall (if lower-case-p
'downcase
'upcase
) "#+end_src\n")))
1920 (goto-char start
) (move-end-of-line 1)))))
1922 (defun org-babel--insert-results-keyword (name hash
)
1923 "Insert RESULTS keyword with NAME value at point.
1924 If NAME is nil, results are anonymous. HASH is a string used as
1925 the results hash, or nil. Leave point before the keyword."
1926 (save-excursion (insert "\n")) ;open line to indent.
1929 (insert (concat "#+" org-babel-results-keyword
1930 (cond ((not hash
) nil
)
1931 (org-babel-hash-show-time
1933 (format-time-string "<%F %T>")
1935 (t (format "[%s]" hash
)))
1937 (when name
(concat " " name
))
1939 ;; Make sure results are going to be followed by at least one blank
1940 ;; line so they do not get merged with the next element, e.g.,
1945 ;; : fixed-width area, unrelated to the above.
1946 (unless (looking-at "^[ \t]*$") (save-excursion (insert "\n")))
1947 (beginning-of-line 0)
1948 (when hash
(org-babel-hide-hash)))
1950 (defun org-babel--clear-results-maybe (hash)
1951 "Clear results when hash doesn't match HASH.
1953 When results hash does not match HASH, remove RESULTS keyword at
1954 point, along with related contents. Do nothing if HASH is nil.
1956 Return a non-nil value if results were cleared. In this case,
1957 leave point where new results should be inserted."
1959 (looking-at org-babel-result-regexp
)
1960 (unless (string= (match-string 1) hash
)
1961 (let* ((e (org-element-at-point))
1962 (post (copy-marker (org-element-property :post-affiliated e
))))
1966 (goto-char (org-element-property :end e
))
1967 (skip-chars-backward " \t\n")
1968 (line-beginning-position 2)))
1969 ;; Delete RESULT keyword. However, if RESULTS keyword is
1970 ;; orphaned, ignore this part. The deletion above already
1972 (unless (= (point) post
)
1973 (delete-region (line-beginning-position)
1974 (line-beginning-position 2)))
1976 (set-marker post nil
)
1979 (defun org-babel-where-is-src-block-result (&optional insert _info hash
)
1980 "Find where the current source block results begin.
1982 Return the point at the beginning of the result of the current
1983 source block, specifically at the beginning of the results line.
1985 If no result exists for this block return nil, unless optional
1986 argument INSERT is non-nil. In this case, create a results line
1987 following the source block and return the position at its
1988 beginning. In the case of inline code, remove the results part
1991 If optional argument HASH is a string, remove contents related to
1992 RESULTS keyword if its hash is different. Then update the latter
1994 (let ((context (org-element-context)))
1996 (org-with-wide-buffer
1997 (pcase (org-element-type context
)
1998 ((or `inline-babel-call
`inline-src-block
)
1999 ;; Results for inline objects are located right after them.
2000 ;; There is no RESULTS line to insert either.
2001 (let ((limit (org-element-property
2002 :contents-end
(org-element-property :parent context
))))
2003 (goto-char (org-element-property :end context
))
2004 (skip-chars-forward " \t\n" limit
)
2008 (let ((result (org-element-context)))
2009 (and (eq (org-element-type result
) 'macro
)
2010 (string= (org-element-property :key result
)
2012 (if (not insert
) (point)
2016 (goto-char (org-element-property :end result
))
2017 (skip-chars-backward " \t")
2020 ((or `babel-call
`src-block
)
2021 (let* ((name (org-element-property :name context
))
2022 (named-results (and name
(org-babel-find-named-result name
))))
2023 (goto-char (or named-results
(org-element-property :end context
)))
2025 ;; Existing results named after the current source.
2027 (when (org-babel--clear-results-maybe hash
)
2028 (org-babel--insert-results-keyword name hash
))
2029 (throw :found
(point)))
2030 ;; Named results expect but none to be found.
2032 ;; No possible anonymous results at the very end of
2033 ;; buffer or outside CONTEXT parent.
2035 (or (org-element-property
2036 :contents-end
(org-element-property :parent context
))
2038 ;; Check if next element is an anonymous result below
2039 ;; the current block.
2040 ((let* ((next (org-element-at-point))
2041 (end (save-excursion
2043 (org-element-property :post-affiliated next
))
2044 (line-end-position)))
2045 (empty-result-re (concat org-babel-result-regexp
"$"))
2046 (case-fold-search t
))
2047 (re-search-forward empty-result-re end t
))
2049 (when (org-babel--clear-results-maybe hash
)
2050 (org-babel--insert-results-keyword nil hash
))
2051 (throw :found
(point))))))
2052 ;; Ignore other elements.
2053 (_ (throw :found nil
))))
2054 ;; No result found. Insert a RESULTS keyword below element, if
2055 ;; appropriate. In this case, ensure there is an empty line
2056 ;; after the previous element.
2059 (goto-char (min (org-element-property :end context
) (point-max)))
2060 (skip-chars-backward " \t\n")
2062 (unless (bolp) (insert "\n"))
2064 (org-babel--insert-results-keyword
2065 (org-element-property :name context
) hash
)
2068 (defun org-babel-read-element (element)
2069 "Read ELEMENT into emacs-lisp.
2070 Return nil if ELEMENT cannot be read."
2071 (org-with-wide-buffer
2072 (goto-char (org-element-property :post-affiliated element
))
2073 (pcase (org-element-type element
)
2075 (let ((v (org-trim (org-element-property :value element
))))
2076 (or (org-babel--string-to-number v
) v
)))
2077 (`table
(org-babel-read-table))
2078 (`plain-list
(org-babel-read-list))
2080 (let ((v (org-element-property :value element
)))
2081 (if (or org-src-preserve-indentation
2082 (org-element-property :preserve-indent element
))
2084 (org-remove-indentation v
))))
2086 (org-remove-indentation (org-element-property :value element
)))
2088 ;; Treat paragraphs containing a single link specially.
2089 (skip-chars-forward " \t")
2090 (if (and (looking-at org-bracket-link-regexp
)
2092 (goto-char (match-end 0))
2093 (skip-chars-forward " \r\t\n")
2094 (<= (org-element-property :end element
)
2096 (org-babel-read-link)
2097 (buffer-substring-no-properties
2098 (org-element-property :contents-begin element
)
2099 (org-element-property :contents-end element
))))
2100 ((or `center-block
`quote-block
`verse-block
`special-block
)
2101 (org-remove-indentation
2102 (buffer-substring-no-properties
2103 (org-element-property :contents-begin element
)
2104 (org-element-property :contents-end element
))))
2107 (defun org-babel-read-result ()
2108 "Read the result at point into emacs-lisp."
2109 (and (not (save-excursion
2111 (looking-at-p "[ \t]*$")))
2112 (org-babel-read-element (org-element-at-point))))
2114 (defun org-babel-read-table ()
2115 "Read the table at point into emacs-lisp."
2116 (mapcar (lambda (row)
2117 (if (and (symbolp row
) (equal row
'hline
)) row
2118 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
)) row
)))
2119 (org-table-to-lisp)))
2121 (defun org-babel-read-list ()
2122 "Read the list at point into emacs-lisp."
2123 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
))
2124 (cdr (org-list-to-lisp))))
2126 (defvar org-link-types-re
)
2127 (defun org-babel-read-link ()
2128 "Read the link at point into emacs-lisp.
2129 If the path of the link is a file path it is expanded using
2130 `expand-file-name'."
2131 (let* ((case-fold-search t
)
2132 (raw (and (looking-at org-bracket-link-regexp
)
2133 (org-no-properties (match-string 1))))
2134 (type (and (string-match org-link-types-re raw
)
2135 (match-string 1 raw
))))
2137 ((not type
) (expand-file-name raw
))
2138 ((string= type
"file")
2139 (and (string-match "file\\(.*\\):\\(.+\\)" raw
)
2140 (expand-file-name (match-string 2 raw
))))
2143 (defun org-babel-format-result (result &optional sep
)
2144 "Format RESULT for writing to file."
2145 (let ((echo-res (lambda (r) (if (stringp r
) r
(format "%S" r
)))))
2149 result
(list :sep
(or sep
"\t") :fmt echo-res
))
2151 (funcall echo-res result
))))
2153 (defun org-babel-insert-result (result &optional result-params info hash lang
)
2154 "Insert RESULT into the current buffer.
2156 By default RESULT is inserted after the end of the current source
2157 block. The RESULT of an inline source block usually will be
2158 wrapped inside a `results' macro and placed on the same line as
2159 the inline source block. The macro is stripped upon export.
2160 Multiline and non-scalar RESULTS from inline source blocks are
2161 not allowed. With optional argument RESULT-PARAMS controls
2162 insertion of results in the Org mode file. RESULT-PARAMS can
2163 take the following values:
2165 replace - (default option) insert results after the source block
2166 or inline source block replacing any previously
2169 silent -- no results are inserted into the Org buffer but
2170 the results are echoed to the minibuffer and are
2171 ingested by Emacs (a potentially time consuming
2174 file ---- the results are interpreted as a file path, and are
2175 inserted into the buffer using the Org file syntax.
2177 list ---- the results are interpreted as an Org list.
2179 raw ----- results are added directly to the Org file. This is
2180 a good option if you code block will output Org
2183 drawer -- results are added directly to the Org file as with
2184 \"raw\", but are wrapped in a RESULTS drawer or results
2185 macro, allowing them to later be replaced or removed
2188 org ----- results are added inside of a \"src_org{}\" or \"#+BEGIN_SRC
2189 org\" block depending on whether the current source block is
2190 inline or not. They are not comma-escaped when inserted,
2191 but Org syntax here will be discarded when exporting the
2194 html ---- results are added inside of a #+BEGIN_EXPORT HTML block
2195 or html export snippet depending on whether the current
2196 source block is inline or not. This is a good option
2197 if your code block will output html formatted text.
2199 latex --- results are added inside of a #+BEGIN_EXPORT LATEX
2200 block or latex export snippet depending on whether the
2201 current source block is inline or not. This is a good
2202 option if your code block will output latex formatted
2205 code ---- the results are extracted in the syntax of the source
2206 code of the language being evaluated and are added
2207 inside of a source block with the source-code language
2208 set appropriately. Also, source block inlining is
2209 preserved in this case. Note this relies on the
2210 optional LANG argument.
2212 list ---- the results are rendered as a list. This option not
2213 allowed for inline src blocks.
2215 table --- the results are rendered as a table. This option not
2216 allowed for inline src blocks.
2218 INFO may provide the values of these header arguments (in the
2219 `header-arguments-alist' see the docstring for
2220 `org-babel-get-src-block-info'):
2222 :file --- the name of the file to which output should be written.
2224 :wrap --- the effect is similar to `latex' in RESULT-PARAMS but
2225 using the argument supplied to specify the export block
2227 (cond ((stringp result
)
2228 (setq result
(org-no-properties result
))
2229 (when (member "file" result-params
)
2230 (setq result
(org-babel-result-to-file
2231 result
(when (assq :file-desc
(nth 2 info
))
2232 (or (cdr (assq :file-desc
(nth 2 info
)))
2235 (t (setq result
(format "%S" result
))))
2236 (if (and result-params
(member "silent" result-params
))
2237 (progn (message (replace-regexp-in-string "%" "%%" (format "%S" result
)))
2239 (let ((inline (let ((context (org-element-context)))
2240 (and (memq (org-element-type context
)
2241 '(inline-babel-call inline-src-block
))
2245 (or (and (member "table" result-params
) "`:results table'")
2246 (and (listp result
) "list result")
2247 (and (string-match-p "\n." result
) "multiline result")
2248 (and (member "list" result-params
) "`:results list'"))))
2250 (user-error "Inline error: %s cannot be used" warning
))))
2252 (let* ((visible-beg (point-min-marker))
2253 (visible-end (copy-marker (point-max) t
))
2254 (inline (let ((context (org-element-context)))
2255 (and (memq (org-element-type context
)
2256 '(inline-babel-call inline-src-block
))
2258 (existing-result (org-babel-where-is-src-block-result t nil hash
))
2259 (results-switches (cdr (assq :results_switches
(nth 2 info
))))
2260 ;; When results exist outside of the current visible
2261 ;; region of the buffer, be sure to widen buffer to
2263 (outside-scope (and existing-result
2265 (or (> visible-beg existing-result
)
2266 (<= visible-end existing-result
))))
2268 ;; Ensure non-inline results end in a newline.
2269 (when (and (org-string-nw-p result
)
2271 (not (string-equal (substring result -
1) "\n")))
2272 (setq result
(concat result
"\n")))
2275 (when outside-scope
(widen))
2276 (if existing-result
(goto-char existing-result
)
2277 (goto-char (org-element-property :end inline
))
2278 (skip-chars-backward " \t"))
2280 (setq indent
(current-indentation))
2285 ;; Make sure new results are separated from the
2286 ;; source code by one space.
2287 (unless existing-result
2289 (setq beg
(point))))
2290 ((member "replace" result-params
)
2291 (delete-region (point) (org-babel-result-end)))
2292 ((member "append" result-params
)
2293 (goto-char (org-babel-result-end)) (setq beg
(point-marker)))
2294 ((member "prepend" result-params
))) ; already there
2295 (setq results-switches
2296 (if results-switches
(concat " " results-switches
) ""))
2298 (lambda (start finish
&optional no-escape no-newlines
2299 inline-start inline-finish
)
2301 (setq start inline-start
)
2302 (setq finish inline-finish
)
2303 (setq no-newlines t
))
2304 (let ((before-finish (marker-position end
)))
2306 (insert (concat finish
(unless no-newlines
"\n")))
2308 (insert (concat start
(unless no-newlines
"\n")))
2310 (org-escape-code-in-region
2311 (min (point) before-finish
) before-finish
))
2315 ;; Non-nil when result R can be turned into
2318 (null (cdr (last r
)))
2320 (lambda (e) (or (atom e
) (null (cdr (last e
)))))
2322 ;; insert results based on type
2324 ;; Do nothing for an empty result.
2326 ;; Insert a list if preferred.
2327 ((member "list" result-params
)
2330 (org-list-to-generic
2334 (list (if (stringp e
) e
(format "%S" e
))))
2335 (if (listp result
) result
2336 (split-string result
"\n" t
))))
2337 '(:splicep nil
:istart
"- " :iend
"\n")))
2339 ;; Try hard to print RESULT as a table. Give up if
2340 ;; it contains an improper list.
2341 ((funcall tabulablep result
)
2343 (insert (concat (orgtbl-to-orgtbl
2346 (or (eq e
'hline
) (listp e
)))
2353 (when (org-at-table-p) (org-table-align))
2354 (goto-char (org-table-end)))
2355 ;; Print verbatim a list that cannot be turned into
2357 ((listp result
) (insert (format "%s\n" result
)))
2358 ((member "file" result-params
)
2360 (setq result
(org-macro-escape-arguments result
)))
2362 ((and inline
(not (member "raw" result-params
)))
2363 (insert (org-macro-escape-arguments
2364 (org-babel-chomp result
"\n"))))
2365 (t (goto-char beg
) (insert result
)))
2366 (setq end
(copy-marker (point) t
))
2367 ;; possibly wrap result
2369 ((assq :wrap
(nth 2 info
))
2370 (let ((name (or (cdr (assq :wrap
(nth 2 info
))) "results")))
2371 (funcall wrap
(concat "#+begin_" name
)
2372 (concat "#+end_" (car (split-string name
)))
2373 nil nil
(concat "{{{results(@@" name
":") "@@)}}}")))
2374 ((member "html" result-params
)
2375 (funcall wrap
"#+begin_export html" "#+end_export" nil nil
2376 "{{{results(@@html:" "@@)}}}"))
2377 ((member "latex" result-params
)
2378 (funcall wrap
"#+begin_export latex" "#+end_export" nil nil
2379 "{{{results(@@latex:" "@@)}}}"))
2380 ((member "org" result-params
)
2381 (goto-char beg
) (when (org-at-table-p) (org-cycle))
2382 (funcall wrap
"#+begin_src org" "#+end_src" nil nil
2383 "{{{results(src_org{" "})}}}"))
2384 ((member "code" result-params
)
2385 (let ((lang (or lang
"none")))
2386 (funcall wrap
(format "#+begin_src %s%s" lang results-switches
)
2388 (format "{{{results(src_%s[%s]{" lang results-switches
)
2390 ((member "raw" result-params
)
2391 (goto-char beg
) (when (org-at-table-p) (org-cycle)))
2392 ((or (member "drawer" result-params
)
2393 ;; Stay backward compatible with <7.9.2
2394 (member "wrap" result-params
))
2395 (goto-char beg
) (when (org-at-table-p) (org-cycle))
2396 (funcall wrap
":results:" ":end:" 'no-escape nil
2397 "{{{results(" ")}}}"))
2398 ((and inline
(member "file" result-params
))
2399 (funcall wrap nil nil nil nil
"{{{results(" ")}}}"))
2400 ((and (not (funcall tabulablep result
))
2401 (not (member "file" result-params
)))
2402 (let ((org-babel-inline-result-wrap
2403 ;; Hard code {{{results(...)}}} on top of
2405 (format "{{{results(%s)}}}"
2406 org-babel-inline-result-wrap
)))
2407 (org-babel-examplify-region
2408 beg end results-switches inline
)))))
2409 ;; Possibly indent results in par with #+results line.
2410 (when (and (not inline
) (numberp indent
) (> indent
0)
2411 ;; In this case `table-align' does the work
2413 (not (and (listp result
)
2414 (member "append" result-params
))))
2415 (indent-rigidly beg end indent
))
2417 (if (member "value" result-params
)
2418 (message "Code block returned no value.")
2419 (message "Code block produced no output."))
2420 (message "Code block evaluation complete.")))
2421 (set-marker end nil
)
2422 (when outside-scope
(narrow-to-region visible-beg visible-end
))
2423 (set-marker visible-beg nil
)
2424 (set-marker visible-end nil
)))))))
2426 (defun org-babel-remove-result (&optional info keep-keyword
)
2427 "Remove the result of the current source block."
2429 (let ((location (org-babel-where-is-src-block-result nil info
)))
2432 (goto-char location
)
2433 (when (looking-at (concat org-babel-result-regexp
".*$"))
2435 (if keep-keyword
(line-beginning-position 2)
2437 (skip-chars-backward " \r\t\n")
2438 (line-beginning-position 2)))
2439 (progn (forward-line) (org-babel-result-end))))))))
2441 (defun org-babel-remove-inline-result (&optional datum
)
2442 "Remove the result of the current inline-src-block or babel call.
2443 The result must be wrapped in a `results' macro to be removed.
2444 Leading white space is trimmed."
2446 (let* ((el (or datum
(org-element-context))))
2447 (when (memq (org-element-type el
) '(inline-src-block inline-babel-call
))
2448 (org-with-wide-buffer
2449 (goto-char (org-element-property :end el
))
2450 (skip-chars-backward " \t")
2451 (let ((result (save-excursion
2454 (org-element-property
2455 :contents-end
(org-element-property :parent el
)))
2456 (org-element-context))))
2457 (when (and (eq (org-element-type result
) 'macro
)
2458 (string= (org-element-property :key result
) "results"))
2459 (delete-region ; And leading whitespace.
2461 (progn (goto-char (org-element-property :end result
))
2462 (skip-chars-backward " \t\n")
2465 (defun org-babel-remove-result-one-or-many (x)
2466 "Remove the result of the current source block.
2467 If called with a prefix argument, remove all result blocks
2471 (org-babel-map-src-blocks nil
(org-babel-remove-result))
2472 (org-babel-remove-result)))
2474 (defun org-babel-result-end ()
2475 "Return the point at the end of the current set of results."
2476 (cond ((looking-at-p "^[ \t]*$") (point)) ;no result
2477 ((looking-at-p (format "^[ \t]*%s[ \t]*$" org-bracket-link-regexp
))
2478 (line-beginning-position 2))
2480 (let ((element (org-element-at-point)))
2481 (if (memq (org-element-type element
)
2482 ;; Possible results types.
2483 '(drawer example-block export-block fixed-width item
2484 plain-list src-block table
))
2486 (goto-char (min (point-max) ;for narrowed buffers
2487 (org-element-property :end element
)))
2488 (skip-chars-backward " \r\t\n")
2489 (line-beginning-position 2))
2492 (defun org-babel-result-to-file (result &optional description
)
2493 "Convert RESULT into an Org link with optional DESCRIPTION.
2494 If the `default-directory' is different from the containing
2495 file's directory then expand relative links."
2496 (when (stringp result
)
2497 (let ((same-directory?
2498 (and buffer-file-name
2499 (not (string= (expand-file-name default-directory
)
2501 (file-name-directory buffer-file-name
)))))))
2502 (format "[[file:%s]%s]"
2503 (if (and default-directory buffer-file-name same-directory?
)
2504 (if (eq org-link-file-path-type
'adaptive
)
2506 (expand-file-name result default-directory
)
2507 (file-name-directory (buffer-file-name)))
2508 (expand-file-name result default-directory
))
2510 (if description
(concat "[" description
"]") "")))))
2512 (defun org-babel-examplify-region (beg end
&optional results-switches inline
)
2513 "Comment out region using the inline `==' or `: ' org example quote."
2517 (if org-babel-uppercase-example-markers
(upcase str
) str
))))
2521 (insert (format org-babel-inline-result-wrap
2522 (delete-and-extract-region beg end
))))
2523 (let ((size (count-lines beg end
)))
2525 (cond ((= size
0)) ; do nothing for an empty result
2526 ((< size org-babel-min-lines-for-block-output
)
2529 (beginning-of-line 1) (insert ": ") (forward-line 1)))
2532 (insert (if results-switches
2534 (funcall maybe-cap
"#+begin_example")
2536 (funcall maybe-cap
"#+begin_example\n")))
2538 (if (markerp end
) (goto-char end
) (forward-char (- end beg
)))
2539 (org-escape-code-in-region p
(point)))
2540 (insert (funcall maybe-cap
"#+end_example\n")))))))))
2542 (defun org-babel-update-block-body (new-body)
2543 "Update the body of the current code block to NEW-BODY."
2544 (let ((element (org-element-at-point)))
2545 (unless (eq (org-element-type element
) 'src-block
)
2546 (error "Not in a source block"))
2547 (goto-char (org-babel-where-is-src-block-head element
))
2548 (let* ((ind (current-indentation))
2549 (body-start (line-beginning-position 2))
2550 (body (org-element-normalize-string
2551 (if (or org-src-preserve-indentation
2552 (org-element-property :preserve-indent element
))
2555 (insert (org-remove-indentation new-body
))
2559 (+ ind org-edit-src-content-indentation
))
2560 (buffer-string))))))
2561 (delete-region body-start
2562 (org-with-wide-buffer
2563 (goto-char (org-element-property :end element
))
2564 (skip-chars-backward " \t\n")
2565 (line-beginning-position)))
2566 (goto-char body-start
)
2569 (defun org-babel-merge-params (&rest plists
)
2570 "Combine all parameter association lists in PLISTS.
2571 Later elements of PLISTS override the values of previous elements.
2572 This takes into account some special considerations for certain
2573 parameters when merging lists."
2574 (let* ((results-exclusive-groups
2575 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2576 (cdr (assq 'results org-babel-common-header-args-w-values
))))
2577 (exports-exclusive-groups
2578 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2579 (cdr (assq 'exports org-babel-common-header-args-w-values
))))
2581 (lambda (exclusive-groups &rest result-params
)
2582 ;; Maintain exclusivity of mutually exclusive parameters,
2583 ;; as defined in EXCLUSIVE-GROUPS while merging lists in
2586 (dolist (new-params result-params
(delete-dups output
))
2587 (dolist (new-param new-params
)
2588 (dolist (exclusive-group exclusive-groups
)
2589 (when (member new-param exclusive-group
)
2590 (setq output
(cl-remove-if
2591 (lambda (o) (member o exclusive-group
))
2593 (push new-param output
))))))
2594 (variable-index 0) ;Handle positional arguments.
2596 params
;Final parameters list.
2597 ;; Some keywords accept multiple values. We need to treat
2599 vars results exports
)
2600 (dolist (plist plists
)
2601 (dolist (pair plist
)
2605 ((listp value
) (car value
))
2606 ((string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*=" value
)
2607 (intern (match-string 1 value
)))
2612 (append (if (not (assoc name vars
)) vars
2613 (push name clearnames
)
2614 (cl-remove-if (lambda (p) (equal name
(car p
)))
2616 (list (cons name pair
)))))
2617 ((and vars
(nth variable-index vars
))
2618 ;; If no name is given and we already have named
2619 ;; variables then assign to named variables in order.
2620 (let ((name (car (nth variable-index vars
))))
2621 ;; Clear out colnames and rownames for replace vars.
2622 (push name clearnames
)
2623 (setf (cddr (nth variable-index vars
))
2624 (concat (symbol-name name
) "=" value
))
2625 (cl-incf variable-index
)))
2626 (t (error "Variable \"%s\" must be assigned a default value"
2628 (`(:results .
,value
)
2629 (setq results
(funcall merge
2630 results-exclusive-groups
2633 (if (stringp value
) value
(eval value t
))))))
2634 (`(,(or :file
:file-ext
) .
,value
)
2635 ;; `:file' and `:file-ext' are regular keywords but they
2636 ;; imply a "file" `:results' and a "results" `:exports'.
2639 (funcall merge results-exclusive-groups results
'("file")))
2640 (unless (or (member "both" exports
)
2641 (member "none" exports
)
2642 (member "code" exports
))
2645 exports-exclusive-groups exports
'("results"))))
2646 (push pair params
)))
2647 (`(:exports .
,value
)
2648 (setq exports
(funcall merge
2649 exports-exclusive-groups
2651 (split-string (or value
"")))))
2652 ;; Regular keywords: any value overwrites the previous one.
2653 (_ (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))))
2654 ;; Handle `:var' and clear out colnames and rownames for replaced
2656 (setq params
(nconc (mapcar (lambda (v) (cons :var
(cddr v
))) vars
)
2658 (dolist (name clearnames
)
2659 (dolist (param '(:colname-names
:rowname-names
))
2660 (when (assq param params
)
2661 (setf (cdr (assq param params
))
2662 (cl-remove-if (lambda (pair) (equal name
(car pair
)))
2663 (cdr (assq param params
))))
2665 (cl-remove-if (lambda (pair) (and (equal (car pair
) param
)
2668 ;; Handle other special keywords, which accept multiple values.
2669 (setq params
(nconc (list (cons :results
(mapconcat #'identity results
" "))
2670 (cons :exports
(mapconcat #'identity exports
" ")))
2672 ;; Return merged params.
2675 (defun org-babel-noweb-p (params context
)
2676 "Check if PARAMS require expansion in CONTEXT.
2677 CONTEXT may be one of :tangle, :export or :eval."
2678 (let ((allowed-values (cl-case context
2679 (:tangle
'("yes" "tangle" "no-export" "strip-export"))
2680 (:eval
'("yes" "no-export" "strip-export" "eval"))
2681 (:export
'("yes")))))
2682 (cl-some (lambda (v) (member v allowed-values
))
2683 (split-string (or (cdr (assq :noweb params
)) "")))))
2685 (defun org-babel-expand-noweb-references (&optional info parent-buffer
)
2686 "Expand Noweb references in the body of the current source code block.
2688 For example the following reference would be replaced with the
2689 body of the source-code block named `example-block'.
2693 Note that any text preceding the <<foo>> construct on a line will
2694 be interposed between the lines of the replacement text. So for
2695 example if <<foo>> is placed behind a comment, then the entire
2696 replacement text will also be commented.
2698 This function must be called from inside of the buffer containing
2699 the source-code block which holds BODY.
2701 In addition the following syntax can be used to insert the
2702 results of evaluating the source-code block named `example-block'.
2706 Any optional arguments can be passed to example-block by placing
2707 the arguments inside the parenthesis following the convention
2708 defined by `org-babel-lob'. For example
2710 <<example-block(a=9)>>
2712 would set the value of argument \"a\" equal to \"9\". Note that
2713 these arguments are not evaluated in the current source-code
2714 block but are passed literally to the \"example-block\"."
2715 (let* ((parent-buffer (or parent-buffer
(current-buffer)))
2716 (info (or info
(org-babel-get-src-block-info 'light
)))
2719 (ob-nww-start org-babel-noweb-wrap-start
)
2720 (ob-nww-end org-babel-noweb-wrap-end
)
2722 (nb-add (lambda (text) (setq new-body
(concat new-body text
))))
2723 index source-name evaluate prefix
)
2725 (setq-local org-babel-noweb-wrap-start ob-nww-start
)
2726 (setq-local org-babel-noweb-wrap-end ob-nww-end
)
2727 (insert body
) (goto-char (point-min))
2728 (setq index
(point))
2729 (while (and (re-search-forward (org-babel-noweb-wrap) nil t
))
2730 (save-match-data (setf source-name
(match-string 1)))
2731 (save-match-data (setq evaluate
(string-match "(.*)" source-name
)))
2734 (buffer-substring (match-beginning 0)
2736 (beginning-of-line 1) (point)))))
2737 ;; add interval to new-body (removing noweb reference)
2738 (goto-char (match-beginning 0))
2739 (funcall nb-add
(buffer-substring index
(point)))
2740 (goto-char (match-end 0))
2741 (setq index
(point))
2744 (with-current-buffer parent-buffer
2747 (mapconcat ;; Interpose PREFIX between every line.
2751 (let ((raw (org-babel-ref-resolve source-name
)))
2752 (if (stringp raw
) raw
(format "%S" raw
)))
2754 ;; Retrieve from the Library of Babel.
2755 (nth 2 (assoc-string source-name org-babel-library-of-babel
))
2756 ;; Return the contents of headlines literally.
2758 (when (org-babel-ref-goto-headline-id source-name
)
2759 (org-babel-ref-headline-body)))
2760 ;; Find the expansion of reference in this buffer.
2762 (goto-char (point-min))
2764 (org-babel-named-src-block-regexp-for-name
2768 (cdr (assq :comments
(nth 2 info
)))))
2771 ;; Comment, according to LANG mode,
2772 ;; string S. Return new string.
2774 (funcall (intern (concat lang
"-mode")))
2775 (comment-region (point)
2776 (progn (insert s
) (point)))
2777 (org-trim (buffer-string)))))
2780 ;; Expand body of code blocked
2781 ;; represented by block info I.
2782 (let ((b (if (org-babel-noweb-p (nth 2 i
) :eval
)
2783 (org-babel-expand-noweb-references i
)
2786 (let ((cs (org-babel-tangle-comment-links i
)))
2787 (concat (funcall c-wrap
(car cs
)) "\n"
2789 (funcall c-wrap
(cadr cs
)))))))))
2790 (if (re-search-forward name-regexp nil t
)
2791 ;; Found a source block named SOURCE-NAME.
2792 ;; Assume it is unique; do not look after
2793 ;; `:noweb-ref' header argument.
2794 (funcall expand-body
2795 (org-babel-get-src-block-info 'light
))
2796 ;; Though luck. We go into the long process
2797 ;; of checking each source block and expand
2798 ;; those with a matching Noweb reference.
2799 (let ((expansion nil
))
2800 (org-babel-map-src-blocks nil
2801 (let* ((info (org-babel-get-src-block-info 'light
))
2802 (parameters (nth 2 info
)))
2803 (when (equal source-name
2804 (cdr (assq :noweb-ref parameters
)))
2805 (push (funcall expand-body info
) expansion
)
2806 (push (or (cdr (assq :noweb-sep parameters
))
2810 (mapconcat #'identity
2811 (nreverse (cdr expansion
))
2813 ;; Possibly raise an error if named block doesn't exist.
2814 (if (or org-babel-noweb-error-all-langs
2815 (member lang org-babel-noweb-error-langs
))
2816 (error "%s could not be resolved (see \
2817 `org-babel-noweb-error-langs')"
2818 (org-babel-noweb-wrap source-name
))
2821 (concat "\n" prefix
))))))
2822 (funcall nb-add
(buffer-substring index
(point-max))))
2825 (defun org-babel--script-escape-inner (str)
2826 (let (in-single in-double backslash out
)
2833 (setq backslash nil
)
2835 ((and in-single
(eq ch ?
'))
2836 ;; Escaped single quote inside single quoted string:
2837 ;; emit just a single quote, since we've changed the
2838 ;; outer quotes to double.
2841 ;; Escaped double quote
2843 ;; This should be interpreted as backslash+quote,
2844 ;; not an escape. Emit a three backslashes
2845 ;; followed by a quote (because one layer of
2846 ;; quoting will be stripped by `org-babel-read').
2847 (append (list ch ?
\\ ?
\\ ?
\\) out
)
2848 ;; Otherwise we are in a double-quoted string. Emit
2849 ;; a single escaped quote
2850 (append (list ch ?
\\) out
)))
2852 ;; Escaped backslash: emit a single escaped backslash
2853 (append (list ?
\\ ?
\\) out
))
2854 ;; Other: emit a quoted backslash followed by whatever
2855 ;; the character was (because one layer of quoting will
2856 ;; be stripped by `org-babel-read').
2857 (t (append (list ch ?
\\ ?
\\) out
))))
2859 (?\
[ (if (or in-double in-single
)
2862 (?\
] (if (or in-double in-single
)
2865 (?\
{ (if (or in-double in-single
)
2868 (?\
} (if (or in-double in-single
)
2871 (?
, (if (or in-double in-single
)
2872 (cons ?
, out
) (cons ?\s out
)))
2875 (setq in-single
(not in-single
)) (cons ?
\" out
)))
2877 (append (list ?
\" ?
\\) out
)
2878 (setq in-double
(not in-double
)) (cons ?
\" out
)))
2879 (?
\\ (unless (or in-single in-double
)
2880 (error "Can't handle backslash outside string in `org-babel-script-escape'"))
2883 (t (cons ch out
))))))
2884 (string-to-list str
))
2885 (when (or in-single in-double
)
2886 (error "Unterminated string in `org-babel-script-escape'"))
2887 (apply #'string
(reverse out
))))
2889 (defun org-babel-script-escape (str &optional force
)
2890 "Safely convert tables into elisp lists."
2891 (unless (stringp str
)
2892 (error "`org-babel-script-escape' expects a string"))
2895 ((and (> (length str
) 2)
2896 (or (and (string-equal "[" (substring str
0 1))
2897 (string-equal "]" (substring str -
1)))
2898 (and (string-equal "{" (substring str
0 1))
2899 (string-equal "}" (substring str -
1)))
2900 (and (string-equal "(" (substring str
0 1))
2901 (string-equal ")" (substring str -
1)))))
2903 (concat "'" (org-babel--script-escape-inner str
)))
2905 (and (> (length str
) 2)
2906 (or (and (string-equal "'" (substring str
0 1))
2907 (string-equal "'" (substring str -
1)))
2908 ;; We need to pass double-quoted strings
2909 ;; through the backslash-twiddling bits, even
2910 ;; though we don't need to change their
2912 (and (string-equal "\"" (substring str
0 1))
2913 (string-equal "\"" (substring str -
1))))))
2914 (org-babel--script-escape-inner str
))
2916 (condition-case nil
(org-babel-read escaped
) (error escaped
))))
2918 (defun org-babel-read (cell &optional inhibit-lisp-eval
)
2919 "Convert the string value of CELL to a number if appropriate.
2920 Otherwise if CELL looks like lisp (meaning it starts with a
2921 \"(\", \"\\='\", \"\\=`\" or a \"[\") then read and evaluate it as
2922 lisp, otherwise return it unmodified as a string. Optional
2923 argument INHIBIT-LISP-EVAL inhibits lisp evaluation for
2924 situations in which is it not appropriate."
2925 (cond ((not (org-string-nw-p cell
)) cell
)
2926 ((org-babel--string-to-number cell
))
2927 ((and (not inhibit-lisp-eval
)
2928 (or (memq (string-to-char cell
) '(?\
( ?
' ?
` ?\
[))
2929 (string= cell
"*this*")))
2930 (eval (read cell
) t
))
2931 ((eq (string-to-char cell
) ?
\") (read cell
))
2932 (t (org-no-properties cell
))))
2934 (defun org-babel--string-to-number (string)
2935 "If STRING represents a number return its value.
2936 Otherwise return nil."
2937 (and (string-match-p "\\`-?[0-9]*\\.?[0-9]*\\'" string
)
2938 (string-to-number string
)))
2940 (defun org-babel-import-elisp-from-file (file-name &optional separator
)
2941 "Read the results located at FILE-NAME into an elisp table.
2942 If the table is trivial, then return it as a scalar."
2944 (save-window-excursion
2948 (org-table-import file-name separator
)
2949 (delete-file file-name
)
2950 (setq result
(mapcar (lambda (row)
2951 (mapcar #'org-babel-string-read row
))
2952 (org-table-to-lisp))))
2953 (error (message "Error reading results: %s" err
) nil
)))
2954 (if (null (cdr result
)) ;; if result is trivial vector, then scalarize it
2955 (if (consp (car result
))
2956 (if (null (cdr (car result
)))
2962 (defun org-babel-string-read (cell)
2963 "Strip nested \"s from around strings."
2964 (org-babel-read (or (and (stringp cell
)
2965 (string-match "\\\"\\(.+\\)\\\"" cell
)
2966 (match-string 1 cell
))
2969 (defun org-babel-chomp (string &optional regexp
)
2970 "Strip a trailing space or carriage return from STRING.
2971 The default regexp used is \"[ \\f\\t\\n\\r\\v]\" but another one
2972 can be specified as the REGEXP argument."
2973 (let ((regexp (or regexp
"[ \f\t\n\r\v]")))
2974 (while (and (> (length string
) 0)
2975 (string-match regexp
(substring string -
1)))
2976 (setq string
(substring string
0 -
1)))
2979 (defun org-babel-process-file-name (name &optional no-quote-p
)
2980 "Prepare NAME to be used in an external process.
2981 If NAME specifies a remote location, the remote portion of the
2982 name is removed, since in that case the process will be executing
2983 remotely. The file name is then processed by `expand-file-name'.
2984 Unless second argument NO-QUOTE-P is non-nil, the file name is
2985 additionally processed by `shell-quote-argument'"
2986 (let ((f (org-babel-local-file-name (expand-file-name name
))))
2987 (if no-quote-p f
(shell-quote-argument f
))))
2989 (defvar org-babel-temporary-directory
)
2990 (unless (or noninteractive
(boundp 'org-babel-temporary-directory
))
2991 (defvar org-babel-temporary-directory
2992 (or (and (boundp 'org-babel-temporary-directory
)
2993 (file-exists-p org-babel-temporary-directory
)
2994 org-babel-temporary-directory
)
2995 (make-temp-file "babel-" t
))
2996 "Directory to hold temporary files created to execute code blocks.
2997 Used by `org-babel-temp-file'. This directory will be removed on
3000 (defcustom org-babel-remote-temporary-directory
"/tmp/"
3001 "Directory to hold temporary files on remote hosts."
3005 (defmacro org-babel-result-cond
(result-params scalar-form
&rest table-forms
)
3006 "Call the code to parse raw string results according to RESULT-PARAMS."
3008 (debug (form form
&rest form
)))
3009 (org-with-gensyms (params)
3010 `(let ((,params
,result-params
))
3011 (unless (member "none" ,params
)
3012 (if (or (member "scalar" ,params
)
3013 (member "verbatim" ,params
)
3014 (member "html" ,params
)
3015 (member "code" ,params
)
3016 (member "pp" ,params
)
3017 (member "file" ,params
)
3018 (and (or (member "output" ,params
)
3019 (member "raw" ,params
)
3020 (member "org" ,params
)
3021 (member "drawer" ,params
))
3022 (not (member "table" ,params
))))
3025 (def-edebug-spec org-babel-result-cond
(form form body
))
3027 (defun org-babel-temp-file (prefix &optional suffix
)
3028 "Create a temporary file in the `org-babel-temporary-directory'.
3029 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
3030 value of `temporary-file-directory' temporarily set to the value
3031 of `org-babel-temporary-directory'."
3032 (if (file-remote-p default-directory
)
3034 (concat (file-remote-p default-directory
)
3036 prefix org-babel-remote-temporary-directory
))))
3037 (make-temp-file prefix nil suffix
))
3038 (let ((temporary-file-directory
3039 (or (and (boundp 'org-babel-temporary-directory
)
3040 (file-exists-p org-babel-temporary-directory
)
3041 org-babel-temporary-directory
)
3042 temporary-file-directory
)))
3043 (make-temp-file prefix nil suffix
))))
3045 (defun org-babel-remove-temporary-directory ()
3046 "Remove `org-babel-temporary-directory' on Emacs shutdown."
3047 (when (and (boundp 'org-babel-temporary-directory
)
3048 (file-exists-p org-babel-temporary-directory
))
3049 ;; taken from `delete-directory' in files.el
3052 (mapc (lambda (file)
3053 ;; This test is equivalent to
3054 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
3055 ;; but more efficient
3056 (if (eq t
(car (file-attributes file
)))
3057 (delete-directory file
)
3058 (delete-file file
)))
3059 ;; We do not want to delete "." and "..".
3060 (directory-files org-babel-temporary-directory
'full
3061 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
3062 (delete-directory org-babel-temporary-directory
))
3064 (message "Failed to remove temporary Org-babel directory %s"
3065 (if (boundp 'org-babel-temporary-directory
)
3066 org-babel-temporary-directory
3067 "[directory not defined]"))))))
3069 (add-hook 'kill-emacs-hook
'org-babel-remove-temporary-directory
)
3071 (defun org-babel-one-header-arg-safe-p (pair safe-list
)
3072 "Determine if the PAIR is a safe babel header arg according to SAFE-LIST.
3074 For the format of SAFE-LIST, see `org-babel-safe-header-args'."
3076 (keywordp (car pair
))
3077 (stringp (cdr pair
))
3079 (memq (car pair
) safe-list
)
3080 (let ((entry (assq (car pair
) safe-list
)))
3083 (cond ((functionp (cdr entry
))
3084 (funcall (cdr entry
) (cdr pair
)))
3085 ((listp (cdr entry
))
3086 (member (cdr pair
) (cdr entry
)))
3089 (defun org-babel-generate-file-param (src-name params
)
3090 "Calculate the filename for source block results.
3092 The directory is calculated from the :output-dir property of the
3093 source block; if not specified, use the current directory.
3095 If the source block has a #+NAME and the :file parameter does not
3096 contain any period characters, then the :file parameter is
3097 treated as an extension, and the output file name is the
3098 concatenation of the directory (as calculated above), the block
3099 name, a period, and the parameter value as a file extension.
3100 Otherwise, the :file parameter is treated as a full file name,
3101 and the output file name is the directory (as calculated above)
3102 plus the parameter value."
3103 (let* ((file-cons (assq :file params
))
3104 (file-ext-cons (assq :file-ext params
))
3105 (file-ext (cdr-safe file-ext-cons
))
3106 (dir (cdr-safe (assq :output-dir params
)))
3108 ;; create the output-dir if it does not exist
3110 (make-directory dir t
))
3112 ;; :file given; add :output-dir if given
3114 (setcdr file-cons
(concat (file-name-as-directory dir
) (cdr file-cons
))))
3115 ;; :file not given; compute from name and :file-ext if possible
3116 (when (and src-name file-ext
)
3118 (setq fname
(concat (file-name-as-directory (or dir
""))
3119 src-name
"." file-ext
))
3120 (setq fname
(concat src-name
"." file-ext
)))
3121 (setq params
(cons (cons :file fname
) params
))))
3124 (defun org-babel-graphical-output-file (params)
3125 "File where a babel block should send graphical output, per PARAMS.
3126 Return nil if no graphical output is expected. Raise an error if
3127 the output file is ill-defined."
3128 (let ((file (cdr (assq :file params
))))
3129 (cond (file (and (member "graphics" (cdr (assq :result-params params
)))
3131 ((assq :file-ext params
)
3132 (user-error ":file-ext given but no :file generated; did you forget \
3134 (t (user-error "No :file header argument given; cannot create \
3135 graphical result")))))
3137 (defun org-babel-make-language-alias (new old
)
3138 "Make source blocks of type NEW aliases for those of type OLD.
3140 NEW and OLD should be strings. This function should be called
3141 after the babel API for OLD-type source blocks is fully defined.
3143 Callers of this function will probably want to add an entry to
3144 `org-src-lang-modes' as well."
3145 (dolist (fn '("execute" "expand-body" "prep-session"
3146 "variable-assignments" "load-session"))
3147 (let ((sym (intern-soft (concat "org-babel-" fn
":" old
))))
3148 (when (and sym
(fboundp sym
))
3149 (defalias (intern (concat "org-babel-" fn
":" new
)) sym
))))
3150 ;; Technically we don't need a `dolist' for just one variable, but
3151 ;; we keep it for symmetry/ease of future expansion.
3152 (dolist (var '("default-header-args"))
3153 (let ((sym (intern-soft (concat "org-babel-" var
":" old
))))
3154 (when (and sym
(boundp sym
))
3155 (defvaralias (intern (concat "org-babel-" var
":" new
)) sym
)))))
3157 (defun org-babel-strip-quotes (string)
3158 "Strip \\\"s from around a string, if applicable."
3159 (org-unbracket-string "\"" "\"" string
))
3164 ;; generated-autoload-file: "org-loaddefs.el"
3167 ;;; ob-core.el ends here