1 ;;; ob-core.el --- Working with Code Blocks -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
5 ;; Authors: Eric Schulte
7 ;; Keywords: literate programming, reproducible research
8 ;; Homepage: http://orgmode.org
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
31 (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-src-lang-modes
)
39 (defvar org-src-preserve-indentation
)
41 (declare-function org-at-item-p
"org-list" ())
42 (declare-function org-at-table-p
"org" (&optional table-type
))
43 (declare-function org-babel-lob-execute-maybe
"ob-lob" ())
44 (declare-function org-babel-ref-goto-headline-id
"ob-ref" (id))
45 (declare-function org-babel-ref-headline-body
"ob-ref" ())
46 (declare-function org-babel-ref-parse
"ob-ref" (assignment))
47 (declare-function org-babel-ref-resolve
"ob-ref" (ref))
48 (declare-function org-babel-ref-split-args
"ob-ref" (arg-string))
49 (declare-function org-babel-tangle-comment-links
"ob-tangle" (&optional info
))
50 (declare-function org-completing-read
"org" (&rest args
))
51 (declare-function org-current-level
"org" ())
52 (declare-function org-cycle
"org" (&optional arg
))
53 (declare-function org-do-remove-indentation
"org" (&optional n
))
54 (declare-function org-edit-src-code
"org-src" (&optional code edit-buffer-name
))
55 (declare-function org-edit-src-exit
"org-src" ())
56 (declare-function org-element-at-point
"org-element" ())
57 (declare-function org-element-context
"org-element" (&optional element
))
58 (declare-function org-element-normalize-string
"org-element" (s))
59 (declare-function org-element-property
"org-element" (property element
))
60 (declare-function org-element-type
"org-element" (element))
61 (declare-function org-entry-get
"org" (pom property
&optional inherit literal-nil
))
62 (declare-function org-escape-code-in-region
"org-src" (beg end
))
63 (declare-function org-get-indentation
"org" (&optional line
))
64 (declare-function org-get-indentation
"org" (&optional line
))
65 (declare-function org-in-regexp
"org" (regexp &optional nlines visually
))
66 (declare-function org-indent-line
"org" ())
67 (declare-function org-list-get-list-end
"org-list" (item struct prevs
))
68 (declare-function org-list-prevs-alist
"org-list" (struct))
69 (declare-function org-list-struct
"org-list" ())
70 (declare-function org-list-to-generic
"org-list" (LIST PARAMS
))
71 (declare-function org-list-to-lisp
"org-list" (&optional delete
))
72 (declare-function org-macro-escape-arguments
"org-macro" (&rest args
))
73 (declare-function org-make-options-regexp
"org" (kwds &optional extra
))
74 (declare-function org-mark-ring-push
"org" (&optional pos buffer
))
75 (declare-function org-narrow-to-subtree
"org" ())
76 (declare-function org-next-block
"org" (arg &optional backward block-regexp
))
77 (declare-function org-number-sequence
"org-compat" (from &optional to inc
))
78 (declare-function org-open-at-point
"org" (&optional in-emacs reference-buffer
))
79 (declare-function org-outline-overlay-data
"org" (&optional use-markers
))
80 (declare-function org-previous-block
"org" (arg &optional block-regexp
))
81 (declare-function org-remove-indentation
"org" (code &optional n
))
82 (declare-function org-reverse-string
"org" (string))
83 (declare-function org-set-outline-overlay-data
"org" (data))
84 (declare-function org-show-context
"org" (&optional key
))
85 (declare-function org-src-coderef-format
"org-src" (element))
86 (declare-function org-src-coderef-regexp
"org-src" (fmt &optional label
))
87 (declare-function org-table-align
"org-table" ())
88 (declare-function org-table-end
"org-table" (&optional table-type
))
89 (declare-function org-table-import
"org-table" (file arg
))
90 (declare-function org-table-to-lisp
"org-table" (&optional txt
))
91 (declare-function org-trim
"org" (s &optional keep-lead
))
92 (declare-function org-unescape-code-in-string
"org-src" (s))
93 (declare-function org-uniquify
"org" (list))
94 (declare-function orgtbl-to-generic
"org-table" (table params
))
95 (declare-function orgtbl-to-orgtbl
"org-table" (table params
))
96 (declare-function outline-show-all
"outline" ())
97 (declare-function tramp-compat-make-temp-file
"tramp-compat" (filename &optional dir-flag
))
99 (defgroup org-babel nil
100 "Code block evaluation and management in `org-mode' documents."
104 (defcustom org-confirm-babel-evaluate t
105 "Confirm before evaluation.
107 Require confirmation before interactively evaluating code
108 blocks in Org buffers. The default value of this variable is t,
109 meaning confirmation is required for any code block evaluation.
110 This variable can be set to nil to inhibit any future
111 confirmation requests. This variable can also be set to a
112 function which takes two arguments the language of the code block
113 and the body of the code block. Such a function should then
114 return a non-nil value if the user should be prompted for
115 execution or nil if no prompt is required.
117 Warning: Disabling confirmation may result in accidental
118 evaluation of potentially harmful code. It may be advisable
119 remove code block execution from `\\[org-ctrl-c-ctrl-c]' \
120 as further protection
121 against accidental code block evaluation. The
122 `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
123 remove code block execution from the `\\[org-ctrl-c-ctrl-c]' keybinding."
126 :type
'(choice boolean function
))
127 ;; don't allow this variable to be changed through file settings
128 (put 'org-confirm-babel-evaluate
'safe-local-variable
(lambda (x) (eq x t
)))
130 (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
132 Remove code block evaluation from the `\\[org-ctrl-c-ctrl-c]' key binding."
137 (defcustom org-babel-results-keyword
"RESULTS"
138 "Keyword used to name results generated by code blocks.
139 It should be \"RESULTS\". However any capitalization may be
143 :package-version
'(Org .
"8.0")
147 (eq (compare-strings "RESULTS" nil nil v nil nil t
)
150 (defcustom org-babel-noweb-wrap-start
"<<"
151 "String used to begin a noweb reference in a code block.
152 See also `org-babel-noweb-wrap-end'."
156 (defcustom org-babel-noweb-wrap-end
">>"
157 "String used to end a noweb reference in a code block.
158 See also `org-babel-noweb-wrap-start'."
162 (defcustom org-babel-inline-result-wrap
"=%s="
163 "Format string used to wrap inline results.
164 This string must include a \"%s\" which will be replaced by the results."
167 (put 'org-babel-inline-result-wrap
171 (string-match-p "%s" value
))))
173 (defcustom org-babel-hash-show-time nil
174 "Non-nil means show the time the code block was evaluated in the result hash."
178 :package-version
'(Org .
"9.0")
181 (defcustom org-babel-uppercase-example-markers nil
182 "When non-nil, begin/end example markers will be inserted in upper case."
186 :package-version
'(Org .
"9.1")
189 (defun org-babel-noweb-wrap (&optional regexp
)
190 (concat org-babel-noweb-wrap-start
191 (or regexp
"\\([^ \t\n].+?[^ \t]\\|[^ \t\n]\\)")
192 org-babel-noweb-wrap-end
))
194 (defvar org-babel-src-name-regexp
195 "^[ \t]*#\\+name:[ \t]*"
196 "Regular expression used to match a source name line.")
198 (defvar org-babel-multi-line-header-regexp
199 "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
200 "Regular expression used to match multi-line header arguments.")
202 (defvar org-babel-src-block-regexp
204 ;; (1) indentation (2) lang
205 "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
207 "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
208 ;; (4) header arguments
211 "\\([^\000]*?\n\\)??[ \t]*#\\+end_src")
212 "Regexp used to identify code blocks.")
214 (defun org-babel--get-vars (params)
215 "Return the babel variable assignments in PARAMS.
217 PARAMS is a quasi-alist of header args, which may contain
218 multiple entries for the key `:var'. This function returns a
219 list of the cdr of all the `:var' entries."
221 (cl-remove-if-not (lambda (x) (eq (car x
) :var
)) params
)))
223 (defvar org-babel-exp-reference-buffer nil
224 "Buffer containing original contents of the exported buffer.
225 This is used by Babel to resolve references in source blocks.
226 Its value is dynamically bound during export.")
228 (defun org-babel-check-confirm-evaluate (info)
229 "Check whether INFO allows code block evaluation.
231 Returns nil if evaluation is disallowed, t if it is
232 unconditionally allowed, and the symbol `query' if the user
233 should be asked whether to allow evaluation."
234 (let* ((headers (nth 2 info
))
235 (eval (or (cdr (assq :eval headers
))
236 (when (assq :noeval headers
) "no")))
237 (eval-no (member eval
'("no" "never")))
238 (export org-babel-exp-reference-buffer
)
239 (eval-no-export (and export
(member eval
'("no-export" "never-export"))))
240 (noeval (or eval-no eval-no-export
))
241 (query (or (equal eval
"query")
242 (and export
(equal eval
"query-export"))
243 (if (functionp org-confirm-babel-evaluate
)
245 (goto-char (nth 5 info
))
246 (funcall org-confirm-babel-evaluate
247 ;; language, code block body
248 (nth 0 info
) (nth 1 info
)))
249 org-confirm-babel-evaluate
))))
255 (defun org-babel-check-evaluate (info)
256 "Check if code block INFO should be evaluated.
257 Do not query the user, but do display an informative message if
258 evaluation is blocked. Returns non-nil if evaluation is not blocked."
259 (let ((confirmed (org-babel-check-confirm-evaluate info
)))
261 (message "Evaluation of this %s code block%sis disabled."
263 (let ((name (nth 4 info
)))
264 (if name
(format " (%s) " name
) " "))))
267 ;; Dynamically scoped for asynchronous export.
268 (defvar org-babel-confirm-evaluate-answer-no
)
270 (defun org-babel-confirm-evaluate (info)
271 "Confirm evaluation of the code block INFO.
273 This query can also be suppressed by setting the value of
274 `org-confirm-babel-evaluate' to nil, in which case all future
275 interactive code block evaluations will proceed without any
276 confirmation from the user.
278 Note disabling confirmation may result in accidental evaluation
279 of potentially harmful code.
281 The variable `org-babel-confirm-evaluate-answer-no' is used by
282 the async export process, which requires a non-interactive
283 environment, to override this check."
284 (let* ((evalp (org-babel-check-confirm-evaluate info
))
287 (name-string (if name
(format " (%s) " name
) " ")))
292 (and (not (bound-and-true-p
293 org-babel-confirm-evaluate-answer-no
))
295 (format "Evaluate this %s code block%son your system? "
298 (message "Evaluation of this %s code block%sis aborted."
301 (x (error "Unexpected value `%s' from `org-babel-check-confirm-evaluate'" x
)))))
304 (defun org-babel-execute-safely-maybe ()
305 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
306 (org-babel-execute-maybe)))
309 (defun org-babel-execute-maybe ()
311 (or (org-babel-execute-src-block-maybe)
312 (org-babel-lob-execute-maybe)))
314 (defmacro org-babel-when-in-src-block
(&rest body
)
315 "Execute BODY if point is in a source block and return t.
317 Otherwise do nothing and return nil."
318 `(if (memq (org-element-type (org-element-context))
319 '(inline-src-block src-block
))
325 (defun org-babel-execute-src-block-maybe ()
326 "Conditionally execute a source block.
327 Detect if this is context for a Babel src-block and if so
328 then run `org-babel-execute-src-block'."
330 (org-babel-when-in-src-block
331 (org-babel-eval-wipe-error-buffer)
332 (org-babel-execute-src-block current-prefix-arg
)))
335 (defun org-babel-view-src-block-info ()
336 "Display information on the current source block.
337 This includes header arguments, language and name, and is largely
338 a window into the `org-babel-get-src-block-info' function."
340 (let ((info (org-babel-get-src-block-info 'light
))
341 (full (lambda (it) (> (length it
) 0)))
342 (printf (lambda (fmt &rest args
) (princ (apply #'format fmt args
)))))
344 (with-help-window (help-buffer)
345 (let ((name (nth 4 info
))
347 (switches (nth 3 info
))
348 (header-args (nth 2 info
)))
349 (when name
(funcall printf
"Name: %s\n" name
))
350 (when lang
(funcall printf
"Lang: %s\n" lang
))
351 (funcall printf
"Properties:\n")
352 (funcall printf
"\t:header-args \t%s\n" (org-entry-get (point) "header-args" t
))
353 (funcall printf
"\t:header-args:%s \t%s\n" lang
(org-entry-get (point) (concat "header-args:" lang
) t
))
355 (when (funcall full switches
) (funcall printf
"Switches: %s\n" switches
))
356 (funcall printf
"Header Arguments:\n")
357 (dolist (pair (sort header-args
358 (lambda (a b
) (string< (symbol-name (car a
))
359 (symbol-name (car b
))))))
360 (when (funcall full
(format "%s" (cdr pair
)))
361 (funcall printf
"\t%S%s\t%s\n"
363 (if (> (length (format "%S" (car pair
))) 7) "" "\t")
367 (defun org-babel-expand-src-block-maybe ()
368 "Conditionally expand a source block.
369 Detect if this is context for a org-babel src-block and if so
370 then run `org-babel-expand-src-block'."
372 (org-babel-when-in-src-block
373 (org-babel-expand-src-block current-prefix-arg
)))
376 (defun org-babel-load-in-session-maybe ()
377 "Conditionally load a source block in a session.
378 Detect if this is context for a org-babel src-block and if so
379 then run `org-babel-load-in-session'."
381 (org-babel-when-in-src-block
382 (org-babel-load-in-session current-prefix-arg
)))
384 (add-hook 'org-metaup-hook
'org-babel-load-in-session-maybe
)
387 (defun org-babel-pop-to-session-maybe ()
388 "Conditionally pop to a session.
389 Detect if this is context for a org-babel src-block and if so
390 then run `org-babel-switch-to-session'."
392 (org-babel-when-in-src-block
393 (org-babel-switch-to-session current-prefix-arg
)))
395 (add-hook 'org-metadown-hook
'org-babel-pop-to-session-maybe
)
397 (defconst org-babel-common-header-args-w-values
398 '((cache .
((no yes
)))
400 (colnames .
((nil no yes
)))
401 (comments .
((no link yes org both noweb
)))
403 (eval .
((yes no no-export strip-export never-export eval never
405 (exports .
((code results both none
)))
410 (hlines .
((no yes
)))
411 (mkdirp .
((yes no
)))
414 (noweb .
((yes no tangle no-export strip-export
)))
418 (padline .
((yes no
)))
421 (results .
((file list vector table scalar verbatim
)
422 (raw html latex org code pp drawer
)
423 (replace silent none append prepend
)
425 (rownames .
((no yes
)))
429 (tangle .
((tangle yes no
:any
)))
430 (tangle-mode .
((#o755
#o555
#o444
:any
)))
434 (defconst org-babel-header-arg-names
435 (mapcar #'car org-babel-common-header-args-w-values
)
436 "Common header arguments used by org-babel.
437 Note that individual languages may define their own language
438 specific header arguments as well.")
440 (defconst org-babel-safe-header-args
441 '(:cache
:colnames
:comments
:exports
:epilogue
:hlines
:noeval
442 :noweb
:noweb-ref
:noweb-sep
:padline
:prologue
:rownames
443 :sep
:session
:tangle
:wrap
444 (:eval .
("never" "query"))
445 (:results .
(lambda (str) (not (string-match "file" str
)))))
446 "A list of safe header arguments for babel source blocks.
448 The list can have entries of the following forms:
449 - :ARG -> :ARG is always a safe header arg
450 - (:ARG . (VAL1 VAL2 ...)) -> :ARG is safe as a header arg if it is
451 `equal' to one of the VALs.
452 - (:ARG . FN) -> :ARG is safe as a header arg if the function FN
453 returns non-nil. FN is passed one
454 argument, the value of the header arg
457 (defmacro org-babel-header-args-safe-fn
(safe-list)
458 "Return a function that determines whether a list of header args are safe.
461 \(put \\='org-babel-default-header-args \\='safe-local-variable
462 (org-babel-header-args-safe-p org-babel-safe-header-args)
464 This allows org-babel languages to extend the list of safe values for
465 their `org-babel-default-header-args:foo' variable.
467 For the format of SAFE-LIST, see `org-babel-safe-header-args'."
473 (org-babel-one-header-arg-safe-p pair
,safe-list
)))
476 (defvar org-babel-default-header-args
477 '((:session .
"none") (:results .
"replace") (:exports .
"code")
478 (:cache .
"no") (:noweb .
"no") (:hlines .
"no") (:tangle .
"no"))
479 "Default arguments to use when evaluating a source block.")
480 (put 'org-babel-default-header-args
'safe-local-variable
481 (org-babel-header-args-safe-fn org-babel-safe-header-args
))
483 (defvar org-babel-default-inline-header-args
484 '((:session .
"none") (:results .
"replace")
485 (:exports .
"results") (:hlines .
"yes"))
486 "Default arguments to use when evaluating an inline source block.")
487 (put 'org-babel-default-inline-header-args
'safe-local-variable
488 (org-babel-header-args-safe-fn org-babel-safe-header-args
))
490 (defconst org-babel-name-regexp
491 (format "^[ \t]*#\\+%s:[ \t]*"
492 ;; FIXME: TBLNAME is for backward compatibility.
493 (regexp-opt '("NAME" "TBLNAME")))
494 "Regexp matching a NAME keyword.")
496 (defconst org-babel-result-regexp
497 (format "^[ \t]*#\\+%s\\(?:\\[\\(?:%s \\)?\\([[:alnum:]]+\\)\\]\\)?:[ \t]*"
498 org-babel-results-keyword
499 ;; <%Y-%m-%d %H:%M:%S>
500 "<\\(?:[0-9]\\{4\\}-[0-1][0-9]-[0-3][0-9] \
501 [0-2][0-9]\\(?::[0-5][0-9]\\)\\{2\\}\\)>")
502 "Regular expression used to match result lines.
503 If the results are associated with a hash key then the hash will
504 be saved in match group 1.")
506 (defconst org-babel-result-w-name-regexp
507 (concat org-babel-result-regexp
"\\(?9:[^ \t\n\r\v\f]+\\)")
508 "Regexp matching a RESULTS keyword with a name.
509 Name is saved in match group 9.")
511 (defvar org-babel-min-lines-for-block-output
10
512 "The minimum number of lines for block output.
513 If number of lines of output is equal to or exceeds this
514 value, the output is placed in a #+begin_example...#+end_example
515 block. Otherwise the output is marked as literal by inserting
516 colons at the starts of the lines. This variable only takes
517 effect if the :results output option is in effect.")
519 (defvar org-babel-noweb-error-all-langs nil
520 "Raise errors when noweb references don't resolve.
521 Also see `org-babel-noweb-error-langs' to control noweb errors on
522 a language by language bases.")
524 (defvar org-babel-noweb-error-langs nil
525 "Languages for which Babel will raise literate programming errors.
526 List of languages for which errors should be raised when the
527 source code block satisfying a noweb reference in this language
528 can not be resolved. Also see `org-babel-noweb-error-all-langs'
529 to raise errors for all languages.")
531 (defvar org-babel-hash-show
4
532 "Number of initial characters to show of a hidden results hash.")
534 (defvar org-babel-after-execute-hook nil
535 "Hook for functions to be called after `org-babel-execute-src-block'")
537 (defun org-babel-named-src-block-regexp-for-name (&optional name
)
538 "This generates a regexp used to match a src block named NAME.
539 If NAME is nil, match any name. Matched name is then put in
540 match group 9. Other match groups are defined in
541 `org-babel-src-block-regexp'."
542 (concat org-babel-src-name-regexp
543 (concat (if name
(regexp-quote name
) "\\(?9:.*?\\)") "[ \t]*" )
544 "\\(?:\n[ \t]*#\\+\\S-+:.*\\)*?"
546 (substring org-babel-src-block-regexp
1)))
548 (defun org-babel-named-data-regexp-for-name (name)
549 "This generates a regexp used to match data named NAME."
550 (concat org-babel-name-regexp
(regexp-quote name
) "[ \t]*$"))
552 (defun org-babel--normalize-body (datum)
553 "Normalize body for element or object DATUM.
554 DATUM is a source block element or an inline source block object.
555 Remove final newline character and spurious indentation."
556 (let* ((value (org-element-property :value datum
))
557 (body (if (string-suffix-p "\n" value
)
558 (substring value
0 -
1)
560 (cond ((eq (org-element-type datum
) 'inline-src-block
)
561 ;; Newline characters and indentation in an inline
562 ;; src-block are not meaningful, since they could come from
563 ;; some paragraph filling. Treat them as a white space.
564 (replace-regexp-in-string "\n[ \t]*" " " body
))
565 ((or org-src-preserve-indentation
566 (org-element-property :preserve-indent datum
))
568 (t (org-remove-indentation body
)))))
571 (defvar org-babel-current-src-block-location nil
572 "Marker pointing to the src block currently being executed.
573 This may also point to a call line or an inline code block. If
574 multiple blocks are being executed (e.g., in chained execution
575 through use of the :var header argument) this marker points to
576 the outer-most code block.")
580 (defun org-babel-get-src-block-info (&optional light datum
)
581 "Extract information from a source block or inline source block.
583 Optional argument LIGHT does not resolve remote variable
584 references; a process which could likely result in the execution
585 of other code blocks.
587 By default, consider the block at point. However, when optional
588 argument DATUM is provided, extract information from that parsed
591 Return nil if point is not on a source block. Otherwise, return
592 a list with the following pattern:
594 (language body arguments switches name start coderef)"
595 (let* ((datum (or datum
(org-element-context)))
596 (type (org-element-type datum
))
597 (inline (eq type
'inline-src-block
)))
598 (when (memq type
'(inline-src-block src-block
))
599 (let* ((lang (org-element-property :language datum
))
600 (lang-headers (intern
601 (concat "org-babel-default-header-args:" lang
)))
602 (name (org-element-property :name datum
))
606 (org-babel--normalize-body datum
)
607 (apply #'org-babel-merge-params
608 (if inline org-babel-default-inline-header-args
609 org-babel-default-header-args
)
610 (and (boundp lang-headers
) (eval lang-headers t
))
612 ;; If DATUM is provided, make sure we get node
613 ;; properties applicable to its location within
615 (org-with-point-at (org-element-property :begin datum
)
616 (org-babel-params-from-properties lang
))
617 (mapcar #'org-babel-parse-header-arguments
618 (cons (org-element-property :parameters datum
)
619 (org-element-property :header datum
)))))
620 (or (org-element-property :switches datum
) "")
622 (org-element-property (if inline
:begin
:post-affiliated
)
624 (and (not inline
) (org-src-coderef-format datum
)))))
626 (setf (nth 2 info
) (org-babel-process-params (nth 2 info
))))
627 (setf (nth 2 info
) (org-babel-generate-file-param name
(nth 2 info
)))
631 (defun org-babel-execute-src-block (&optional arg info params
)
632 "Execute the current source code block.
633 Insert the results of execution into the buffer. Source code
634 execution and the collection and formatting of results can be
635 controlled through a variety of header arguments.
637 With prefix argument ARG, force re-execution even if an existing
638 result cached in the buffer would otherwise have been returned.
640 Optionally supply a value for INFO in the form returned by
641 `org-babel-get-src-block-info'.
643 Optionally supply a value for PARAMS which will be merged with
644 the header arguments specified at the front of the source code
647 (let* ((org-babel-current-src-block-location
648 (or org-babel-current-src-block-location
650 (org-babel-where-is-src-block-head)))
651 (info (if info
(copy-tree info
) (org-babel-get-src-block-info))))
652 ;; Merge PARAMS with INFO before considering source block
653 ;; evaluation since both could disagree.
654 (cl-callf org-babel-merge-params
(nth 2 info
) params
)
655 (when (org-babel-check-evaluate info
)
656 (cl-callf org-babel-process-params
(nth 2 info
))
657 (let* ((params (nth 2 info
))
658 (cache (let ((c (cdr (assq :cache params
))))
659 (and (not arg
) c
(string= "yes" c
))))
660 (new-hash (and cache
(org-babel-sha1-hash info
)))
661 (old-hash (and cache
(org-babel-current-result-hash)))
662 (current-cache (and new-hash
(equal new-hash old-hash
))))
665 (save-excursion ;Return cached result.
666 (goto-char (org-babel-where-is-src-block-result nil info
))
668 (skip-chars-forward " \t")
669 (let ((result (org-babel-read-result)))
670 (message (replace-regexp-in-string "%" "%%" (format "%S" result
)))
672 ((org-babel-confirm-evaluate info
)
673 (let* ((lang (nth 0 info
))
674 (result-params (cdr (assq :result-params params
)))
675 ;; Expand noweb references in BODY and remove any
678 (let ((coderef (nth 6 info
))
680 (if (org-babel-noweb-p params
:eval
)
681 (org-babel-expand-noweb-references info
)
683 (if (not coderef
) expand
684 (replace-regexp-in-string
685 (org-src-coderef-regexp coderef
) "" expand nil nil
1))))
686 (dir (cdr (assq :dir params
)))
688 (or (and dir
(file-name-as-directory (expand-file-name dir
)))
690 (cmd (intern (concat "org-babel-execute:" lang
)))
692 (unless (fboundp cmd
)
693 (error "No org-babel-execute function for %s!" lang
))
694 (message "executing %s code block%s..."
696 (let ((name (nth 4 info
)))
697 (if name
(format " (%s)" name
) "")))
698 (if (member "none" result-params
)
699 (progn (funcall cmd body params
)
700 (message "result silenced"))
702 (let ((r (funcall cmd body params
)))
703 (if (and (eq (cdr (assq :result-type params
)) 'value
)
704 (or (member "vector" result-params
)
705 (member "table" result-params
))
709 (let ((file (cdr (assq :file params
))))
710 ;; If non-empty result and :file then write to :file.
714 (insert (org-babel-format-result
715 result
(cdr (assq :sep params
))))))
717 ;; Possibly perform post process provided its
718 ;; appropriate. Dynamically bind "*this*" to the
719 ;; actual results of the block.
720 (let ((post (cdr (assq :post params
))))
722 (let ((*this
* (if (not file
) result
723 (org-babel-result-to-file
725 (let ((desc (assq :file-desc params
)))
726 (and desc
(or (cdr desc
) result
)))))))
727 (setq result
(org-babel-ref-resolve post
))
729 (setq result-params
(remove "file" result-params
))))))
730 (org-babel-insert-result
731 result result-params info new-hash lang
)))
732 (run-hooks 'org-babel-after-execute-hook
)
735 (defun org-babel-expand-body:generic
(body params
&optional var-lines
)
736 "Expand BODY with PARAMS.
737 Expand a block of code with org-babel according to its header
738 arguments. This generic implementation of body expansion is
739 called for languages which have not defined their own specific
740 org-babel-expand-body:lang function."
741 (let ((pro (cdr (assq :prologue params
)))
742 (epi (cdr (assq :epilogue params
))))
743 (mapconcat #'identity
744 (append (when pro
(list pro
))
747 (when epi
(list epi
)))
751 (defun org-babel-expand-src-block (&optional _arg info params
)
752 "Expand the current source code block.
753 Expand according to the source code block's header
754 arguments and pop open the results in a preview buffer."
756 (let* ((info (or info
(org-babel-get-src-block-info)))
758 (params (setf (nth 2 info
)
759 (sort (org-babel-merge-params (nth 2 info
) params
)
760 (lambda (el1 el2
) (string< (symbol-name (car el1
))
761 (symbol-name (car el2
)))))))
762 (body (setf (nth 1 info
)
763 (if (org-babel-noweb-p params
:eval
)
764 (org-babel-expand-noweb-references info
) (nth 1 info
))))
765 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
766 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
769 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
770 (org-babel-expand-body:generic
771 body params
(and (fboundp assignments-cmd
)
772 (funcall assignments-cmd params
))))))
773 (if (called-interactively-p 'any
)
775 expanded
(concat "*Org-Babel Preview " (buffer-name) "[ " lang
" ]*"))
778 (defun org-babel-edit-distance (s1 s2
)
779 "Return the edit (levenshtein) distance between strings S1 S2."
780 (let* ((l1 (length s1
))
782 (dist (vconcat (mapcar (lambda (_) (make-vector (1+ l2
) nil
))
783 (number-sequence 1 (1+ l1
)))))
784 (in (lambda (i j
) (aref (aref dist i
) j
))))
785 (setf (aref (aref dist
0) 0) 0)
786 (dolist (j (number-sequence 1 l2
))
787 (setf (aref (aref dist
0) j
) j
))
788 (dolist (i (number-sequence 1 l1
))
789 (setf (aref (aref dist i
) 0) i
)
790 (dolist (j (number-sequence 1 l2
))
791 (setf (aref (aref dist i
) j
)
793 (1+ (funcall in
(1- i
) j
))
794 (1+ (funcall in i
(1- j
)))
795 (+ (if (equal (aref s1
(1- i
)) (aref s2
(1- j
))) 0 1)
796 (funcall in
(1- i
) (1- j
)))))))
799 (defun org-babel-combine-header-arg-lists (original &rest others
)
800 "Combine a number of lists of header argument names and arguments."
801 (let ((results (copy-sequence original
)))
802 (dolist (new-list others
)
803 (dolist (arg-pair new-list
)
804 (let ((header (car arg-pair
)))
806 (cons arg-pair
(cl-remove-if
807 (lambda (pair) (equal header
(car pair
)))
812 (defun org-babel-check-src-block ()
813 "Check for misspelled header arguments in the current code block."
815 ;; TODO: report malformed code block
816 ;; TODO: report incompatible combinations of header arguments
817 ;; TODO: report uninitialized variables
818 (let ((too-close 2) ;; <- control closeness to report potential match
819 (names (mapcar #'symbol-name org-babel-header-arg-names
)))
820 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg
)) 1))
821 (and (org-babel-where-is-src-block-head)
822 (org-babel-parse-header-arguments
824 (match-string 4))))))
826 (when (and (not (string= header name
))
827 (<= (org-babel-edit-distance header name
) too-close
)
828 (not (member header names
)))
829 (error "Supplied header \"%S\" is suspiciously close to \"%S\""
831 (message "No suspicious header arguments found.")))
834 (defun org-babel-insert-header-arg (&optional header-arg value
)
835 "Insert a header argument selecting from lists of common args and values."
837 (let* ((info (org-babel-get-src-block-info 'light
))
840 (lang-headers (intern (concat "org-babel-header-args:" lang
)))
841 (headers (org-babel-combine-header-arg-lists
842 org-babel-common-header-args-w-values
843 (when (boundp lang-headers
) (eval lang-headers t
))))
844 (header-arg (or header-arg
848 (lambda (header-spec) (symbol-name (car header-spec
)))
850 (vals (cdr (assoc (intern header-arg
) headers
)))
854 (read-from-minibuffer "value: "))
858 (let ((arg (completing-read
861 (mapcar #'symbol-name group
)))))
862 (if (and arg
(not (string= "default" arg
)))
868 (goto-char (point-at-eol))
869 (unless (= (char-before (point)) ?\
) (insert " "))
870 (insert ":" header-arg
) (when value
(insert " " value
)))))
872 ;; Add support for completing-read insertion of header arguments after ":"
873 (defun org-babel-header-arg-expand ()
874 "Call `org-babel-enter-header-arg-w-completion' in appropriate contexts."
875 (when (and (equal (char-before) ?\
:) (org-babel-where-is-src-block-head))
876 (org-babel-enter-header-arg-w-completion (match-string 2))))
878 (defun org-babel-enter-header-arg-w-completion (&optional lang
)
879 "Insert header argument appropriate for LANG with completion."
880 (let* ((lang-headers-var (intern (concat "org-babel-header-args:" lang
)))
881 (lang-headers (when (boundp lang-headers-var
) (eval lang-headers-var t
)))
882 (headers-w-values (org-babel-combine-header-arg-lists
883 org-babel-common-header-args-w-values lang-headers
))
884 (headers (mapcar #'symbol-name
(mapcar #'car headers-w-values
)))
885 (header (org-completing-read "Header Arg: " headers
))
886 (args (cdr (assoc (intern header
) headers-w-values
)))
887 (arg (when (and args
(listp args
))
889 (format "%s: " header
)
890 (mapcar #'symbol-name
(apply #'append args
))))))
891 (insert (concat header
" " (or arg
"")))
894 (add-hook 'org-tab-first-hook
'org-babel-header-arg-expand
)
897 (defun org-babel-load-in-session (&optional _arg info
)
898 "Load the body of the current source-code block.
899 Evaluate the header arguments for the source block before
900 entering the session. After loading the body this pops open the
903 (let* ((info (or info
(org-babel-get-src-block-info)))
905 (params (nth 2 info
))
907 (user-error "No src code block at point")
909 (if (org-babel-noweb-p params
:eval
)
910 (org-babel-expand-noweb-references info
)
912 (session (cdr (assq :session params
)))
913 (dir (cdr (assq :dir params
)))
915 (or (and dir
(file-name-as-directory dir
)) default-directory
))
916 (cmd (intern (concat "org-babel-load-session:" lang
))))
917 (unless (fboundp cmd
)
918 (error "No org-babel-load-session function for %s!" lang
))
919 (pop-to-buffer (funcall cmd session body params
))
923 (defun org-babel-initiate-session (&optional arg info
)
924 "Initiate session for current code block.
925 If called with a prefix argument then resolve any variable
926 references in the header arguments and assign these variables in
927 the session. Copy the body of the code block to the kill ring."
929 (let* ((info (or info
(org-babel-get-src-block-info (not arg
))))
932 (params (nth 2 info
))
933 (session (cdr (assq :session params
)))
934 (dir (cdr (assq :dir params
)))
936 (or (and dir
(file-name-as-directory dir
)) default-directory
))
937 (init-cmd (intern (format "org-babel-%s-initiate-session" lang
)))
938 (prep-cmd (intern (concat "org-babel-prep-session:" lang
))))
939 (when (and (stringp session
) (string= session
"none"))
940 (error "This block is not using a session!"))
941 (unless (fboundp init-cmd
)
942 (error "No org-babel-initiate-session function for %s!" lang
))
943 (with-temp-buffer (insert (org-trim body
))
944 (copy-region-as-kill (point-min) (point-max)))
946 (unless (fboundp prep-cmd
)
947 (error "No org-babel-prep-session function for %s!" lang
))
948 (funcall prep-cmd session params
))
949 (funcall init-cmd session params
)))
952 (defun org-babel-switch-to-session (&optional arg info
)
953 "Switch to the session of the current code block.
954 Uses `org-babel-initiate-session' to start the session. If called
955 with a prefix argument then this is passed on to
956 `org-babel-initiate-session'."
958 (pop-to-buffer (org-babel-initiate-session arg info
))
961 (defalias 'org-babel-pop-to-session
'org-babel-switch-to-session
)
963 (defvar org-src-window-setup
)
966 (defun org-babel-switch-to-session-with-code (&optional arg _info
)
967 "Switch to code buffer and display session."
971 (let ((other-window-buffer (window-buffer (next-window))))
972 (set-window-buffer (next-window) (current-buffer))
973 (set-window-buffer (selected-window) other-window-buffer
))
975 (info (org-babel-get-src-block-info))
976 (org-src-window-setup 'reorganize-frame
))
978 (org-babel-switch-to-session arg info
))
980 (funcall swap-windows
)))
983 (defmacro org-babel-do-in-edit-buffer
(&rest body
)
984 "Evaluate BODY in edit buffer if there is a code block at point.
985 Return t if a code block was found at point, nil otherwise."
986 `(let ((org-src-window-setup 'switch-invisibly
))
987 (when (and (org-babel-where-is-src-block-head)
989 (unwind-protect (progn ,@body
)
992 (def-edebug-spec org-babel-do-in-edit-buffer
(body))
994 (defun org-babel-do-key-sequence-in-edit-buffer (key)
995 "Read key sequence and execute the command in edit buffer.
996 Enter a key sequence to be executed in the language major-mode
997 edit buffer. For example, TAB will alter the contents of the
998 Org code block according to the effect of TAB in the language
999 major mode buffer. For languages that support interactive
1000 sessions, this can be used to send code from the Org buffer
1001 to the session for evaluation using the native major mode
1002 evaluation mechanisms."
1003 (interactive "kEnter key-sequence to execute in edit buffer: ")
1004 (org-babel-do-in-edit-buffer
1006 (key-binding (or key
(read-key-sequence nil
))))))
1008 (defvar org-bracket-link-regexp
)
1010 (defun org-babel-active-location-p ()
1011 (memq (org-element-type (save-match-data (org-element-context)))
1012 '(babel-call inline-babel-call inline-src-block src-block
)))
1015 (defun org-babel-open-src-block-result (&optional re-run
)
1016 "If `point' is on a src block then open the results of the
1017 source code block, otherwise return nil. With optional prefix
1018 argument RE-RUN the source-code block is evaluated even if
1019 results already exist."
1021 (let ((info (org-babel-get-src-block-info 'light
)))
1024 ;; go to the results, if there aren't any then run the block
1025 (goto-char (or (and (not re-run
) (org-babel-where-is-src-block-result))
1026 (progn (org-babel-execute-src-block)
1027 (org-babel-where-is-src-block-result))))
1029 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
1031 (if (looking-at org-bracket-link-regexp
)
1034 (let ((r (org-babel-format-result
1035 (org-babel-read-result) (cdr (assq :sep
(nth 2 info
))))))
1036 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
1037 (delete-region (point-min) (point-max))
1042 (defmacro org-babel-map-src-blocks
(file &rest body
)
1043 "Evaluate BODY forms on each source-block in FILE.
1044 If FILE is nil evaluate BODY forms on source blocks in current
1045 buffer. During evaluation of BODY the following local variables
1046 are set relative to the currently matched code block.
1048 full-block ------- string holding the entirety of the code block
1049 beg-block -------- point at the beginning of the code block
1050 end-block -------- point at the end of the matched code block
1051 lang ------------- string holding the language of the code block
1052 beg-lang --------- point at the beginning of the lang
1053 end-lang --------- point at the end of the lang
1054 switches --------- string holding the switches
1055 beg-switches ----- point at the beginning of the switches
1056 end-switches ----- point at the end of the switches
1057 header-args ------ string holding the header-args
1058 beg-header-args -- point at the beginning of the header-args
1059 end-header-args -- point at the end of the header-args
1060 body ------------- string holding the body of the code block
1061 beg-body --------- point at the beginning of the body
1062 end-body --------- point at the end of the body"
1063 (declare (indent 1))
1064 (let ((tempvar (make-symbol "file")))
1065 `(let* ((case-fold-search t
)
1067 (visited-p (or (null ,tempvar
)
1068 (get-file-buffer (expand-file-name ,tempvar
))))
1069 (point (point)) to-be-removed
)
1070 (save-window-excursion
1071 (when ,tempvar
(find-file ,tempvar
))
1072 (setq to-be-removed
(current-buffer))
1073 (goto-char (point-min))
1074 (while (re-search-forward org-babel-src-block-regexp nil t
)
1075 (when (org-babel-active-location-p)
1076 (goto-char (match-beginning 0))
1077 (let ((full-block (match-string 0))
1078 (beg-block (match-beginning 0))
1079 (end-block (match-end 0))
1080 (lang (match-string 2))
1081 (beg-lang (match-beginning 2))
1082 (end-lang (match-end 2))
1083 (switches (match-string 3))
1084 (beg-switches (match-beginning 3))
1085 (end-switches (match-end 3))
1086 (header-args (match-string 4))
1087 (beg-header-args (match-beginning 4))
1088 (end-header-args (match-end 4))
1089 (body (match-string 5))
1090 (beg-body (match-beginning 5))
1091 (end-body (match-end 5)))
1092 ;; Silence byte-compiler in case `body' doesn't use all
1094 (ignore full-block beg-block end-block lang
1095 beg-lang end-lang switches beg-switches
1096 end-switches header-args beg-header-args
1097 end-header-args body beg-body end-body
)
1099 (goto-char end-block
)))))
1100 (unless visited-p
(kill-buffer to-be-removed
))
1101 (goto-char point
))))
1102 (def-edebug-spec org-babel-map-src-blocks
(form body
))
1105 (defmacro org-babel-map-inline-src-blocks
(file &rest body
)
1106 "Evaluate BODY forms on each inline source block in FILE.
1107 If FILE is nil evaluate BODY forms on source blocks in current
1109 (declare (indent 1) (debug (form body
)))
1110 (org-with-gensyms (datum end point tempvar to-be-removed visitedp
)
1111 `(let* ((case-fold-search t
)
1113 (,visitedp
(or (null ,tempvar
)
1114 (get-file-buffer (expand-file-name ,tempvar
))))
1117 (save-window-excursion
1118 (when ,tempvar
(find-file ,tempvar
))
1119 (setq ,to-be-removed
(current-buffer))
1120 (goto-char (point-min))
1121 (while (re-search-forward "src_\\S-" nil t
)
1122 (let ((,datum
(save-match-data (org-element-context))))
1123 (when (eq (org-element-type ,datum
) 'inline-src-block
)
1124 (goto-char (match-beginning 0))
1125 (let ((,end
(copy-marker (org-element-property :end
,datum
))))
1128 (set-marker ,end nil
))))))
1129 (unless ,visitedp
(kill-buffer ,to-be-removed
))
1130 (goto-char ,point
))))
1133 (defmacro org-babel-map-call-lines
(file &rest body
)
1134 "Evaluate BODY forms on each call line in FILE.
1135 If FILE is nil evaluate BODY forms on source blocks in current
1137 (declare (indent 1) (debug (form body
)))
1138 (org-with-gensyms (datum end point tempvar to-be-removed visitedp
)
1139 `(let* ((case-fold-search t
)
1141 (,visitedp
(or (null ,tempvar
)
1142 (get-file-buffer (expand-file-name ,tempvar
))))
1145 (save-window-excursion
1146 (when ,tempvar
(find-file ,tempvar
))
1147 (setq ,to-be-removed
(current-buffer))
1148 (goto-char (point-min))
1149 (while (re-search-forward "call_\\S-\\|^[ \t]*#\\+CALL:" nil t
)
1150 (let ((,datum
(save-match-data (org-element-context))))
1151 (when (memq (org-element-type ,datum
)
1152 '(babel-call inline-babel-call
))
1153 (goto-char (match-beginning 0))
1154 (let ((,end
(copy-marker (org-element-property :end
,datum
))))
1157 (set-marker ,end nil
))))))
1158 (unless ,visitedp
(kill-buffer ,to-be-removed
))
1159 (goto-char ,point
))))
1162 (defmacro org-babel-map-executables
(file &rest body
)
1163 "Evaluate BODY forms on each active Babel code in FILE.
1164 If FILE is nil evaluate BODY forms on source blocks in current
1166 (declare (indent 1) (debug (form body
)))
1167 (org-with-gensyms (datum end point tempvar to-be-removed visitedp
)
1168 `(let* ((case-fold-search t
)
1170 (,visitedp
(or (null ,tempvar
)
1171 (get-file-buffer (expand-file-name ,tempvar
))))
1174 (save-window-excursion
1175 (when ,tempvar
(find-file ,tempvar
))
1176 (setq ,to-be-removed
(current-buffer))
1177 (goto-char (point-min))
1178 (while (re-search-forward
1179 "\\(call\\|src\\)_\\|^[ \t]*#\\+\\(BEGIN_SRC\\|CALL:\\)" nil t
)
1180 (let ((,datum
(save-match-data (org-element-context))))
1181 (when (memq (org-element-type ,datum
)
1182 '(babel-call inline-babel-call inline-src-block
1184 (goto-char (match-beginning 0))
1185 (let ((,end
(copy-marker (org-element-property :end
,datum
))))
1188 (set-marker ,end nil
))))))
1189 (unless ,visitedp
(kill-buffer ,to-be-removed
))
1190 (goto-char ,point
))))
1193 (defun org-babel-execute-buffer (&optional arg
)
1194 "Execute source code blocks in a buffer.
1195 Call `org-babel-execute-src-block' on every source block in
1196 the current buffer."
1198 (org-babel-eval-wipe-error-buffer)
1199 (org-save-outline-visibility t
1200 (org-babel-map-executables nil
1201 (if (memq (org-element-type (org-element-context))
1202 '(babel-call inline-babel-call
))
1203 (org-babel-lob-execute-maybe)
1204 (org-babel-execute-src-block arg
)))))
1207 (defun org-babel-execute-subtree (&optional arg
)
1208 "Execute source code blocks in a subtree.
1209 Call `org-babel-execute-src-block' on every source block in
1210 the current subtree."
1214 (org-narrow-to-subtree)
1215 (org-babel-execute-buffer arg
)
1219 (defun org-babel-sha1-hash (&optional info
)
1220 "Generate an sha1 hash based on the value of info."
1222 (let ((print-level nil
)
1223 (info (or info
(org-babel-get-src-block-info))))
1225 (sort (copy-sequence (nth 2 info
))
1226 (lambda (a b
) (string< (car a
) (car b
)))))
1227 (let* ((rm (lambda (lst)
1228 (dolist (p '("replace" "silent" "none"
1229 "append" "prepend"))
1230 (setq lst
(remove p lst
)))
1233 (let ((v (if (and (listp (cdr arg
)) (null (cddr arg
)))
1234 (copy-sequence (cdr arg
))
1236 (when (and v
(not (and (sequencep v
)
1240 ((and (listp v
) ; lists are sorted
1241 (member (car arg
) '(:result-params
)))
1242 (sort (funcall rm v
) #'string
<))
1243 ((and (stringp v
) ; strings are sorted
1244 (member (car arg
) '(:results
:exports
)))
1245 (mapconcat #'identity
(sort (funcall rm
(split-string v
))
1250 (params (nth 2 info
))
1251 (body (if (org-babel-noweb-p params
:eval
)
1252 (org-babel-expand-noweb-references info
) (nth 1 info
)))
1253 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
1254 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
1257 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
1258 (org-babel-expand-body:generic
1259 body params
(and (fboundp assignments-cmd
)
1260 (funcall assignments-cmd params
))))))
1261 (let* ((it (format "%s-%s"
1264 (delq nil
(mapcar (lambda (arg)
1265 (let ((normalized (funcall norm arg
)))
1267 (format "%S" normalized
))))
1271 (when (called-interactively-p 'interactive
) (message hash
))
1274 (defun org-babel-current-result-hash (&optional info
)
1275 "Return the current in-buffer hash."
1276 (let ((result (org-babel-where-is-src-block-result nil info
)))
1278 (org-with-wide-buffer
1280 (looking-at org-babel-result-regexp
)
1281 (match-string-no-properties 1)))))
1283 (defun org-babel-set-current-result-hash (hash info
)
1284 "Set the current in-buffer hash to HASH."
1285 (org-with-wide-buffer
1286 (goto-char (org-babel-where-is-src-block-result nil info
))
1287 (looking-at org-babel-result-regexp
)
1288 (goto-char (match-beginning 1))
1289 (mapc #'delete-overlay
(overlays-at (point)))
1290 (forward-char org-babel-hash-show
)
1291 (mapc #'delete-overlay
(overlays-at (point)))
1292 (replace-match hash nil nil nil
1)
1294 (org-babel-hide-hash)))
1296 (defun org-babel-hide-hash ()
1297 "Hide the hash in the current results line.
1298 Only the initial `org-babel-hash-show' characters of the hash
1299 will remain visible."
1300 (add-to-invisibility-spec '(org-babel-hide-hash . t
))
1302 (when (and (re-search-forward org-babel-result-regexp nil t
)
1304 (let* ((start (match-beginning 1))
1305 (hide-start (+ org-babel-hash-show start
))
1307 (hash (match-string 1))
1309 (setq ov1
(make-overlay start hide-start
))
1310 (setq ov2
(make-overlay hide-start end
))
1311 (overlay-put ov2
'invisible
'org-babel-hide-hash
)
1312 (overlay-put ov1
'babel-hash hash
)))))
1314 (defun org-babel-hide-all-hashes ()
1315 "Hide the hash in the current buffer.
1316 Only the initial `org-babel-hash-show' characters of each hash
1317 will remain visible. This function should be called as part of
1318 the `org-mode-hook'."
1320 (while (and (not org-babel-hash-show-time
)
1321 (re-search-forward org-babel-result-regexp nil t
))
1322 (goto-char (match-beginning 0))
1323 (org-babel-hide-hash)
1324 (goto-char (match-end 0)))))
1325 (add-hook 'org-mode-hook
'org-babel-hide-all-hashes
)
1327 (defun org-babel-hash-at-point (&optional point
)
1328 "Return the value of the hash at POINT.
1330 The hash is also added as the last element of the kill ring.
1331 This can be called with `\\[org-ctrl-c-ctrl-c]'."
1333 (let ((hash (car (delq nil
(mapcar
1334 (lambda (ol) (overlay-get ol
'babel-hash
))
1335 (overlays-at (or point
(point))))))))
1336 (when hash
(kill-new hash
) (message hash
))))
1338 (defun org-babel-result-hide-spec ()
1339 "Hide portions of results lines.
1340 Add `org-babel-hide-result' as an invisibility spec for hiding
1341 portions of results lines."
1342 (add-to-invisibility-spec '(org-babel-hide-result . t
)))
1343 (add-hook 'org-mode-hook
'org-babel-result-hide-spec
)
1345 (defvar org-babel-hide-result-overlays nil
1346 "Overlays hiding results.")
1348 (defun org-babel-result-hide-all ()
1349 "Fold all results in the current buffer."
1351 (org-babel-show-result-all)
1353 (while (re-search-forward org-babel-result-regexp nil t
)
1354 (save-excursion (goto-char (match-beginning 0))
1355 (org-babel-hide-result-toggle-maybe)))))
1357 (defun org-babel-show-result-all ()
1358 "Unfold all results in the current buffer."
1359 (mapc 'delete-overlay org-babel-hide-result-overlays
)
1360 (setq org-babel-hide-result-overlays nil
))
1363 (defun org-babel-hide-result-toggle-maybe ()
1364 "Toggle visibility of result at point."
1366 (let ((case-fold-search t
))
1368 (beginning-of-line 1)
1369 (looking-at org-babel-result-regexp
))
1370 (progn (org-babel-hide-result-toggle)
1371 t
) ;; to signal that we took action
1372 nil
))) ;; to signal that we did not
1374 (defun org-babel-hide-result-toggle (&optional force
)
1375 "Toggle the visibility of the current result."
1379 (if (re-search-forward org-babel-result-regexp nil t
)
1380 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
1382 (while (looking-at org-babel-multi-line-header-regexp
)
1384 (goto-char (- (org-babel-result-end) 1)) (point)))
1386 (if (memq t
(mapcar (lambda (overlay)
1387 (eq (overlay-get overlay
'invisible
)
1388 'org-babel-hide-result
))
1389 (overlays-at start
)))
1390 (when (or (not force
) (eq force
'off
))
1392 (when (member ov org-babel-hide-result-overlays
)
1393 (setq org-babel-hide-result-overlays
1394 (delq ov org-babel-hide-result-overlays
)))
1395 (when (eq (overlay-get ov
'invisible
)
1396 'org-babel-hide-result
)
1397 (delete-overlay ov
)))
1398 (overlays-at start
)))
1399 (setq ov
(make-overlay start end
))
1400 (overlay-put ov
'invisible
'org-babel-hide-result
)
1401 ;; make the block accessible to isearch
1403 ov
'isearch-open-invisible
1405 (when (member ov org-babel-hide-result-overlays
)
1406 (setq org-babel-hide-result-overlays
1407 (delq ov org-babel-hide-result-overlays
)))
1408 (when (eq (overlay-get ov
'invisible
)
1409 'org-babel-hide-result
)
1410 (delete-overlay ov
))))
1411 (push ov org-babel-hide-result-overlays
)))
1412 (error "Not looking at a result line"))))
1414 ;; org-tab-after-check-for-cycling-hook
1415 (add-hook 'org-tab-first-hook
'org-babel-hide-result-toggle-maybe
)
1416 ;; Remove overlays when changing major mode
1417 (add-hook 'org-mode-hook
1418 (lambda () (add-hook 'change-major-mode-hook
1419 'org-babel-show-result-all
'append
'local
)))
1421 (defvar org-file-properties
)
1422 (defun org-babel-params-from-properties (&optional lang
)
1423 "Retrieve parameters specified as properties.
1424 Return a list of association lists of source block params
1425 specified in the properties of the current outline entry."
1428 ;; header arguments specified with the header-args property at
1430 (org-babel-parse-header-arguments
1431 (org-entry-get org-babel-current-src-block-location
1434 (and lang
; language-specific header arguments at point of call
1435 (org-babel-parse-header-arguments
1436 (org-entry-get org-babel-current-src-block-location
1437 (concat "header-args:" lang
)
1440 (defun org-babel-balanced-split (string alts
)
1441 "Split STRING on instances of ALTS.
1442 ALTS is a character, or cons of two character options where each
1443 option may be either the numeric code of a single character or
1444 a list of character alternatives. For example, to split on
1445 balanced instances of \"[ \t]:\", set ALTS to ((32 9) . 58)."
1448 (goto-char (point-min))
1449 (let ((splitp (lambda (past next
)
1450 ;; Non-nil when there should be a split after NEXT
1451 ;; character. PAST is the character before NEXT.
1453 (`(,(and first
(pred consp
)) .
,(and second
(pred consp
)))
1454 (and (memq past first
) (memq next second
)))
1455 (`(,first .
,(and second
(pred consp
)))
1456 (and (eq past first
) (memq next second
)))
1457 (`(,(and first
(pred consp
)) .
,second
)
1458 (and (memq past first
) (eq next second
)))
1459 (`(,first .
,second
)
1460 (and (eq past first
) (eq next second
)))
1461 ((pred (eq next
)) t
)
1467 ((funcall splitp
(char-before) (char-after))
1468 ;; There is a split after point. If ALTS is two-folds,
1469 ;; remove last parsed character as it belongs to ALTS.
1470 (when (consp alts
) (pop partial
))
1471 ;; Include elements parsed so far in RESULTS and flush
1474 (push (apply #'string
(nreverse partial
)) result
)
1477 ((memq (char-after) '(?\
( ?\
[))
1478 ;; Include everything between balanced brackets.
1479 (let* ((origin (point))
1480 (after (char-after))
1481 (openings (list after
)))
1483 (while (and openings
(re-search-forward "[]()]" nil t
))
1484 (pcase (char-before)
1485 ((and match
(or ?\
[ ?\
()) (push match openings
))
1486 (?\
] (when (eq ?\
[ (car openings
)) (pop openings
)))
1487 (_ (when (eq ?\
( (car openings
)) (pop openings
)))))
1490 (nconc (nreverse (string-to-list
1491 (buffer-substring origin
(point))))
1493 ;; Un-balanced bracket. Backtrack.
1494 (push after partial
)
1495 (goto-char (1+ origin
)))))
1496 ((and (eq ?
\" (char-after)) (not (eq ?
\\ (char-before))))
1497 ;; Include everything from current double quote to next
1498 ;; non-escaped double quote.
1499 (let ((origin (point)))
1500 (if (re-search-forward "[^\\]\"" nil t
)
1502 (nconc (nreverse (string-to-list
1503 (buffer-substring origin
(point))))
1505 ;; No closing double quote. Backtrack.
1508 (t (push (char-after) partial
)
1510 ;; Add pending parsing and return result.
1511 (when partial
(push (apply #'string
(nreverse partial
)) result
))
1512 (nreverse result
))))
1514 (defun org-babel-join-splits-near-ch (ch list
)
1515 "Join splits where \"=\" is on either end of the split."
1516 (let ((last= (lambda (str) (= ch
(aref str
(1- (length str
))))))
1517 (first= (lambda (str) (= ch
(aref str
0)))))
1519 (cl-reduce (lambda (acc el
)
1520 (let ((head (car acc
)))
1521 (if (and head
(or (funcall last
= head
) (funcall first
= el
)))
1522 (cons (concat head el
) (cdr acc
))
1524 list
:initial-value nil
))))
1526 (defun org-babel-parse-header-arguments (arg-string)
1527 "Parse a string of header arguments returning an alist."
1528 (when (> (length arg-string
) 0)
1529 (org-babel-parse-multiple-vars
1534 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1536 (cons (intern (match-string 1 arg
))
1537 (org-babel-read (org-babel-chomp (match-string 2 arg
))))
1538 (cons (intern (org-babel-chomp arg
)) nil
)))
1539 (let ((raw (org-babel-balanced-split arg-string
'((32 9) .
58))))
1540 (cons (car raw
) (mapcar (lambda (r) (concat ":" r
)) (cdr raw
)))))))))
1542 (defun org-babel-parse-multiple-vars (header-arguments)
1543 "Expand multiple variable assignments behind a single :var keyword.
1545 This allows expression of multiple variables with one :var as
1548 #+PROPERTY: var foo=1, bar=2"
1550 (mapc (lambda (pair)
1551 (if (eq (car pair
) :var
)
1552 (mapcar (lambda (v) (push (cons :var
(org-trim v
)) results
))
1553 (org-babel-join-splits-near-ch
1554 61 (org-babel-balanced-split (cdr pair
) 32)))
1555 (push pair results
)))
1557 (nreverse results
)))
1559 (defun org-babel-process-params (params)
1560 "Expand variables in PARAMS and add summary parameters."
1561 (let* ((processed-vars (mapcar (lambda (el)
1564 (org-babel-ref-parse el
)))
1565 (org-babel--get-vars params
)))
1566 (vars-and-names (if (and (assq :colname-names params
)
1567 (assq :rowname-names params
))
1568 (list processed-vars
)
1569 (org-babel-disassemble-tables
1571 (cdr (assq :hlines params
))
1572 (cdr (assq :colnames params
))
1573 (cdr (assq :rownames params
)))))
1574 (raw-result (or (cdr (assq :results params
)) ""))
1575 (result-params (delete-dups
1577 (split-string (if (stringp raw-result
)
1579 (eval raw-result t
)))
1580 (cdr (assq :result-params params
))))))
1582 (mapcar (lambda (var) (cons :var var
)) (car vars-and-names
))
1584 (cons :colname-names
(or (cdr (assq :colname-names params
))
1585 (cadr vars-and-names
)))
1586 (cons :rowname-names
(or (cdr (assq :rowname-names params
))
1587 (cl-caddr vars-and-names
)))
1588 (cons :result-params result-params
)
1589 (cons :result-type
(cond ((member "output" result-params
) 'output
)
1590 ((member "value" result-params
) 'value
)
1593 (lambda (x) (memq (car x
) '(:colname-names
:rowname-names
:result-params
1594 :result-type
:var
)))
1597 ;; row and column names
1598 (defun org-babel-del-hlines (table)
1599 "Remove all `hline's from TABLE."
1600 (remq 'hline table
))
1602 (defun org-babel-get-colnames (table)
1603 "Return the column names of TABLE.
1604 Return a cons cell, the `car' of which contains the TABLE less
1605 colnames, and the `cdr' of which contains a list of the column
1607 (if (eq 'hline
(nth 1 table
))
1608 (cons (cddr table
) (car table
))
1609 (cons (cdr table
) (car table
))))
1611 (defun org-babel-get-rownames (table)
1612 "Return the row names of TABLE.
1613 Return a cons cell, the `car' of which contains the TABLE less
1614 rownames, and the `cdr' of which contains a list of the rownames.
1615 Note: this function removes any hlines in TABLE."
1616 (let* ((table (org-babel-del-hlines table
))
1617 (rownames (funcall (lambda ()
1623 (setq tp
(cdr tp
))))
1625 (cons table rownames
)))
1627 (defun org-babel-put-colnames (table colnames
)
1628 "Add COLNAMES to TABLE if they exist."
1629 (if colnames
(apply 'list colnames
'hline table
) table
))
1631 (defun org-babel-put-rownames (table rownames
)
1632 "Add ROWNAMES to TABLE if they exist."
1634 (mapcar (lambda (row)
1636 (cons (or (pop rownames
) "") row
)
1640 (defun org-babel-pick-name (names selector
)
1641 "Select one out of an alist of row or column names.
1642 SELECTOR can be either a list of names in which case those names
1643 will be returned directly, or an index into the list NAMES in
1644 which case the indexed names will be return."
1645 (if (listp selector
)
1648 (if (and selector
(symbolp selector
) (not (equal t selector
)))
1649 (cdr (assoc selector names
))
1650 (if (integerp selector
)
1651 (nth (- selector
1) names
)
1652 (cdr (car (last names
))))))))
1654 (defun org-babel-disassemble-tables (vars hlines colnames rownames
)
1655 "Parse tables for further processing.
1656 Process the variables in VARS according to the HLINES,
1657 ROWNAMES and COLNAMES header arguments. Return a list consisting
1658 of the vars, cnames and rnames."
1659 (let (cnames rnames
)
1663 (when (listp (cdr var
))
1664 (when (and (not (equal colnames
"no"))
1665 (or colnames
(and (eq (nth 1 (cdr var
)) 'hline
)
1666 (not (member 'hline
(cddr (cdr var
)))))))
1667 (let ((both (org-babel-get-colnames (cdr var
))))
1668 (setq cnames
(cons (cons (car var
) (cdr both
))
1670 (setq var
(cons (car var
) (car both
)))))
1671 (when (and rownames
(not (equal rownames
"no")))
1672 (let ((both (org-babel-get-rownames (cdr var
))))
1673 (setq rnames
(cons (cons (car var
) (cdr both
))
1675 (setq var
(cons (car var
) (car both
)))))
1676 (when (and hlines
(not (equal hlines
"yes")))
1677 (setq var
(cons (car var
) (org-babel-del-hlines (cdr var
))))))
1680 (reverse cnames
) (reverse rnames
))))
1682 (defun org-babel-reassemble-table (table colnames rownames
)
1683 "Add column and row names to a table.
1684 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1685 to the table for reinsertion to org-mode."
1687 (let ((table (if (and rownames
(= (length table
) (length rownames
)))
1688 (org-babel-put-rownames table rownames
) table
)))
1689 (if (and colnames
(listp (car table
)) (= (length (car table
))
1691 (org-babel-put-colnames table colnames
) table
))
1694 (defun org-babel-where-is-src-block-head (&optional src-block
)
1695 "Find where the current source block begins.
1697 If optional argument SRC-BLOCK is `src-block' type element, find
1698 its current beginning instead.
1700 Return the point at the beginning of the current source block.
1701 Specifically at the beginning of the #+BEGIN_SRC line. Also set
1702 match-data relatively to `org-babel-src-block-regexp', which see.
1703 If the point is not on a source block then return nil."
1704 (let ((element (or src-block
(org-element-at-point))))
1705 (when (eq (org-element-type element
) 'src-block
)
1706 (let ((end (org-element-property :end element
)))
1707 (org-with-wide-buffer
1708 ;; Ensure point is not on a blank line after the block.
1710 (skip-chars-forward " \r\t\n" end
)
1711 (when (< (point) end
)
1712 (prog1 (goto-char (org-element-property :post-affiliated element
))
1713 (looking-at org-babel-src-block-regexp
))))))))
1716 (defun org-babel-goto-src-block-head ()
1717 "Go to the beginning of the current code block."
1719 (let ((head (org-babel-where-is-src-block-head)))
1720 (if head
(goto-char head
) (error "Not currently in a code block"))))
1723 (defun org-babel-goto-named-src-block (name)
1724 "Go to a named source-code block."
1726 (let ((completion-ignore-case t
)
1727 (case-fold-search t
)
1728 (all-block-names (org-babel-src-block-names)))
1729 (list (completing-read
1730 "source-block name: " all-block-names nil t
1731 (let* ((context (org-element-context))
1732 (type (org-element-type context
))
1734 (and (memq type
'(inline-src-block src-block
))
1735 (org-in-regexp (org-babel-noweb-wrap)))))
1739 (+ (car noweb-ref
) (length org-babel-noweb-wrap-start
))
1740 (- (cdr noweb-ref
) (length org-babel-noweb-wrap-end
))))
1741 ((memq type
'(babel-call inline-babel-call
)) ;#+CALL:
1742 (org-element-property :call context
))
1743 ((car (org-element-property :results context
))) ;#+RESULTS:
1744 ((let ((symbol (thing-at-point 'symbol
))) ;Symbol.
1746 (member-ignore-case symbol all-block-names
)
1749 (let ((point (org-babel-find-named-block name
)))
1751 ;; Taken from `org-open-at-point'.
1752 (progn (org-mark-ring-push) (goto-char point
) (org-show-context))
1753 (message "source-code block `%s' not found in this buffer" name
))))
1755 (defun org-babel-find-named-block (name)
1756 "Find a named source-code block.
1757 Return the location of the source block identified by source
1758 NAME, or nil if no such block exists. Set match data according
1759 to `org-babel-named-src-block-regexp'."
1761 (goto-char (point-min))
1762 (let ((regexp (org-babel-named-src-block-regexp-for-name name
)))
1763 (or (and (looking-at regexp
)
1764 (progn (goto-char (match-beginning 1))
1765 (line-beginning-position)))
1766 (ignore-errors (org-next-block 1 nil
))))))
1768 (defun org-babel-src-block-names (&optional file
)
1769 "Returns the names of source blocks in FILE or the current buffer."
1770 (when file
(find-file file
))
1772 (goto-char (point-min))
1773 (let* ((re (org-babel-named-src-block-regexp-for-name))
1774 (names (and (looking-at re
)
1775 (list (match-string-no-properties 9)))))
1776 (while (ignore-errors (org-next-block 1 nil re
))
1777 (push (match-string-no-properties 9) names
))
1781 (defun org-babel-goto-named-result (name)
1782 "Go to a named result."
1784 (let ((completion-ignore-case t
))
1785 (list (completing-read "Source-block name: "
1786 (org-babel-result-names) nil t
))))
1787 (let ((point (org-babel-find-named-result name
)))
1789 ;; taken from `org-open-at-point'
1790 (progn (goto-char point
) (org-show-context))
1791 (message "result `%s' not found in this buffer" name
))))
1793 (defun org-babel-find-named-result (name)
1794 "Find a named result.
1795 Return the location of the result named NAME in the current
1796 buffer or nil if no such result exists."
1798 (goto-char (point-min))
1799 (let ((case-fold-search t
)
1800 (re (format "^[ \t]*#\\+%s.*?:[ \t]*%s[ \t]*$"
1801 org-babel-results-keyword
1802 (regexp-quote name
))))
1804 (while (re-search-forward re nil t
)
1805 (let ((element (org-element-at-point)))
1806 (when (or (eq (org-element-type element
) 'keyword
)
1808 (org-element-property :post-affiliated element
)))
1809 (throw :found
(line-beginning-position)))))))))
1811 (defun org-babel-result-names (&optional file
)
1812 "Returns the names of results in FILE or the current buffer."
1814 (when file
(find-file file
)) (goto-char (point-min))
1815 (let ((case-fold-search t
) names
)
1816 (while (re-search-forward org-babel-result-w-name-regexp nil t
)
1817 (setq names
(cons (match-string-no-properties 9) names
)))
1821 (defun org-babel-next-src-block (&optional arg
)
1822 "Jump to the next source block.
1823 With optional prefix argument ARG, jump forward ARG many source blocks."
1825 (org-next-block arg nil org-babel-src-block-regexp
))
1828 (defun org-babel-previous-src-block (&optional arg
)
1829 "Jump to the previous source block.
1830 With optional prefix argument ARG, jump backward ARG many source blocks."
1832 (org-previous-block arg org-babel-src-block-regexp
))
1834 (defvar org-babel-load-languages
)
1837 (defun org-babel-mark-block ()
1838 "Mark current src block."
1840 (let ((head (org-babel-where-is-src-block-head)))
1844 (looking-at org-babel-src-block-regexp
))
1845 (push-mark (match-end 5) nil t
)
1846 (goto-char (match-beginning 5)))))
1848 (defun org-babel-demarcate-block (&optional arg
)
1849 "Wrap or split the code in the region or on the point.
1850 When called from inside of a code block the current block is
1851 split. When called from outside of a code block a new code block
1852 is created. In both cases if the region is demarcated and if the
1853 region is not active then the point is demarcated."
1855 (let* ((info (org-babel-get-src-block-info 'light
))
1856 (start (org-babel-where-is-src-block-head))
1857 (block (and start
(match-string 0)))
1858 (headers (and start
(match-string 4)))
1859 (stars (concat (make-string (or (org-current-level) 1) ?
*) " "))
1860 (lower-case-p (and block
1861 (let (case-fold-search)
1862 (string-match-p "#\\+begin_src" block
)))))
1868 (let ((lang (nth 0 info
))
1869 (indent (make-string (org-get-indentation) ?\s
)))
1870 (when (string-match "^[[:space:]]*$"
1871 (buffer-substring (point-at-bol)
1873 (delete-region (point-at-bol) (point-at-eol)))
1875 (if (looking-at "^") "" "\n")
1876 indent
(funcall (if lower-case-p
'downcase
'upcase
) "#+end_src\n")
1877 (if arg stars indent
) "\n"
1878 indent
(funcall (if lower-case-p
'downcase
'upcase
) "#+begin_src ")
1880 (if (> (length headers
) 1)
1881 (concat " " headers
) headers
)
1882 (if (looking-at "[\n\r]")
1884 (concat "\n" (make-string (current-column) ?
)))))))
1885 (move-end-of-line 2))
1886 (sort (if (org-region-active-p) (list (mark) (point)) (list (point))) #'>))
1887 (let ((start (point))
1888 (lang (completing-read
1890 (mapcar #'symbol-name
1892 (append (mapcar #'car org-babel-load-languages
)
1893 (mapcar (lambda (el) (intern (car el
)))
1894 org-src-lang-modes
))))))
1895 (body (delete-and-extract-region
1896 (if (org-region-active-p) (mark) (point)) (point))))
1897 (insert (concat (if (looking-at "^") "" "\n")
1898 (if arg
(concat stars
"\n") "")
1899 (funcall (if lower-case-p
'downcase
'upcase
) "#+begin_src ")
1902 (if (or (= (length body
) 0)
1903 (string-suffix-p "\r" body
)
1904 (string-suffix-p "\n" body
)) "" "\n")
1905 (funcall (if lower-case-p
'downcase
'upcase
) "#+end_src\n")))
1906 (goto-char start
) (move-end-of-line 1)))))
1908 (defun org-babel--insert-results-keyword (name hash
)
1909 "Insert RESULTS keyword with NAME value at point.
1910 If NAME is nil, results are anonymous. HASH is a string used as
1911 the results hash, or nil. Leave point before the keyword."
1912 (save-excursion (insert "\n")) ;open line to indent.
1915 (insert (concat "#+" org-babel-results-keyword
1916 (cond ((not hash
) nil
)
1917 (org-babel-hash-show-time
1919 (format-time-string "<%F %T>")
1921 (t (format "[%s]" hash
)))
1923 (when name
(concat " " name
))
1925 ;; Make sure results are going to be followed by at least one blank
1926 ;; line so they do not get merged with the next element, e.g.,
1931 ;; : fixed-width area, unrelated to the above.
1932 (unless (looking-at "^[ \t]*$") (save-excursion (insert "\n")))
1933 (beginning-of-line 0)
1934 (when hash
(org-babel-hide-hash)))
1936 (defun org-babel--clear-results-maybe (hash)
1937 "Clear results when hash doesn't match HASH.
1939 When results hash does not match HASH, remove RESULTS keyword at
1940 point, along with related contents. Do nothing if HASH is nil.
1942 Return a non-nil value if results were cleared. In this case,
1943 leave point where new results should be inserted."
1945 (looking-at org-babel-result-regexp
)
1946 (unless (string= (match-string 1) hash
)
1947 (let* ((e (org-element-at-point))
1948 (post (copy-marker (org-element-property :post-affiliated e
))))
1952 (goto-char (org-element-property :end e
))
1953 (skip-chars-backward " \t\n")
1954 (line-beginning-position 2)))
1955 ;; Delete RESULT keyword. However, if RESULTS keyword is
1956 ;; orphaned, ignore this part. The deletion above already
1958 (unless (= (point) post
)
1959 (delete-region (line-beginning-position)
1960 (line-beginning-position 2)))
1962 (set-marker post nil
)
1965 (defun org-babel-where-is-src-block-result (&optional insert _info hash
)
1966 "Find where the current source block results begin.
1968 Return the point at the beginning of the result of the current
1969 source block, specifically at the beginning of the results line.
1971 If no result exists for this block return nil, unless optional
1972 argument INSERT is non-nil. In this case, create a results line
1973 following the source block and return the position at its
1974 beginning. In the case of inline code, remove the results part
1977 If optional argument HASH is a string, remove contents related to
1978 RESULTS keyword if its hash is different. Then update the latter
1980 (let ((context (org-element-context)))
1982 (org-with-wide-buffer
1983 (pcase (org-element-type context
)
1984 ((or `inline-babel-call
`inline-src-block
)
1985 ;; Results for inline objects are located right after them.
1986 ;; There is no RESULTS line to insert either.
1987 (let ((limit (org-element-property
1988 :contents-end
(org-element-property :parent context
))))
1989 (goto-char (org-element-property :end context
))
1990 (skip-chars-forward " \t\n" limit
)
1994 (let ((result (org-element-context)))
1995 (and (eq (org-element-type result
) 'macro
)
1996 (string= (org-element-property :key result
)
1998 (if (not insert
) (point)
2002 (goto-char (org-element-property :end result
))
2003 (skip-chars-backward " \t")
2006 ((or `babel-call
`src-block
)
2007 (let* ((name (org-element-property :name context
))
2008 (named-results (and name
(org-babel-find-named-result name
))))
2009 (goto-char (or named-results
(org-element-property :end context
)))
2011 ;; Existing results named after the current source.
2013 (when (org-babel--clear-results-maybe hash
)
2014 (org-babel--insert-results-keyword name hash
))
2015 (throw :found
(point)))
2016 ;; Named results expect but none to be found.
2018 ;; No possible anonymous results at the very end of
2019 ;; buffer or outside CONTEXT parent.
2021 (or (org-element-property
2022 :contents-end
(org-element-property :parent context
))
2024 ;; Check if next element is an anonymous result below
2025 ;; the current block.
2026 ((let* ((next (org-element-at-point))
2027 (end (save-excursion
2029 (org-element-property :post-affiliated next
))
2030 (line-end-position)))
2031 (empty-result-re (concat org-babel-result-regexp
"$"))
2032 (case-fold-search t
))
2033 (re-search-forward empty-result-re end t
))
2035 (when (org-babel--clear-results-maybe hash
)
2036 (org-babel--insert-results-keyword nil hash
))
2037 (throw :found
(point))))))
2038 ;; Ignore other elements.
2039 (_ (throw :found nil
))))
2040 ;; No result found. Insert a RESULTS keyword below element, if
2041 ;; appropriate. In this case, ensure there is an empty line
2042 ;; after the previous element.
2045 (goto-char (min (org-element-property :end context
) (point-max)))
2046 (skip-chars-backward " \t\n")
2048 (unless (bolp) (insert "\n"))
2050 (org-babel--insert-results-keyword
2051 (org-element-property :name context
) hash
)
2054 (defun org-babel-read-element (element)
2055 "Read ELEMENT into emacs-lisp.
2056 Return nil if ELEMENT cannot be read."
2057 (org-with-wide-buffer
2058 (goto-char (org-element-property :post-affiliated element
))
2059 (pcase (org-element-type element
)
2061 (let ((v (org-trim (org-element-property :value element
))))
2062 (or (org-babel--string-to-number v
) v
)))
2063 (`table
(org-babel-read-table))
2064 (`plain-list
(org-babel-read-list))
2066 (let ((v (org-element-property :value element
)))
2067 (if (or org-src-preserve-indentation
2068 (org-element-property :preserve-indent element
))
2070 (org-remove-indentation v
))))
2072 (org-remove-indentation (org-element-property :value element
)))
2074 ;; Treat paragraphs containing a single link specially.
2075 (skip-chars-forward " \t")
2076 (if (and (looking-at org-bracket-link-regexp
)
2078 (goto-char (match-end 0))
2079 (skip-chars-forward " \r\t\n")
2080 (<= (org-element-property :end element
)
2082 (org-babel-read-link)
2083 (buffer-substring-no-properties
2084 (org-element-property :contents-begin element
)
2085 (org-element-property :contents-end element
))))
2086 ((or `center-block
`quote-block
`verse-block
`special-block
)
2087 (org-remove-indentation
2088 (buffer-substring-no-properties
2089 (org-element-property :contents-begin element
)
2090 (org-element-property :contents-end element
))))
2093 (defun org-babel-read-result ()
2094 "Read the result at point into emacs-lisp."
2095 (and (not (save-excursion
2097 (looking-at-p "[ \t]*$")))
2098 (org-babel-read-element (org-element-at-point))))
2100 (defun org-babel-read-table ()
2101 "Read the table at point into emacs-lisp."
2102 (mapcar (lambda (row)
2103 (if (and (symbolp row
) (equal row
'hline
)) row
2104 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
)) row
)))
2105 (org-table-to-lisp)))
2107 (defun org-babel-read-list ()
2108 "Read the list at point into emacs-lisp."
2109 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
))
2110 (cdr (org-list-to-lisp))))
2112 (defvar org-link-types-re
)
2113 (defun org-babel-read-link ()
2114 "Read the link at point into emacs-lisp.
2115 If the path of the link is a file path it is expanded using
2116 `expand-file-name'."
2117 (let* ((case-fold-search t
)
2118 (raw (and (looking-at org-bracket-link-regexp
)
2119 (org-no-properties (match-string 1))))
2120 (type (and (string-match org-link-types-re raw
)
2121 (match-string 1 raw
))))
2123 ((not type
) (expand-file-name raw
))
2124 ((string= type
"file")
2125 (and (string-match "file\\(.*\\):\\(.+\\)" raw
)
2126 (expand-file-name (match-string 2 raw
))))
2129 (defun org-babel-format-result (result &optional sep
)
2130 "Format RESULT for writing to file."
2131 (let ((echo-res (lambda (r) (if (stringp r
) r
(format "%S" r
)))))
2135 result
(list :sep
(or sep
"\t") :fmt echo-res
))
2137 (funcall echo-res result
))))
2139 (defun org-babel-insert-result (result &optional result-params info hash lang
)
2140 "Insert RESULT into the current buffer.
2142 By default RESULT is inserted after the end of the current source
2143 block. The RESULT of an inline source block usually will be
2144 wrapped inside a `results' macro and placed on the same line as
2145 the inline source block. The macro is stripped upon export.
2146 Multiline and non-scalar RESULTS from inline source blocks are
2147 not allowed. With optional argument RESULT-PARAMS controls
2148 insertion of results in the Org mode file. RESULT-PARAMS can
2149 take the following values:
2151 replace - (default option) insert results after the source block
2152 or inline source block replacing any previously
2155 silent -- no results are inserted into the Org buffer but
2156 the results are echoed to the minibuffer and are
2157 ingested by Emacs (a potentially time consuming
2160 file ---- the results are interpreted as a file path, and are
2161 inserted into the buffer using the Org file syntax.
2163 list ---- the results are interpreted as an Org list.
2165 raw ----- results are added directly to the Org file. This is
2166 a good option if you code block will output Org
2169 drawer -- results are added directly to the Org file as with
2170 \"raw\", but are wrapped in a RESULTS drawer or results
2171 macro, allowing them to later be replaced or removed
2174 org ----- results are added inside of a \"src_org{}\" or \"#+BEGIN_SRC
2175 org\" block depending on whether the current source block is
2176 inline or not. They are not comma-escaped when inserted,
2177 but Org syntax here will be discarded when exporting the
2180 html ---- results are added inside of a #+BEGIN_EXPORT HTML block
2181 or html export snippet depending on whether the current
2182 source block is inline or not. This is a good option
2183 if your code block will output html formatted text.
2185 latex --- results are added inside of a #+BEGIN_EXPORT LATEX
2186 block or latex export snippet depending on whether the
2187 current source block is inline or not. This is a good
2188 option if your code block will output latex formatted
2191 code ---- the results are extracted in the syntax of the source
2192 code of the language being evaluated and are added
2193 inside of a source block with the source-code language
2194 set appropriately. Also, source block inlining is
2195 preserved in this case. Note this relies on the
2196 optional LANG argument.
2198 list ---- the results are rendered as a list. This option not
2199 allowed for inline src blocks.
2201 table --- the results are rendered as a table. This option not
2202 allowed for inline src blocks.
2204 INFO may provide the values of these header arguments (in the
2205 `header-arguments-alist' see the docstring for
2206 `org-babel-get-src-block-info'):
2208 :file --- the name of the file to which output should be written.
2210 :wrap --- the effect is similar to `latex' in RESULT-PARAMS but
2211 using the argument supplied to specify the export block
2213 (cond ((stringp result
)
2214 (setq result
(org-no-properties result
))
2215 (when (member "file" result-params
)
2216 (setq result
(org-babel-result-to-file
2217 result
(when (assq :file-desc
(nth 2 info
))
2218 (or (cdr (assq :file-desc
(nth 2 info
)))
2221 (t (setq result
(format "%S" result
))))
2222 (if (and result-params
(member "silent" result-params
))
2223 (progn (message (replace-regexp-in-string "%" "%%" (format "%S" result
)))
2225 (let ((inline (let ((context (org-element-context)))
2226 (and (memq (org-element-type context
)
2227 '(inline-babel-call inline-src-block
))
2231 (or (and (member "table" result-params
) "`:results table'")
2232 (and (listp result
) "list result")
2233 (and (string-match-p "\n." result
) "multiline result")
2234 (and (member "list" result-params
) "`:results list'"))))
2236 (user-error "Inline error: %s cannot be used" warning
))))
2238 (let* ((visible-beg (point-min-marker))
2239 (visible-end (copy-marker (point-max) t
))
2240 (inline (let ((context (org-element-context)))
2241 (and (memq (org-element-type context
)
2242 '(inline-babel-call inline-src-block
))
2244 (existing-result (org-babel-where-is-src-block-result t nil hash
))
2245 (results-switches (cdr (assq :results_switches
(nth 2 info
))))
2246 ;; When results exist outside of the current visible
2247 ;; region of the buffer, be sure to widen buffer to
2249 (outside-scope (and existing-result
2251 (or (> visible-beg existing-result
)
2252 (<= visible-end existing-result
))))
2254 ;; Ensure non-inline results end in a newline.
2255 (when (and (org-string-nw-p result
)
2257 (not (string-equal (substring result -
1) "\n")))
2258 (setq result
(concat result
"\n")))
2261 (when outside-scope
(widen))
2262 (if existing-result
(goto-char existing-result
)
2263 (goto-char (org-element-property :end inline
))
2264 (skip-chars-backward " \t"))
2266 (setq indent
(org-get-indentation))
2271 ;; Make sure new results are separated from the
2272 ;; source code by one space.
2273 (unless existing-result
2275 (setq beg
(point))))
2276 ((member "replace" result-params
)
2277 (delete-region (point) (org-babel-result-end)))
2278 ((member "append" result-params
)
2279 (goto-char (org-babel-result-end)) (setq beg
(point-marker)))
2280 ((member "prepend" result-params
))) ; already there
2281 (setq results-switches
2282 (if results-switches
(concat " " results-switches
) ""))
2284 (lambda (start finish
&optional no-escape no-newlines
2285 inline-start inline-finish
)
2287 (setq start inline-start
)
2288 (setq finish inline-finish
)
2289 (setq no-newlines t
))
2290 (let ((before-finish (marker-position end
)))
2292 (insert (concat finish
(unless no-newlines
"\n")))
2294 (insert (concat start
(unless no-newlines
"\n")))
2296 (org-escape-code-in-region
2297 (min (point) before-finish
) before-finish
))
2301 ;; Non-nil when result R can be turned into
2304 (null (cdr (last r
)))
2306 (lambda (e) (or (atom e
) (null (cdr (last e
)))))
2308 ;; insert results based on type
2310 ;; Do nothing for an empty result.
2312 ;; Insert a list if preferred.
2313 ((member "list" result-params
)
2316 (org-list-to-generic
2320 (list (if (stringp e
) e
(format "%S" e
))))
2321 (if (listp result
) result
2322 (split-string result
"\n" t
))))
2323 '(:splicep nil
:istart
"- " :iend
"\n")))
2325 ;; Try hard to print RESULT as a table. Give up if
2326 ;; it contains an improper list.
2327 ((funcall tabulablep result
)
2329 (insert (concat (orgtbl-to-orgtbl
2332 (or (eq e
'hline
) (listp e
)))
2339 (when (org-at-table-p) (org-table-align))
2340 (goto-char (org-table-end)))
2341 ;; Print verbatim a list that cannot be turned into
2343 ((listp result
) (insert (format "%s\n" result
)))
2344 ((member "file" result-params
)
2346 (setq result
(org-macro-escape-arguments result
)))
2348 ((and inline
(not (member "raw" result-params
)))
2349 (insert (org-macro-escape-arguments
2350 (org-babel-chomp result
"\n"))))
2351 (t (goto-char beg
) (insert result
)))
2352 (setq end
(copy-marker (point) t
))
2353 ;; possibly wrap result
2355 ((assq :wrap
(nth 2 info
))
2356 (let ((name (or (cdr (assq :wrap
(nth 2 info
))) "RESULTS")))
2357 (funcall wrap
(concat "#+BEGIN_" name
)
2358 (concat "#+END_" (car (org-split-string name
)))
2359 nil nil
(concat "{{{results(@@" name
":") "@@)}}}")))
2360 ((member "html" result-params
)
2361 (funcall wrap
"#+BEGIN_EXPORT html" "#+END_EXPORT" nil nil
2362 "{{{results(@@html:" "@@)}}}"))
2363 ((member "latex" result-params
)
2364 (funcall wrap
"#+BEGIN_EXPORT latex" "#+END_EXPORT" nil nil
2365 "{{{results(@@latex:" "@@)}}}"))
2366 ((member "org" result-params
)
2367 (goto-char beg
) (when (org-at-table-p) (org-cycle))
2368 (funcall wrap
"#+BEGIN_SRC org" "#+END_SRC" nil nil
2369 "{{{results(src_org{" "})}}}"))
2370 ((member "code" result-params
)
2371 (let ((lang (or lang
"none")))
2372 (funcall wrap
(format "#+BEGIN_SRC %s%s" lang results-switches
)
2374 (format "{{{results(src_%s[%s]{" lang results-switches
)
2376 ((member "raw" result-params
)
2377 (goto-char beg
) (when (org-at-table-p) (org-cycle)))
2378 ((or (member "drawer" result-params
)
2379 ;; Stay backward compatible with <7.9.2
2380 (member "wrap" result-params
))
2381 (goto-char beg
) (when (org-at-table-p) (org-cycle))
2382 (funcall wrap
":RESULTS:" ":END:" 'no-escape nil
2383 "{{{results(" ")}}}"))
2384 ((and inline
(member "file" result-params
))
2385 (funcall wrap nil nil nil nil
"{{{results(" ")}}}"))
2386 ((and (not (funcall tabulablep result
))
2387 (not (member "file" result-params
)))
2388 (let ((org-babel-inline-result-wrap
2389 ;; Hard code {{{results(...)}}} on top of
2391 (format "{{{results(%s)}}}"
2392 org-babel-inline-result-wrap
)))
2393 (org-babel-examplify-region
2394 beg end results-switches inline
)))))
2395 ;; Possibly indent results in par with #+results line.
2396 (when (and (not inline
) (numberp indent
) (> indent
0)
2397 ;; In this case `table-align' does the work
2399 (not (and (listp result
)
2400 (member "append" result-params
))))
2401 (indent-rigidly beg end indent
))
2403 (if (member "value" result-params
)
2404 (message "Code block returned no value.")
2405 (message "Code block produced no output."))
2406 (message "Code block evaluation complete.")))
2407 (set-marker end nil
)
2408 (when outside-scope
(narrow-to-region visible-beg visible-end
))
2409 (set-marker visible-beg nil
)
2410 (set-marker visible-end nil
)))))))
2412 (defun org-babel-remove-result (&optional info keep-keyword
)
2413 "Remove the result of the current source block."
2415 (let ((location (org-babel-where-is-src-block-result nil info
)))
2418 (goto-char location
)
2419 (when (looking-at (concat org-babel-result-regexp
".*$"))
2421 (if keep-keyword
(1+ (match-end 0)) (1- (match-beginning 0)))
2422 (progn (forward-line 1) (org-babel-result-end))))))))
2424 (defun org-babel-remove-inline-result (&optional datum
)
2425 "Remove the result of the current inline-src-block or babel call.
2426 The result must be wrapped in a `results' macro to be removed.
2427 Leading white space is trimmed."
2429 (let* ((el (or datum
(org-element-context))))
2430 (when (memq (org-element-type el
) '(inline-src-block inline-babel-call
))
2431 (org-with-wide-buffer
2432 (goto-char (org-element-property :end el
))
2433 (skip-chars-backward " \t")
2434 (let ((result (save-excursion
2437 (org-element-property
2438 :contents-end
(org-element-property :parent el
)))
2439 (org-element-context))))
2440 (when (and (eq (org-element-type result
) 'macro
)
2441 (string= (org-element-property :key result
) "results"))
2442 (delete-region ; And leading whitespace.
2444 (progn (goto-char (org-element-property :end result
))
2445 (skip-chars-backward " \t\n")
2448 (defun org-babel-remove-result-one-or-many (x)
2449 "Remove the result of the current source block.
2450 If called with a prefix argument, remove all result blocks
2454 (org-babel-map-src-blocks nil
(org-babel-remove-result))
2455 (org-babel-remove-result)))
2457 (defun org-babel-result-end ()
2458 "Return the point at the end of the current set of results."
2461 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
2462 ((org-at-item-p) (let* ((struct (org-list-struct))
2463 (prvs (org-list-prevs-alist struct
)))
2464 (org-list-get-list-end (point-at-bol) struct prvs
)))
2465 ((let ((case-fold-search t
)) (looking-at "^\\([ \t]*\\):results:"))
2466 (progn (re-search-forward (concat "^" (match-string 1) ":END:"))
2467 (forward-char 1) (point)))
2469 (let ((case-fold-search t
))
2470 (if (looking-at (concat "[ \t]*#\\+begin_\\([^ \t\n\r]+\\)"))
2471 (progn (re-search-forward (concat "[ \t]*#\\+end_" (match-string 1))
2474 (while (looking-at "[ \t]*\\(: \\|:$\\|\\[\\[\\)")
2478 (defun org-babel-result-to-file (result &optional description
)
2479 "Convert RESULT into an `org-mode' link with optional DESCRIPTION.
2480 If the `default-directory' is different from the containing
2481 file's directory then expand relative links."
2482 (when (stringp result
)
2483 (format "[[file:%s]%s]"
2484 (if (and default-directory
2486 (not (string= (expand-file-name default-directory
)
2488 (file-name-directory buffer-file-name
)))))
2489 (expand-file-name result default-directory
)
2491 (if description
(concat "[" description
"]") ""))))
2493 (defun org-babel-examplify-region (beg end
&optional results-switches inline
)
2494 "Comment out region using the inline `==' or `: ' org example quote."
2498 (if org-babel-uppercase-example-markers
(upcase str
) str
))))
2502 (insert (format org-babel-inline-result-wrap
2503 (delete-and-extract-region beg end
))))
2504 (let ((size (count-lines beg end
)))
2506 (cond ((= size
0)) ; do nothing for an empty result
2507 ((< size org-babel-min-lines-for-block-output
)
2510 (beginning-of-line 1) (insert ": ") (forward-line 1)))
2513 (insert (if results-switches
2515 (funcall maybe-cap
"#+begin_example")
2517 (funcall maybe-cap
"#+begin_example\n")))
2519 (if (markerp end
) (goto-char end
) (forward-char (- end beg
)))
2520 (org-escape-code-in-region p
(point)))
2521 (insert (funcall maybe-cap
"#+end_example\n")))))))))
2523 (defun org-babel-update-block-body (new-body)
2524 "Update the body of the current code block to NEW-BODY."
2525 (let ((element (org-element-at-point)))
2526 (unless (eq (org-element-type element
) 'src-block
)
2527 (error "Not in a source block"))
2528 (goto-char (org-babel-where-is-src-block-head element
))
2529 (let* ((ind (org-get-indentation))
2530 (body-start (line-beginning-position 2))
2531 (body (org-element-normalize-string
2532 (if (or org-src-preserve-indentation
2533 (org-element-property :preserve-indent element
))
2536 (insert (org-remove-indentation new-body
))
2540 (+ ind org-edit-src-content-indentation
))
2541 (buffer-string))))))
2542 (delete-region body-start
2543 (org-with-wide-buffer
2544 (goto-char (org-element-property :end element
))
2545 (skip-chars-backward " \t\n")
2546 (line-beginning-position)))
2547 (goto-char body-start
)
2550 (defun org-babel-merge-params (&rest plists
)
2551 "Combine all parameter association lists in PLISTS.
2552 Later elements of PLISTS override the values of previous elements.
2553 This takes into account some special considerations for certain
2554 parameters when merging lists."
2555 (let* ((results-exclusive-groups
2556 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2557 (cdr (assq 'results org-babel-common-header-args-w-values
))))
2558 (exports-exclusive-groups
2559 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2560 (cdr (assq 'exports org-babel-common-header-args-w-values
))))
2562 (lambda (exclusive-groups &rest result-params
)
2563 ;; Maintain exclusivity of mutually exclusive parameters,
2564 ;; as defined in EXCLUSIVE-GROUPS while merging lists in
2567 (dolist (new-params result-params
(delete-dups output
))
2568 (dolist (new-param new-params
)
2569 (dolist (exclusive-group exclusive-groups
)
2570 (when (member new-param exclusive-group
)
2571 (setq output
(cl-remove-if
2572 (lambda (o) (member o exclusive-group
))
2574 (push new-param output
))))))
2575 (variable-index 0) ;Handle positional arguments.
2577 params
;Final parameters list.
2578 ;; Some keywords accept multiple values. We need to treat
2580 vars results exports
)
2581 (dolist (plist plists
)
2582 (dolist (pair plist
)
2586 ((listp value
) (car value
))
2587 ((string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*=" value
)
2588 (intern (match-string 1 value
)))
2593 (append (if (not (assoc name vars
)) vars
2594 (push name clearnames
)
2595 (cl-remove-if (lambda (p) (equal name
(car p
)))
2597 (list (cons name pair
)))))
2598 ((and vars
(nth variable-index vars
))
2599 ;; If no name is given and we already have named
2600 ;; variables then assign to named variables in order.
2601 (let ((name (car (nth variable-index vars
))))
2602 ;; Clear out colnames and rownames for replace vars.
2603 (push name clearnames
)
2604 (setf (cddr (nth variable-index vars
))
2605 (concat (symbol-name name
) "=" value
))
2606 (cl-incf variable-index
)))
2607 (t (error "Variable \"%s\" must be assigned a default value"
2609 (`(:results .
,value
)
2610 (setq results
(funcall merge
2611 results-exclusive-groups
2614 (if (stringp value
) value
(eval value t
))))))
2615 (`(,(or :file
:file-ext
) .
,value
)
2616 ;; `:file' and `:file-ext' are regular keywords but they
2617 ;; imply a "file" `:results' and a "results" `:exports'.
2620 (funcall merge results-exclusive-groups results
'("file")))
2621 (unless (or (member "both" exports
)
2622 (member "none" exports
)
2623 (member "code" exports
))
2626 exports-exclusive-groups exports
'("results"))))
2627 (push pair params
)))
2628 (`(:exports .
,value
)
2629 (setq exports
(funcall merge
2630 exports-exclusive-groups
2632 (split-string (or value
"")))))
2633 ;; Regular keywords: any value overwrites the previous one.
2634 (_ (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))))
2635 ;; Handle `:var' and clear out colnames and rownames for replaced
2637 (setq params
(nconc (mapcar (lambda (v) (cons :var
(cddr v
))) vars
)
2639 (dolist (name clearnames
)
2640 (dolist (param '(:colname-names
:rowname-names
))
2641 (when (assq param params
)
2642 (setf (cdr (assq param params
))
2643 (cl-remove-if (lambda (pair) (equal name
(car pair
)))
2644 (cdr (assq param params
))))
2646 (cl-remove-if (lambda (pair) (and (equal (car pair
) param
)
2649 ;; Handle other special keywords, which accept multiple values.
2650 (setq params
(nconc (list (cons :results
(mapconcat #'identity results
" "))
2651 (cons :exports
(mapconcat #'identity exports
" ")))
2653 ;; Return merged params.
2656 (defvar org-babel-use-quick-and-dirty-noweb-expansion nil
2657 "Set to true to use regular expressions to expand noweb references.
2658 This results in much faster noweb reference expansion but does
2659 not properly allow code blocks to inherit the \":noweb-ref\"
2660 header argument from buffer or subtree wide properties.")
2662 (defun org-babel-noweb-p (params context
)
2663 "Check if PARAMS require expansion in CONTEXT.
2664 CONTEXT may be one of :tangle, :export or :eval."
2665 (let ((allowed-values (cl-case context
2666 (:tangle
'("yes" "tangle" "no-export" "strip-export"))
2667 (:eval
'("yes" "no-export" "strip-export" "eval"))
2668 (:export
'("yes")))))
2669 (cl-some (lambda (v) (member v allowed-values
))
2670 (split-string (or (cdr (assq :noweb params
)) "")))))
2672 (defun org-babel-expand-noweb-references (&optional info parent-buffer
)
2673 "Expand Noweb references in the body of the current source code block.
2675 For example the following reference would be replaced with the
2676 body of the source-code block named `example-block'.
2680 Note that any text preceding the <<foo>> construct on a line will
2681 be interposed between the lines of the replacement text. So for
2682 example if <<foo>> is placed behind a comment, then the entire
2683 replacement text will also be commented.
2685 This function must be called from inside of the buffer containing
2686 the source-code block which holds BODY.
2688 In addition the following syntax can be used to insert the
2689 results of evaluating the source-code block named `example-block'.
2693 Any optional arguments can be passed to example-block by placing
2694 the arguments inside the parenthesis following the convention
2695 defined by `org-babel-lob'. For example
2697 <<example-block(a=9)>>
2699 would set the value of argument \"a\" equal to \"9\". Note that
2700 these arguments are not evaluated in the current source-code
2701 block but are passed literally to the \"example-block\"."
2702 (let* ((parent-buffer (or parent-buffer
(current-buffer)))
2703 (info (or info
(org-babel-get-src-block-info 'light
)))
2706 (ob-nww-start org-babel-noweb-wrap-start
)
2707 (ob-nww-end org-babel-noweb-wrap-end
)
2708 (comment (string= "noweb" (cdr (assq :comments
(nth 2 info
)))))
2709 (rx-prefix (concat "\\(" org-babel-src-name-regexp
"\\|"
2710 ":noweb-ref[ \t]+" "\\)"))
2712 (nb-add (lambda (text) (setq new-body
(concat new-body text
))))
2713 (c-wrap (lambda (text)
2715 (funcall (intern (concat lang
"-mode")))
2716 (comment-region (point) (progn (insert text
) (point)))
2717 (org-trim (buffer-string)))))
2718 index source-name evaluate prefix
)
2720 (setq-local org-babel-noweb-wrap-start ob-nww-start
)
2721 (setq-local org-babel-noweb-wrap-end ob-nww-end
)
2722 (insert body
) (goto-char (point-min))
2723 (setq index
(point))
2724 (while (and (re-search-forward (org-babel-noweb-wrap) nil t
))
2725 (save-match-data (setf source-name
(match-string 1)))
2726 (save-match-data (setq evaluate
(string-match "(.*)" source-name
)))
2729 (buffer-substring (match-beginning 0)
2731 (beginning-of-line 1) (point)))))
2732 ;; add interval to new-body (removing noweb reference)
2733 (goto-char (match-beginning 0))
2734 (funcall nb-add
(buffer-substring index
(point)))
2735 (goto-char (match-end 0))
2736 (setq index
(point))
2739 (with-current-buffer parent-buffer
2742 (mapconcat ;; Interpose PREFIX between every line.
2746 (let ((raw (org-babel-ref-resolve source-name
)))
2747 (if (stringp raw
) raw
(format "%S" raw
)))
2749 ;; Retrieve from the library of babel.
2750 (nth 2 (assoc (intern source-name
)
2751 org-babel-library-of-babel
))
2752 ;; Return the contents of headlines literally.
2754 (when (org-babel-ref-goto-headline-id source-name
)
2755 (org-babel-ref-headline-body)))
2756 ;; Find the expansion of reference in this buffer.
2757 (let ((rx (concat rx-prefix source-name
"[ \t\n]"))
2760 (goto-char (point-min))
2761 (if org-babel-use-quick-and-dirty-noweb-expansion
2762 (while (re-search-forward rx nil t
)
2763 (let* ((i (org-babel-get-src-block-info 'light
))
2764 (body (org-babel-expand-noweb-references i
))
2765 (sep (or (cdr (assq :noweb-sep
(nth 2 i
)))
2768 (let ((cs (org-babel-tangle-comment-links i
)))
2769 (concat (funcall c-wrap
(car cs
)) "\n"
2771 (funcall c-wrap
(cadr cs
))))
2773 (setq expansion
(cons sep
(cons full expansion
)))))
2774 (org-babel-map-src-blocks nil
2775 (let ((i (org-babel-get-src-block-info 'light
)))
2776 (when (equal (or (cdr (assq :noweb-ref
(nth 2 i
)))
2779 (let* ((body (org-babel-expand-noweb-references i
))
2780 (sep (or (cdr (assq :noweb-sep
(nth 2 i
)))
2783 (let ((cs (org-babel-tangle-comment-links i
)))
2784 (concat (funcall c-wrap
(car cs
)) "\n"
2786 (funcall c-wrap
(cadr cs
))))
2789 (cons sep
(cons full expansion
)))))))))
2791 (mapconcat #'identity
(nreverse (cdr expansion
)) "")))
2792 ;; Possibly raise an error if named block doesn't exist.
2793 (if (or org-babel-noweb-error-all-langs
2794 (member lang org-babel-noweb-error-langs
))
2796 (org-babel-noweb-wrap source-name
)
2797 "could not be resolved (see "
2798 "`org-babel-noweb-error-langs')"))
2800 "[\n\r]") (concat "\n" prefix
))))))
2801 (funcall nb-add
(buffer-substring index
(point-max))))
2804 (defun org-babel--script-escape-inner (str)
2805 (let (in-single in-double backslash out
)
2812 (setq backslash nil
)
2814 ((and in-single
(eq ch ?
'))
2815 ;; Escaped single quote inside single quoted string:
2816 ;; emit just a single quote, since we've changed the
2817 ;; outer quotes to double.
2820 ;; Escaped double quote
2822 ;; This should be interpreted as backslash+quote,
2823 ;; not an escape. Emit a three backslashes
2824 ;; followed by a quote (because one layer of
2825 ;; quoting will be stripped by `org-babel-read').
2826 (append (list ch ?
\\ ?
\\ ?
\\) out
)
2827 ;; Otherwise we are in a double-quoted string. Emit
2828 ;; a single escaped quote
2829 (append (list ch ?
\\) out
)))
2831 ;; Escaped backslash: emit a single escaped backslash
2832 (append (list ?
\\ ?
\\) out
))
2833 ;; Other: emit a quoted backslash followed by whatever
2834 ;; the character was (because one layer of quoting will
2835 ;; be stripped by `org-babel-read').
2836 (t (append (list ch ?
\\ ?
\\) out
))))
2838 (?\
[ (if (or in-double in-single
)
2841 (?\
] (if (or in-double in-single
)
2844 (?\
{ (if (or in-double in-single
)
2847 (?\
} (if (or in-double in-single
)
2850 (?
, (if (or in-double in-single
)
2851 (cons ?
, out
) (cons ?\s out
)))
2854 (setq in-single
(not in-single
)) (cons ?
\" out
)))
2856 (append (list ?
\" ?
\\) out
)
2857 (setq in-double
(not in-double
)) (cons ?
\" out
)))
2858 (?
\\ (unless (or in-single in-double
)
2859 (error "Can't handle backslash outside string in `org-babel-script-escape'"))
2862 (t (cons ch out
))))))
2863 (string-to-list str
))
2864 (when (or in-single in-double
)
2865 (error "Unterminated string in `org-babel-script-escape'"))
2866 (apply #'string
(reverse out
))))
2868 (defun org-babel-script-escape (str &optional force
)
2869 "Safely convert tables into elisp lists."
2870 (unless (stringp str
)
2871 (error "`org-babel-script-escape' expects a string"))
2874 ((and (> (length str
) 2)
2875 (or (and (string-equal "[" (substring str
0 1))
2876 (string-equal "]" (substring str -
1)))
2877 (and (string-equal "{" (substring str
0 1))
2878 (string-equal "}" (substring str -
1)))
2879 (and (string-equal "(" (substring str
0 1))
2880 (string-equal ")" (substring str -
1)))))
2882 (concat "'" (org-babel--script-escape-inner str
)))
2884 (and (> (length str
) 2)
2885 (or (and (string-equal "'" (substring str
0 1))
2886 (string-equal "'" (substring str -
1)))
2887 ;; We need to pass double-quoted strings
2888 ;; through the backslash-twiddling bits, even
2889 ;; though we don't need to change their
2891 (and (string-equal "\"" (substring str
0 1))
2892 (string-equal "\"" (substring str -
1))))))
2893 (org-babel--script-escape-inner str
))
2895 (condition-case nil
(org-babel-read escaped
) (error escaped
))))
2897 (defun org-babel-read (cell &optional inhibit-lisp-eval
)
2898 "Convert the string value of CELL to a number if appropriate.
2899 Otherwise if CELL looks like lisp (meaning it starts with a
2900 \"(\", \"\\='\", \"\\=`\" or a \"[\") then read and evaluate it as
2901 lisp, otherwise return it unmodified as a string. Optional
2902 argument INHIBIT-LISP-EVAL inhibits lisp evaluation for
2903 situations in which is it not appropriate."
2904 (cond ((not (org-string-nw-p cell
)) cell
)
2905 ((org-babel--string-to-number cell
))
2906 ((and (not inhibit-lisp-eval
)
2907 (or (memq (string-to-char cell
) '(?\
( ?
' ?
` ?\
[))
2908 (string= cell
"*this*")))
2909 (eval (read cell
) t
))
2910 ((eq (string-to-char cell
) ?
\") (read cell
))
2911 (t (org-no-properties cell
))))
2913 (defun org-babel--string-to-number (string)
2914 "If STRING represents a number return its value.
2915 Otherwise return nil."
2916 (and (string-match-p "\\`-?[0-9]*\\.?[0-9]*\\'" string
)
2917 (string-to-number string
)))
2919 (defun org-babel-import-elisp-from-file (file-name &optional separator
)
2920 "Read the results located at FILE-NAME into an elisp table.
2921 If the table is trivial, then return it as a scalar."
2923 (save-window-excursion
2927 (org-table-import file-name separator
)
2928 (delete-file file-name
)
2929 (setq result
(mapcar (lambda (row)
2930 (mapcar #'org-babel-string-read row
))
2931 (org-table-to-lisp))))
2932 (error (message "Error reading results: %s" err
) nil
)))
2933 (if (null (cdr result
)) ;; if result is trivial vector, then scalarize it
2934 (if (consp (car result
))
2935 (if (null (cdr (car result
)))
2941 (defun org-babel-string-read (cell)
2942 "Strip nested \"s from around strings."
2943 (org-babel-read (or (and (stringp cell
)
2944 (string-match "\\\"\\(.+\\)\\\"" cell
)
2945 (match-string 1 cell
))
2948 (defun org-babel-chomp (string &optional regexp
)
2949 "Strip a trailing space or carriage return from STRING.
2950 The default regexp used is \"[ \\f\\t\\n\\r\\v]\" but another one
2951 can be specified as the REGEXP argument."
2952 (let ((regexp (or regexp
"[ \f\t\n\r\v]")))
2953 (while (and (> (length string
) 0)
2954 (string-match regexp
(substring string -
1)))
2955 (setq string
(substring string
0 -
1)))
2958 (defun org-babel-process-file-name (name &optional no-quote-p
)
2959 "Prepare NAME to be used in an external process.
2960 If NAME specifies a remote location, the remote portion of the
2961 name is removed, since in that case the process will be executing
2962 remotely. The file name is then processed by `expand-file-name'.
2963 Unless second argument NO-QUOTE-P is non-nil, the file name is
2964 additionally processed by `shell-quote-argument'"
2965 (let ((f (org-babel-local-file-name (expand-file-name name
))))
2966 (if no-quote-p f
(shell-quote-argument f
))))
2968 (defvar org-babel-temporary-directory
)
2969 (unless (or noninteractive
(boundp 'org-babel-temporary-directory
))
2970 (defvar org-babel-temporary-directory
2971 (or (and (boundp 'org-babel-temporary-directory
)
2972 (file-exists-p org-babel-temporary-directory
)
2973 org-babel-temporary-directory
)
2974 (make-temp-file "babel-" t
))
2975 "Directory to hold temporary files created to execute code blocks.
2976 Used by `org-babel-temp-file'. This directory will be removed on
2979 (defcustom org-babel-remote-temporary-directory
"/tmp/"
2980 "Directory to hold temporary files on remote hosts."
2984 (defmacro org-babel-result-cond
(result-params scalar-form
&rest table-forms
)
2985 "Call the code to parse raw string results according to RESULT-PARAMS."
2987 (debug (form form
&rest form
)))
2988 (org-with-gensyms (params)
2989 `(let ((,params
,result-params
))
2990 (unless (member "none" ,params
)
2991 (if (or (member "scalar" ,params
)
2992 (member "verbatim" ,params
)
2993 (member "html" ,params
)
2994 (member "code" ,params
)
2995 (member "pp" ,params
)
2996 (member "file" ,params
)
2997 (and (or (member "output" ,params
)
2998 (member "raw" ,params
)
2999 (member "org" ,params
)
3000 (member "drawer" ,params
))
3001 (not (member "table" ,params
))))
3004 (def-edebug-spec org-babel-result-cond
(form form body
))
3006 (defun org-babel-temp-file (prefix &optional suffix
)
3007 "Create a temporary file in the `org-babel-temporary-directory'.
3008 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
3009 value of `temporary-file-directory' temporarily set to the value
3010 of `org-babel-temporary-directory'."
3011 (if (file-remote-p default-directory
)
3013 (concat (file-remote-p default-directory
)
3015 prefix org-babel-remote-temporary-directory
))))
3016 (make-temp-file prefix nil suffix
))
3017 (let ((temporary-file-directory
3018 (or (and (boundp 'org-babel-temporary-directory
)
3019 (file-exists-p org-babel-temporary-directory
)
3020 org-babel-temporary-directory
)
3021 temporary-file-directory
)))
3022 (make-temp-file prefix nil suffix
))))
3024 (defun org-babel-remove-temporary-directory ()
3025 "Remove `org-babel-temporary-directory' on Emacs shutdown."
3026 (when (and (boundp 'org-babel-temporary-directory
)
3027 (file-exists-p org-babel-temporary-directory
))
3028 ;; taken from `delete-directory' in files.el
3031 (mapc (lambda (file)
3032 ;; This test is equivalent to
3033 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
3034 ;; but more efficient
3035 (if (eq t
(car (file-attributes file
)))
3036 (delete-directory file
)
3037 (delete-file file
)))
3038 ;; We do not want to delete "." and "..".
3039 (directory-files org-babel-temporary-directory
'full
3040 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
3041 (delete-directory org-babel-temporary-directory
))
3043 (message "Failed to remove temporary Org-babel directory %s"
3044 (if (boundp 'org-babel-temporary-directory
)
3045 org-babel-temporary-directory
3046 "[directory not defined]"))))))
3048 (add-hook 'kill-emacs-hook
'org-babel-remove-temporary-directory
)
3050 (defun org-babel-one-header-arg-safe-p (pair safe-list
)
3051 "Determine if the PAIR is a safe babel header arg according to SAFE-LIST.
3053 For the format of SAFE-LIST, see `org-babel-safe-header-args'."
3055 (keywordp (car pair
))
3056 (stringp (cdr pair
))
3058 (memq (car pair
) safe-list
)
3059 (let ((entry (assq (car pair
) safe-list
)))
3062 (cond ((functionp (cdr entry
))
3063 (funcall (cdr entry
) (cdr pair
)))
3064 ((listp (cdr entry
))
3065 (member (cdr pair
) (cdr entry
)))
3068 (defun org-babel-generate-file-param (src-name params
)
3069 "Calculate the filename for source block results.
3071 The directory is calculated from the :output-dir property of the
3072 source block; if not specified, use the current directory.
3074 If the source block has a #+NAME and the :file parameter does not
3075 contain any period characters, then the :file parameter is
3076 treated as an extension, and the output file name is the
3077 concatenation of the directory (as calculated above), the block
3078 name, a period, and the parameter value as a file extension.
3079 Otherwise, the :file parameter is treated as a full file name,
3080 and the output file name is the directory (as calculated above)
3081 plus the parameter value."
3082 (let* ((file-cons (assq :file params
))
3083 (file-ext-cons (assq :file-ext params
))
3084 (file-ext (cdr-safe file-ext-cons
))
3085 (dir (cdr-safe (assq :output-dir params
)))
3087 ;; create the output-dir if it does not exist
3089 (make-directory dir t
))
3091 ;; :file given; add :output-dir if given
3093 (setcdr file-cons
(concat (file-name-as-directory dir
) (cdr file-cons
))))
3094 ;; :file not given; compute from name and :file-ext if possible
3095 (when (and src-name file-ext
)
3097 (setq fname
(concat (file-name-as-directory (or dir
""))
3098 src-name
"." file-ext
))
3099 (setq fname
(concat src-name
"." file-ext
)))
3100 (setq params
(cons (cons :file fname
) params
))))
3103 (defun org-babel-graphical-output-file (params)
3104 "File where a babel block should send graphical output, per PARAMS.
3105 Return nil if no graphical output is expected. Raise an error if
3106 the output file is ill-defined."
3107 (let ((file (cdr (assq :file params
))))
3108 (cond (file (and (member "graphics" (cdr (assq :result-params params
)))
3110 ((assq :file-ext params
)
3111 (user-error ":file-ext given but no :file generated; did you forget \
3113 (t (user-error "No :file header argument given; cannot create \
3114 graphical result")))))
3116 (defun org-babel-make-language-alias (new old
)
3117 "Make source blocks of type NEW aliases for those of type OLD.
3119 NEW and OLD should be strings. This function should be called
3120 after the babel API for OLD-type source blocks is fully defined.
3122 Callers of this function will probably want to add an entry to
3123 `org-src-lang-modes' as well."
3124 (dolist (fn '("execute" "expand-body" "prep-session"
3125 "variable-assignments" "load-session"))
3126 (let ((sym (intern-soft (concat "org-babel-" fn
":" old
))))
3127 (when (and sym
(fboundp sym
))
3128 (defalias (intern (concat "org-babel-" fn
":" new
)) sym
))))
3129 ;; Technically we don't need a `dolist' for just one variable, but
3130 ;; we keep it for symmetry/ease of future expansion.
3131 (dolist (var '("default-header-args"))
3132 (let ((sym (intern-soft (concat "org-babel-" var
":" old
))))
3133 (when (and sym
(boundp sym
))
3134 (defvaralias (intern (concat "org-babel-" var
":" new
)) sym
)))))
3136 (defun org-babel-strip-quotes (string)
3137 "Strip \\\"s from around a string, if applicable."
3138 (org-unbracket-string "\"" "\"" string
))
3143 ;; generated-autoload-file: "org-loaddefs.el"
3146 ;;; ob-core.el ends here