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-split-string
"org" (string &optional separators
))
86 (declare-function org-src-coderef-format
"org-src" (element))
87 (declare-function org-src-coderef-regexp
"org-src" (fmt &optional label
))
88 (declare-function org-table-align
"org-table" ())
89 (declare-function org-table-end
"org-table" (&optional table-type
))
90 (declare-function org-table-import
"org-table" (file arg
))
91 (declare-function org-table-to-lisp
"org-table" (&optional txt
))
92 (declare-function org-trim
"org" (s &optional keep-lead
))
93 (declare-function org-unescape-code-in-string
"org-src" (s))
94 (declare-function org-uniquify
"org" (list))
95 (declare-function orgtbl-to-generic
"org-table" (table params
))
96 (declare-function orgtbl-to-orgtbl
"org-table" (table params
))
97 (declare-function outline-show-all
"outline" ())
98 (declare-function tramp-compat-make-temp-file
"tramp-compat" (filename &optional dir-flag
))
100 (defgroup org-babel nil
101 "Code block evaluation and management in `org-mode' documents."
105 (defcustom org-confirm-babel-evaluate t
106 "Confirm before evaluation.
108 Require confirmation before interactively evaluating code
109 blocks in Org buffers. The default value of this variable is t,
110 meaning confirmation is required for any code block evaluation.
111 This variable can be set to nil to inhibit any future
112 confirmation requests. This variable can also be set to a
113 function which takes two arguments the language of the code block
114 and the body of the code block. Such a function should then
115 return a non-nil value if the user should be prompted for
116 execution or nil if no prompt is required.
118 Warning: Disabling confirmation may result in accidental
119 evaluation of potentially harmful code. It may be advisable
120 remove code block execution from `\\[org-ctrl-c-ctrl-c]' \
121 as further protection
122 against accidental code block evaluation. The
123 `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
124 remove code block execution from the `\\[org-ctrl-c-ctrl-c]' keybinding."
127 :type
'(choice boolean function
))
128 ;; don't allow this variable to be changed through file settings
129 (put 'org-confirm-babel-evaluate
'safe-local-variable
(lambda (x) (eq x t
)))
131 (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
133 Remove code block evaluation from the `\\[org-ctrl-c-ctrl-c]' key binding."
138 (defcustom org-babel-results-keyword
"RESULTS"
139 "Keyword used to name results generated by code blocks.
140 It should be \"RESULTS\". However any capitalization may be
144 :package-version
'(Org .
"8.0")
148 (eq (compare-strings "RESULTS" nil nil v nil nil t
)
151 (defcustom org-babel-noweb-wrap-start
"<<"
152 "String used to begin a noweb reference in a code block.
153 See also `org-babel-noweb-wrap-end'."
157 (defcustom org-babel-noweb-wrap-end
">>"
158 "String used to end a noweb reference in a code block.
159 See also `org-babel-noweb-wrap-start'."
163 (defcustom org-babel-inline-result-wrap
"=%s="
164 "Format string used to wrap inline results.
165 This string must include a \"%s\" which will be replaced by the results."
168 (put 'org-babel-inline-result-wrap
172 (string-match-p "%s" value
))))
174 (defcustom org-babel-hash-show-time nil
175 "Non-nil means show the time the code block was evaluated in the result hash."
179 :package-version
'(Org .
"9.0")
182 (defcustom org-babel-uppercase-example-markers nil
183 "When non-nil, begin/end example markers will be inserted in upper case."
187 :package-version
'(Org .
"9.1")
190 (defun org-babel-noweb-wrap (&optional regexp
)
191 (concat org-babel-noweb-wrap-start
192 (or regexp
"\\([^ \t\n].+?[^ \t]\\|[^ \t\n]\\)")
193 org-babel-noweb-wrap-end
))
195 (defvar org-babel-src-name-regexp
196 "^[ \t]*#\\+name:[ \t]*"
197 "Regular expression used to match a source name line.")
199 (defvar org-babel-multi-line-header-regexp
200 "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
201 "Regular expression used to match multi-line header arguments.")
203 (defvar org-babel-src-block-regexp
205 ;; (1) indentation (2) lang
206 "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
208 "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
209 ;; (4) header arguments
212 "\\([^\000]*?\n\\)??[ \t]*#\\+end_src")
213 "Regexp used to identify code blocks.")
215 (defun org-babel--get-vars (params)
216 "Return the babel variable assignments in PARAMS.
218 PARAMS is a quasi-alist of header args, which may contain
219 multiple entries for the key `:var'. This function returns a
220 list of the cdr of all the `:var' entries."
222 (cl-remove-if-not (lambda (x) (eq (car x
) :var
)) params
)))
224 (defvar org-babel-exp-reference-buffer nil
225 "Buffer containing original contents of the exported buffer.
226 This is used by Babel to resolve references in source blocks.
227 Its value is dynamically bound during export.")
229 (defun org-babel-check-confirm-evaluate (info)
230 "Check whether INFO allows code block evaluation.
232 Returns nil if evaluation is disallowed, t if it is
233 unconditionally allowed, and the symbol `query' if the user
234 should be asked whether to allow evaluation."
235 (let* ((headers (nth 2 info
))
236 (eval (or (cdr (assq :eval headers
))
237 (when (assq :noeval headers
) "no")))
238 (eval-no (member eval
'("no" "never")))
239 (export org-babel-exp-reference-buffer
)
240 (eval-no-export (and export
(member eval
'("no-export" "never-export"))))
241 (noeval (or eval-no eval-no-export
))
242 (query (or (equal eval
"query")
243 (and export
(equal eval
"query-export"))
244 (if (functionp org-confirm-babel-evaluate
)
246 (goto-char (nth 5 info
))
247 (funcall org-confirm-babel-evaluate
248 ;; language, code block body
249 (nth 0 info
) (nth 1 info
)))
250 org-confirm-babel-evaluate
))))
256 (defun org-babel-check-evaluate (info)
257 "Check if code block INFO should be evaluated.
258 Do not query the user, but do display an informative message if
259 evaluation is blocked. Returns non-nil if evaluation is not blocked."
260 (let ((confirmed (org-babel-check-confirm-evaluate info
)))
262 (message "Evaluation of this %s code block%sis disabled."
264 (let ((name (nth 4 info
)))
265 (if name
(format " (%s) " name
) " "))))
268 ;; Dynamically scoped for asynchronous export.
269 (defvar org-babel-confirm-evaluate-answer-no
)
271 (defun org-babel-confirm-evaluate (info)
272 "Confirm evaluation of the code block INFO.
274 This query can also be suppressed by setting the value of
275 `org-confirm-babel-evaluate' to nil, in which case all future
276 interactive code block evaluations will proceed without any
277 confirmation from the user.
279 Note disabling confirmation may result in accidental evaluation
280 of potentially harmful code.
282 The variable `org-babel-confirm-evaluate-answer-no' is used by
283 the async export process, which requires a non-interactive
284 environment, to override this check."
285 (let* ((evalp (org-babel-check-confirm-evaluate info
))
288 (name-string (if name
(format " (%s) " name
) " ")))
293 (and (not (bound-and-true-p
294 org-babel-confirm-evaluate-answer-no
))
296 (format "Evaluate this %s code block%son your system? "
299 (message "Evaluation of this %s code block%sis aborted."
302 (x (error "Unexpected value `%s' from `org-babel-check-confirm-evaluate'" x
)))))
305 (defun org-babel-execute-safely-maybe ()
306 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
307 (org-babel-execute-maybe)))
310 (defun org-babel-execute-maybe ()
312 (or (org-babel-execute-src-block-maybe)
313 (org-babel-lob-execute-maybe)))
315 (defmacro org-babel-when-in-src-block
(&rest body
)
316 "Execute BODY if point is in a source block and return t.
318 Otherwise do nothing and return nil."
319 `(if (memq (org-element-type (org-element-context))
320 '(inline-src-block src-block
))
326 (defun org-babel-execute-src-block-maybe ()
327 "Conditionally execute a source block.
328 Detect if this is context for a Babel src-block and if so
329 then run `org-babel-execute-src-block'."
331 (org-babel-when-in-src-block
332 (org-babel-eval-wipe-error-buffer)
333 (org-babel-execute-src-block current-prefix-arg
)))
336 (defun org-babel-view-src-block-info ()
337 "Display information on the current source block.
338 This includes header arguments, language and name, and is largely
339 a window into the `org-babel-get-src-block-info' function."
341 (let ((info (org-babel-get-src-block-info 'light
))
342 (full (lambda (it) (> (length it
) 0)))
343 (printf (lambda (fmt &rest args
) (princ (apply #'format fmt args
)))))
345 (with-help-window (help-buffer)
346 (let ((name (nth 4 info
))
348 (switches (nth 3 info
))
349 (header-args (nth 2 info
)))
350 (when name
(funcall printf
"Name: %s\n" name
))
351 (when lang
(funcall printf
"Lang: %s\n" lang
))
352 (funcall printf
"Properties:\n")
353 (funcall printf
"\t:header-args \t%s\n" (org-entry-get (point) "header-args" t
))
354 (funcall printf
"\t:header-args:%s \t%s\n" lang
(org-entry-get (point) (concat "header-args:" lang
) t
))
356 (when (funcall full switches
) (funcall printf
"Switches: %s\n" switches
))
357 (funcall printf
"Header Arguments:\n")
358 (dolist (pair (sort header-args
359 (lambda (a b
) (string< (symbol-name (car a
))
360 (symbol-name (car b
))))))
361 (when (funcall full
(format "%s" (cdr pair
)))
362 (funcall printf
"\t%S%s\t%s\n"
364 (if (> (length (format "%S" (car pair
))) 7) "" "\t")
368 (defun org-babel-expand-src-block-maybe ()
369 "Conditionally expand a source block.
370 Detect if this is context for a org-babel src-block and if so
371 then run `org-babel-expand-src-block'."
373 (org-babel-when-in-src-block
374 (org-babel-expand-src-block current-prefix-arg
)))
377 (defun org-babel-load-in-session-maybe ()
378 "Conditionally load a source block in a session.
379 Detect if this is context for a org-babel src-block and if so
380 then run `org-babel-load-in-session'."
382 (org-babel-when-in-src-block
383 (org-babel-load-in-session current-prefix-arg
)))
385 (add-hook 'org-metaup-hook
'org-babel-load-in-session-maybe
)
388 (defun org-babel-pop-to-session-maybe ()
389 "Conditionally pop to a session.
390 Detect if this is context for a org-babel src-block and if so
391 then run `org-babel-switch-to-session'."
393 (org-babel-when-in-src-block
394 (org-babel-switch-to-session current-prefix-arg
)))
396 (add-hook 'org-metadown-hook
'org-babel-pop-to-session-maybe
)
398 (defconst org-babel-common-header-args-w-values
399 '((cache .
((no yes
)))
401 (colnames .
((nil no yes
)))
402 (comments .
((no link yes org both noweb
)))
404 (eval .
((yes no no-export strip-export never-export eval never
406 (exports .
((code results both none
)))
411 (hlines .
((no yes
)))
412 (mkdirp .
((yes no
)))
415 (noweb .
((yes no tangle no-export strip-export
)))
419 (padline .
((yes no
)))
422 (results .
((file list vector table scalar verbatim
)
423 (raw html latex org code pp drawer
)
424 (replace silent none append prepend
)
426 (rownames .
((no yes
)))
430 (tangle .
((tangle yes no
:any
)))
431 (tangle-mode .
((#o755
#o555
#o444
:any
)))
435 (defconst org-babel-header-arg-names
436 (mapcar #'car org-babel-common-header-args-w-values
)
437 "Common header arguments used by org-babel.
438 Note that individual languages may define their own language
439 specific header arguments as well.")
441 (defconst org-babel-safe-header-args
442 '(:cache
:colnames
:comments
:exports
:epilogue
:hlines
:noeval
443 :noweb
:noweb-ref
:noweb-sep
:padline
:prologue
:rownames
444 :sep
:session
:tangle
:wrap
445 (:eval .
("never" "query"))
446 (:results .
(lambda (str) (not (string-match "file" str
)))))
447 "A list of safe header arguments for babel source blocks.
449 The list can have entries of the following forms:
450 - :ARG -> :ARG is always a safe header arg
451 - (:ARG . (VAL1 VAL2 ...)) -> :ARG is safe as a header arg if it is
452 `equal' to one of the VALs.
453 - (:ARG . FN) -> :ARG is safe as a header arg if the function FN
454 returns non-nil. FN is passed one
455 argument, the value of the header arg
458 (defmacro org-babel-header-args-safe-fn
(safe-list)
459 "Return a function that determines whether a list of header args are safe.
462 \(put \\='org-babel-default-header-args \\='safe-local-variable
463 (org-babel-header-args-safe-p org-babel-safe-header-args)
465 This allows org-babel languages to extend the list of safe values for
466 their `org-babel-default-header-args:foo' variable.
468 For the format of SAFE-LIST, see `org-babel-safe-header-args'."
474 (org-babel-one-header-arg-safe-p pair
,safe-list
)))
477 (defvar org-babel-default-header-args
478 '((:session .
"none") (:results .
"replace") (:exports .
"code")
479 (:cache .
"no") (:noweb .
"no") (:hlines .
"no") (:tangle .
"no"))
480 "Default arguments to use when evaluating a source block.")
481 (put 'org-babel-default-header-args
'safe-local-variable
482 (org-babel-header-args-safe-fn org-babel-safe-header-args
))
484 (defvar org-babel-default-inline-header-args
485 '((:session .
"none") (:results .
"replace")
486 (:exports .
"results") (:hlines .
"yes"))
487 "Default arguments to use when evaluating an inline source block.")
488 (put 'org-babel-default-inline-header-args
'safe-local-variable
489 (org-babel-header-args-safe-fn org-babel-safe-header-args
))
491 (defconst org-babel-name-regexp
492 (format "^[ \t]*#\\+%s:[ \t]*"
493 ;; FIXME: TBLNAME is for backward compatibility.
494 (regexp-opt '("NAME" "TBLNAME")))
495 "Regexp matching a NAME keyword.")
497 (defconst org-babel-result-regexp
498 (format "^[ \t]*#\\+%s\\(?:\\[\\(?:%s \\)?\\([[:alnum:]]+\\)\\]\\)?:[ \t]*"
499 org-babel-results-keyword
500 ;; <%Y-%m-%d %H:%M:%S>
501 "<\\(?:[0-9]\\{4\\}-[0-1][0-9]-[0-3][0-9] \
502 [0-2][0-9]\\(?::[0-5][0-9]\\)\\{2\\}\\)>")
503 "Regular expression used to match result lines.
504 If the results are associated with a hash key then the hash will
505 be saved in match group 1.")
507 (defconst org-babel-result-w-name-regexp
508 (concat org-babel-result-regexp
"\\(?9:[^ \t\n\r\v\f]+\\)")
509 "Regexp matching a RESULTS keyword with a name.
510 Name is saved in match group 9.")
512 (defvar org-babel-min-lines-for-block-output
10
513 "The minimum number of lines for block output.
514 If number of lines of output is equal to or exceeds this
515 value, the output is placed in a #+begin_example...#+end_example
516 block. Otherwise the output is marked as literal by inserting
517 colons at the starts of the lines. This variable only takes
518 effect if the :results output option is in effect.")
520 (defvar org-babel-noweb-error-all-langs nil
521 "Raise errors when noweb references don't resolve.
522 Also see `org-babel-noweb-error-langs' to control noweb errors on
523 a language by language bases.")
525 (defvar org-babel-noweb-error-langs nil
526 "Languages for which Babel will raise literate programming errors.
527 List of languages for which errors should be raised when the
528 source code block satisfying a noweb reference in this language
529 can not be resolved. Also see `org-babel-noweb-error-all-langs'
530 to raise errors for all languages.")
532 (defvar org-babel-hash-show
4
533 "Number of initial characters to show of a hidden results hash.")
535 (defvar org-babel-after-execute-hook nil
536 "Hook for functions to be called after `org-babel-execute-src-block'")
538 (defun org-babel-named-src-block-regexp-for-name (&optional name
)
539 "This generates a regexp used to match a src block named NAME.
540 If NAME is nil, match any name. Matched name is then put in
541 match group 9. Other match groups are defined in
542 `org-babel-src-block-regexp'."
543 (concat org-babel-src-name-regexp
544 (concat (if name
(regexp-quote name
) "\\(?9:.*?\\)") "[ \t]*" )
545 "\\(?:\n[ \t]*#\\+\\S-+:.*\\)*?"
547 (substring org-babel-src-block-regexp
1)))
549 (defun org-babel-named-data-regexp-for-name (name)
550 "This generates a regexp used to match data named NAME."
551 (concat org-babel-name-regexp
(regexp-quote name
) "[ \t]*$"))
553 (defun org-babel--normalize-body (datum)
554 "Normalize body for element or object DATUM.
555 DATUM is a source block element or an inline source block object.
556 Remove final newline character and spurious indentation."
557 (let* ((value (org-element-property :value datum
))
558 (body (if (string-suffix-p "\n" value
)
559 (substring value
0 -
1)
561 (cond ((eq (org-element-type datum
) 'inline-src-block
)
562 ;; Newline characters and indentation in an inline
563 ;; src-block are not meaningful, since they could come from
564 ;; some paragraph filling. Treat them as a white space.
565 (replace-regexp-in-string "\n[ \t]*" " " body
))
566 ((or org-src-preserve-indentation
567 (org-element-property :preserve-indent datum
))
569 (t (org-remove-indentation body
)))))
572 (defvar org-babel-current-src-block-location nil
573 "Marker pointing to the src block currently being executed.
574 This may also point to a call line or an inline code block. If
575 multiple blocks are being executed (e.g., in chained execution
576 through use of the :var header argument) this marker points to
577 the outer-most code block.")
581 (defun org-babel-get-src-block-info (&optional light datum
)
582 "Extract information from a source block or inline source block.
584 Optional argument LIGHT does not resolve remote variable
585 references; a process which could likely result in the execution
586 of other code blocks.
588 By default, consider the block at point. However, when optional
589 argument DATUM is provided, extract information from that parsed
592 Return nil if point is not on a source block. Otherwise, return
593 a list with the following pattern:
595 (language body arguments switches name start coderef)"
596 (let* ((datum (or datum
(org-element-context)))
597 (type (org-element-type datum
))
598 (inline (eq type
'inline-src-block
)))
599 (when (memq type
'(inline-src-block src-block
))
600 (let* ((lang (org-element-property :language datum
))
601 (lang-headers (intern
602 (concat "org-babel-default-header-args:" lang
)))
603 (name (org-element-property :name datum
))
607 (org-babel--normalize-body datum
)
608 (apply #'org-babel-merge-params
609 (if inline org-babel-default-inline-header-args
610 org-babel-default-header-args
)
611 (and (boundp lang-headers
) (eval lang-headers t
))
613 ;; If DATUM is provided, make sure we get node
614 ;; properties applicable to its location within
616 (org-with-point-at (org-element-property :begin datum
)
617 (org-babel-params-from-properties lang
))
618 (mapcar #'org-babel-parse-header-arguments
619 (cons (org-element-property :parameters datum
)
620 (org-element-property :header datum
)))))
621 (or (org-element-property :switches datum
) "")
623 (org-element-property (if inline
:begin
:post-affiliated
)
625 (and (not inline
) (org-src-coderef-format datum
)))))
627 (setf (nth 2 info
) (org-babel-process-params (nth 2 info
))))
628 (setf (nth 2 info
) (org-babel-generate-file-param name
(nth 2 info
)))
632 (defun org-babel-execute-src-block (&optional arg info params
)
633 "Execute the current source code block.
634 Insert the results of execution into the buffer. Source code
635 execution and the collection and formatting of results can be
636 controlled through a variety of header arguments.
638 With prefix argument ARG, force re-execution even if an existing
639 result cached in the buffer would otherwise have been returned.
641 Optionally supply a value for INFO in the form returned by
642 `org-babel-get-src-block-info'.
644 Optionally supply a value for PARAMS which will be merged with
645 the header arguments specified at the front of the source code
648 (let* ((org-babel-current-src-block-location
649 (or org-babel-current-src-block-location
651 (org-babel-where-is-src-block-head)))
652 (info (if info
(copy-tree info
) (org-babel-get-src-block-info))))
653 ;; Merge PARAMS with INFO before considering source block
654 ;; evaluation since both could disagree.
655 (cl-callf org-babel-merge-params
(nth 2 info
) params
)
656 (when (org-babel-check-evaluate info
)
657 (cl-callf org-babel-process-params
(nth 2 info
))
658 (let* ((params (nth 2 info
))
659 (cache (let ((c (cdr (assq :cache params
))))
660 (and (not arg
) c
(string= "yes" c
))))
661 (new-hash (and cache
(org-babel-sha1-hash info
)))
662 (old-hash (and cache
(org-babel-current-result-hash)))
663 (current-cache (and new-hash
(equal new-hash old-hash
))))
666 (save-excursion ;Return cached result.
667 (goto-char (org-babel-where-is-src-block-result nil info
))
669 (skip-chars-forward " \t")
670 (let ((result (org-babel-read-result)))
671 (message (replace-regexp-in-string "%" "%%" (format "%S" result
)))
673 ((org-babel-confirm-evaluate info
)
674 (let* ((lang (nth 0 info
))
675 (result-params (cdr (assq :result-params params
)))
676 ;; Expand noweb references in BODY and remove any
679 (let ((coderef (nth 6 info
))
681 (if (org-babel-noweb-p params
:eval
)
682 (org-babel-expand-noweb-references info
)
684 (if (not coderef
) expand
685 (replace-regexp-in-string
686 (org-src-coderef-regexp coderef
) "" expand nil nil
1))))
687 (dir (cdr (assq :dir params
)))
689 (or (and dir
(file-name-as-directory (expand-file-name dir
)))
691 (cmd (intern (concat "org-babel-execute:" lang
)))
693 (unless (fboundp cmd
)
694 (error "No org-babel-execute function for %s!" lang
))
695 (message "executing %s code block%s..."
697 (let ((name (nth 4 info
)))
698 (if name
(format " (%s)" name
) "")))
699 (if (member "none" result-params
)
700 (progn (funcall cmd body params
)
701 (message "result silenced"))
703 (let ((r (funcall cmd body params
)))
704 (if (and (eq (cdr (assq :result-type params
)) 'value
)
705 (or (member "vector" result-params
)
706 (member "table" result-params
))
710 (let ((file (cdr (assq :file params
))))
711 ;; If non-empty result and :file then write to :file.
715 (insert (org-babel-format-result
716 result
(cdr (assq :sep params
))))))
718 ;; Possibly perform post process provided its
719 ;; appropriate. Dynamically bind "*this*" to the
720 ;; actual results of the block.
721 (let ((post (cdr (assq :post params
))))
723 (let ((*this
* (if (not file
) result
724 (org-babel-result-to-file
726 (let ((desc (assq :file-desc params
)))
727 (and desc
(or (cdr desc
) result
)))))))
728 (setq result
(org-babel-ref-resolve post
))
730 (setq result-params
(remove "file" result-params
))))))
731 (org-babel-insert-result
732 result result-params info new-hash lang
)))
733 (run-hooks 'org-babel-after-execute-hook
)
736 (defun org-babel-expand-body:generic
(body params
&optional var-lines
)
737 "Expand BODY with PARAMS.
738 Expand a block of code with org-babel according to its header
739 arguments. This generic implementation of body expansion is
740 called for languages which have not defined their own specific
741 org-babel-expand-body:lang function."
742 (let ((pro (cdr (assq :prologue params
)))
743 (epi (cdr (assq :epilogue params
))))
744 (mapconcat #'identity
745 (append (when pro
(list pro
))
748 (when epi
(list epi
)))
752 (defun org-babel-expand-src-block (&optional _arg info params
)
753 "Expand the current source code block.
754 Expand according to the source code block's header
755 arguments and pop open the results in a preview buffer."
757 (let* ((info (or info
(org-babel-get-src-block-info)))
759 (params (setf (nth 2 info
)
760 (sort (org-babel-merge-params (nth 2 info
) params
)
761 (lambda (el1 el2
) (string< (symbol-name (car el1
))
762 (symbol-name (car el2
)))))))
763 (body (setf (nth 1 info
)
764 (if (org-babel-noweb-p params
:eval
)
765 (org-babel-expand-noweb-references info
) (nth 1 info
))))
766 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
767 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
770 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
771 (org-babel-expand-body:generic
772 body params
(and (fboundp assignments-cmd
)
773 (funcall assignments-cmd params
))))))
774 (if (called-interactively-p 'any
)
776 expanded
(concat "*Org-Babel Preview " (buffer-name) "[ " lang
" ]*"))
779 (defun org-babel-edit-distance (s1 s2
)
780 "Return the edit (levenshtein) distance between strings S1 S2."
781 (let* ((l1 (length s1
))
783 (dist (vconcat (mapcar (lambda (_) (make-vector (1+ l2
) nil
))
784 (number-sequence 1 (1+ l1
)))))
785 (in (lambda (i j
) (aref (aref dist i
) j
))))
786 (setf (aref (aref dist
0) 0) 0)
787 (dolist (j (number-sequence 1 l2
))
788 (setf (aref (aref dist
0) j
) j
))
789 (dolist (i (number-sequence 1 l1
))
790 (setf (aref (aref dist i
) 0) i
)
791 (dolist (j (number-sequence 1 l2
))
792 (setf (aref (aref dist i
) j
)
794 (1+ (funcall in
(1- i
) j
))
795 (1+ (funcall in i
(1- j
)))
796 (+ (if (equal (aref s1
(1- i
)) (aref s2
(1- j
))) 0 1)
797 (funcall in
(1- i
) (1- j
)))))))
800 (defun org-babel-combine-header-arg-lists (original &rest others
)
801 "Combine a number of lists of header argument names and arguments."
802 (let ((results (copy-sequence original
)))
803 (dolist (new-list others
)
804 (dolist (arg-pair new-list
)
805 (let ((header (car arg-pair
)))
807 (cons arg-pair
(cl-remove-if
808 (lambda (pair) (equal header
(car pair
)))
813 (defun org-babel-check-src-block ()
814 "Check for misspelled header arguments in the current code block."
816 ;; TODO: report malformed code block
817 ;; TODO: report incompatible combinations of header arguments
818 ;; TODO: report uninitialized variables
819 (let ((too-close 2) ;; <- control closeness to report potential match
820 (names (mapcar #'symbol-name org-babel-header-arg-names
)))
821 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg
)) 1))
822 (and (org-babel-where-is-src-block-head)
823 (org-babel-parse-header-arguments
825 (match-string 4))))))
827 (when (and (not (string= header name
))
828 (<= (org-babel-edit-distance header name
) too-close
)
829 (not (member header names
)))
830 (error "Supplied header \"%S\" is suspiciously close to \"%S\""
832 (message "No suspicious header arguments found.")))
835 (defun org-babel-insert-header-arg (&optional header-arg value
)
836 "Insert a header argument selecting from lists of common args and values."
838 (let* ((info (org-babel-get-src-block-info 'light
))
841 (lang-headers (intern (concat "org-babel-header-args:" lang
)))
842 (headers (org-babel-combine-header-arg-lists
843 org-babel-common-header-args-w-values
844 (when (boundp lang-headers
) (eval lang-headers t
))))
845 (header-arg (or header-arg
849 (lambda (header-spec) (symbol-name (car header-spec
)))
851 (vals (cdr (assoc (intern header-arg
) headers
)))
855 (read-from-minibuffer "value: "))
859 (let ((arg (completing-read
862 (mapcar #'symbol-name group
)))))
863 (if (and arg
(not (string= "default" arg
)))
869 (goto-char (point-at-eol))
870 (unless (= (char-before (point)) ?\
) (insert " "))
871 (insert ":" header-arg
) (when value
(insert " " value
)))))
873 ;; Add support for completing-read insertion of header arguments after ":"
874 (defun org-babel-header-arg-expand ()
875 "Call `org-babel-enter-header-arg-w-completion' in appropriate contexts."
876 (when (and (equal (char-before) ?\
:) (org-babel-where-is-src-block-head))
877 (org-babel-enter-header-arg-w-completion (match-string 2))))
879 (defun org-babel-enter-header-arg-w-completion (&optional lang
)
880 "Insert header argument appropriate for LANG with completion."
881 (let* ((lang-headers-var (intern (concat "org-babel-header-args:" lang
)))
882 (lang-headers (when (boundp lang-headers-var
) (eval lang-headers-var t
)))
883 (headers-w-values (org-babel-combine-header-arg-lists
884 org-babel-common-header-args-w-values lang-headers
))
885 (headers (mapcar #'symbol-name
(mapcar #'car headers-w-values
)))
886 (header (org-completing-read "Header Arg: " headers
))
887 (args (cdr (assoc (intern header
) headers-w-values
)))
888 (arg (when (and args
(listp args
))
890 (format "%s: " header
)
891 (mapcar #'symbol-name
(apply #'append args
))))))
892 (insert (concat header
" " (or arg
"")))
895 (add-hook 'org-tab-first-hook
'org-babel-header-arg-expand
)
898 (defun org-babel-load-in-session (&optional _arg info
)
899 "Load the body of the current source-code block.
900 Evaluate the header arguments for the source block before
901 entering the session. After loading the body this pops open the
904 (let* ((info (or info
(org-babel-get-src-block-info)))
906 (params (nth 2 info
))
908 (user-error "No src code block at point")
910 (if (org-babel-noweb-p params
:eval
)
911 (org-babel-expand-noweb-references info
)
913 (session (cdr (assq :session params
)))
914 (dir (cdr (assq :dir params
)))
916 (or (and dir
(file-name-as-directory dir
)) default-directory
))
917 (cmd (intern (concat "org-babel-load-session:" lang
))))
918 (unless (fboundp cmd
)
919 (error "No org-babel-load-session function for %s!" lang
))
920 (pop-to-buffer (funcall cmd session body params
))
924 (defun org-babel-initiate-session (&optional arg info
)
925 "Initiate session for current code block.
926 If called with a prefix argument then resolve any variable
927 references in the header arguments and assign these variables in
928 the session. Copy the body of the code block to the kill ring."
930 (let* ((info (or info
(org-babel-get-src-block-info (not arg
))))
933 (params (nth 2 info
))
934 (session (cdr (assq :session params
)))
935 (dir (cdr (assq :dir params
)))
937 (or (and dir
(file-name-as-directory dir
)) default-directory
))
938 (init-cmd (intern (format "org-babel-%s-initiate-session" lang
)))
939 (prep-cmd (intern (concat "org-babel-prep-session:" lang
))))
940 (when (and (stringp session
) (string= session
"none"))
941 (error "This block is not using a session!"))
942 (unless (fboundp init-cmd
)
943 (error "No org-babel-initiate-session function for %s!" lang
))
944 (with-temp-buffer (insert (org-trim body
))
945 (copy-region-as-kill (point-min) (point-max)))
947 (unless (fboundp prep-cmd
)
948 (error "No org-babel-prep-session function for %s!" lang
))
949 (funcall prep-cmd session params
))
950 (funcall init-cmd session params
)))
953 (defun org-babel-switch-to-session (&optional arg info
)
954 "Switch to the session of the current code block.
955 Uses `org-babel-initiate-session' to start the session. If called
956 with a prefix argument then this is passed on to
957 `org-babel-initiate-session'."
959 (pop-to-buffer (org-babel-initiate-session arg info
))
962 (defalias 'org-babel-pop-to-session
'org-babel-switch-to-session
)
964 (defvar org-src-window-setup
)
967 (defun org-babel-switch-to-session-with-code (&optional arg _info
)
968 "Switch to code buffer and display session."
972 (let ((other-window-buffer (window-buffer (next-window))))
973 (set-window-buffer (next-window) (current-buffer))
974 (set-window-buffer (selected-window) other-window-buffer
))
976 (info (org-babel-get-src-block-info))
977 (org-src-window-setup 'reorganize-frame
))
979 (org-babel-switch-to-session arg info
))
981 (funcall swap-windows
)))
984 (defmacro org-babel-do-in-edit-buffer
(&rest body
)
985 "Evaluate BODY in edit buffer if there is a code block at point.
986 Return t if a code block was found at point, nil otherwise."
987 `(let ((org-src-window-setup 'switch-invisibly
))
988 (when (and (org-babel-where-is-src-block-head)
990 (unwind-protect (progn ,@body
)
993 (def-edebug-spec org-babel-do-in-edit-buffer
(body))
995 (defun org-babel-do-key-sequence-in-edit-buffer (key)
996 "Read key sequence and execute the command in edit buffer.
997 Enter a key sequence to be executed in the language major-mode
998 edit buffer. For example, TAB will alter the contents of the
999 Org code block according to the effect of TAB in the language
1000 major mode buffer. For languages that support interactive
1001 sessions, this can be used to send code from the Org buffer
1002 to the session for evaluation using the native major mode
1003 evaluation mechanisms."
1004 (interactive "kEnter key-sequence to execute in edit buffer: ")
1005 (org-babel-do-in-edit-buffer
1007 (key-binding (or key
(read-key-sequence nil
))))))
1009 (defvar org-bracket-link-regexp
)
1011 (defun org-babel-active-location-p ()
1012 (memq (org-element-type (save-match-data (org-element-context)))
1013 '(babel-call inline-babel-call inline-src-block src-block
)))
1016 (defun org-babel-open-src-block-result (&optional re-run
)
1017 "If `point' is on a src block then open the results of the
1018 source code block, otherwise return nil. With optional prefix
1019 argument RE-RUN the source-code block is evaluated even if
1020 results already exist."
1022 (let ((info (org-babel-get-src-block-info 'light
)))
1025 ;; go to the results, if there aren't any then run the block
1026 (goto-char (or (and (not re-run
) (org-babel-where-is-src-block-result))
1027 (progn (org-babel-execute-src-block)
1028 (org-babel-where-is-src-block-result))))
1030 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
1032 (if (looking-at org-bracket-link-regexp
)
1035 (let ((r (org-babel-format-result
1036 (org-babel-read-result) (cdr (assq :sep
(nth 2 info
))))))
1037 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
1038 (delete-region (point-min) (point-max))
1043 (defmacro org-babel-map-src-blocks
(file &rest body
)
1044 "Evaluate BODY forms on each source-block in FILE.
1045 If FILE is nil evaluate BODY forms on source blocks in current
1046 buffer. During evaluation of BODY the following local variables
1047 are set relative to the currently matched code block.
1049 full-block ------- string holding the entirety of the code block
1050 beg-block -------- point at the beginning of the code block
1051 end-block -------- point at the end of the matched code block
1052 lang ------------- string holding the language of the code block
1053 beg-lang --------- point at the beginning of the lang
1054 end-lang --------- point at the end of the lang
1055 switches --------- string holding the switches
1056 beg-switches ----- point at the beginning of the switches
1057 end-switches ----- point at the end of the switches
1058 header-args ------ string holding the header-args
1059 beg-header-args -- point at the beginning of the header-args
1060 end-header-args -- point at the end of the header-args
1061 body ------------- string holding the body of the code block
1062 beg-body --------- point at the beginning of the body
1063 end-body --------- point at the end of the body"
1064 (declare (indent 1))
1065 (let ((tempvar (make-symbol "file")))
1066 `(let* ((case-fold-search t
)
1068 (visited-p (or (null ,tempvar
)
1069 (get-file-buffer (expand-file-name ,tempvar
))))
1070 (point (point)) to-be-removed
)
1071 (save-window-excursion
1072 (when ,tempvar
(find-file ,tempvar
))
1073 (setq to-be-removed
(current-buffer))
1074 (goto-char (point-min))
1075 (while (re-search-forward org-babel-src-block-regexp nil t
)
1076 (when (org-babel-active-location-p)
1077 (goto-char (match-beginning 0))
1078 (let ((full-block (match-string 0))
1079 (beg-block (match-beginning 0))
1080 (end-block (match-end 0))
1081 (lang (match-string 2))
1082 (beg-lang (match-beginning 2))
1083 (end-lang (match-end 2))
1084 (switches (match-string 3))
1085 (beg-switches (match-beginning 3))
1086 (end-switches (match-end 3))
1087 (header-args (match-string 4))
1088 (beg-header-args (match-beginning 4))
1089 (end-header-args (match-end 4))
1090 (body (match-string 5))
1091 (beg-body (match-beginning 5))
1092 (end-body (match-end 5)))
1093 ;; Silence byte-compiler in case `body' doesn't use all
1095 (ignore full-block beg-block end-block lang
1096 beg-lang end-lang switches beg-switches
1097 end-switches header-args beg-header-args
1098 end-header-args body beg-body end-body
)
1100 (goto-char end-block
)))))
1101 (unless visited-p
(kill-buffer to-be-removed
))
1102 (goto-char point
))))
1103 (def-edebug-spec org-babel-map-src-blocks
(form body
))
1106 (defmacro org-babel-map-inline-src-blocks
(file &rest body
)
1107 "Evaluate BODY forms on each inline source block in FILE.
1108 If FILE is nil evaluate BODY forms on source blocks in current
1110 (declare (indent 1) (debug (form body
)))
1111 (org-with-gensyms (datum end point tempvar to-be-removed visitedp
)
1112 `(let* ((case-fold-search t
)
1114 (,visitedp
(or (null ,tempvar
)
1115 (get-file-buffer (expand-file-name ,tempvar
))))
1118 (save-window-excursion
1119 (when ,tempvar
(find-file ,tempvar
))
1120 (setq ,to-be-removed
(current-buffer))
1121 (goto-char (point-min))
1122 (while (re-search-forward "src_\\S-" nil t
)
1123 (let ((,datum
(save-match-data (org-element-context))))
1124 (when (eq (org-element-type ,datum
) 'inline-src-block
)
1125 (goto-char (match-beginning 0))
1126 (let ((,end
(copy-marker (org-element-property :end
,datum
))))
1129 (set-marker ,end nil
))))))
1130 (unless ,visitedp
(kill-buffer ,to-be-removed
))
1131 (goto-char ,point
))))
1134 (defmacro org-babel-map-call-lines
(file &rest body
)
1135 "Evaluate BODY forms on each call line in FILE.
1136 If FILE is nil evaluate BODY forms on source blocks in current
1138 (declare (indent 1) (debug (form body
)))
1139 (org-with-gensyms (datum end point tempvar to-be-removed visitedp
)
1140 `(let* ((case-fold-search t
)
1142 (,visitedp
(or (null ,tempvar
)
1143 (get-file-buffer (expand-file-name ,tempvar
))))
1146 (save-window-excursion
1147 (when ,tempvar
(find-file ,tempvar
))
1148 (setq ,to-be-removed
(current-buffer))
1149 (goto-char (point-min))
1150 (while (re-search-forward "call_\\S-\\|^[ \t]*#\\+CALL:" nil t
)
1151 (let ((,datum
(save-match-data (org-element-context))))
1152 (when (memq (org-element-type ,datum
)
1153 '(babel-call inline-babel-call
))
1154 (goto-char (match-beginning 0))
1155 (let ((,end
(copy-marker (org-element-property :end
,datum
))))
1158 (set-marker ,end nil
))))))
1159 (unless ,visitedp
(kill-buffer ,to-be-removed
))
1160 (goto-char ,point
))))
1163 (defmacro org-babel-map-executables
(file &rest body
)
1164 "Evaluate BODY forms on each active Babel code in FILE.
1165 If FILE is nil evaluate BODY forms on source blocks in current
1167 (declare (indent 1) (debug (form body
)))
1168 (org-with-gensyms (datum end point tempvar to-be-removed visitedp
)
1169 `(let* ((case-fold-search t
)
1171 (,visitedp
(or (null ,tempvar
)
1172 (get-file-buffer (expand-file-name ,tempvar
))))
1175 (save-window-excursion
1176 (when ,tempvar
(find-file ,tempvar
))
1177 (setq ,to-be-removed
(current-buffer))
1178 (goto-char (point-min))
1179 (while (re-search-forward
1180 "\\(call\\|src\\)_\\|^[ \t]*#\\+\\(BEGIN_SRC\\|CALL:\\)" nil t
)
1181 (let ((,datum
(save-match-data (org-element-context))))
1182 (when (memq (org-element-type ,datum
)
1183 '(babel-call inline-babel-call inline-src-block
1185 (goto-char (match-beginning 0))
1186 (let ((,end
(copy-marker (org-element-property :end
,datum
))))
1189 (set-marker ,end nil
))))))
1190 (unless ,visitedp
(kill-buffer ,to-be-removed
))
1191 (goto-char ,point
))))
1194 (defun org-babel-execute-buffer (&optional arg
)
1195 "Execute source code blocks in a buffer.
1196 Call `org-babel-execute-src-block' on every source block in
1197 the current buffer."
1199 (org-babel-eval-wipe-error-buffer)
1200 (org-save-outline-visibility t
1201 (org-babel-map-executables nil
1202 (if (memq (org-element-type (org-element-context))
1203 '(babel-call inline-babel-call
))
1204 (org-babel-lob-execute-maybe)
1205 (org-babel-execute-src-block arg
)))))
1208 (defun org-babel-execute-subtree (&optional arg
)
1209 "Execute source code blocks in a subtree.
1210 Call `org-babel-execute-src-block' on every source block in
1211 the current subtree."
1215 (org-narrow-to-subtree)
1216 (org-babel-execute-buffer arg
)
1220 (defun org-babel-sha1-hash (&optional info
)
1221 "Generate an sha1 hash based on the value of info."
1223 (let ((print-level nil
)
1224 (info (or info
(org-babel-get-src-block-info))))
1226 (sort (copy-sequence (nth 2 info
))
1227 (lambda (a b
) (string< (car a
) (car b
)))))
1228 (let* ((rm (lambda (lst)
1229 (dolist (p '("replace" "silent" "none"
1230 "append" "prepend"))
1231 (setq lst
(remove p lst
)))
1234 (let ((v (if (and (listp (cdr arg
)) (null (cddr arg
)))
1235 (copy-sequence (cdr arg
))
1237 (when (and v
(not (and (sequencep v
)
1241 ((and (listp v
) ; lists are sorted
1242 (member (car arg
) '(:result-params
)))
1243 (sort (funcall rm v
) #'string
<))
1244 ((and (stringp v
) ; strings are sorted
1245 (member (car arg
) '(:results
:exports
)))
1246 (mapconcat #'identity
(sort (funcall rm
(split-string v
))
1251 (params (nth 2 info
))
1252 (body (if (org-babel-noweb-p params
:eval
)
1253 (org-babel-expand-noweb-references info
) (nth 1 info
)))
1254 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
1255 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
1258 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
1259 (org-babel-expand-body:generic
1260 body params
(and (fboundp assignments-cmd
)
1261 (funcall assignments-cmd params
))))))
1262 (let* ((it (format "%s-%s"
1265 (delq nil
(mapcar (lambda (arg)
1266 (let ((normalized (funcall norm arg
)))
1268 (format "%S" normalized
))))
1272 (when (called-interactively-p 'interactive
) (message hash
))
1275 (defun org-babel-current-result-hash (&optional info
)
1276 "Return the current in-buffer hash."
1277 (let ((result (org-babel-where-is-src-block-result nil info
)))
1279 (org-with-wide-buffer
1281 (looking-at org-babel-result-regexp
)
1282 (match-string-no-properties 1)))))
1284 (defun org-babel-set-current-result-hash (hash info
)
1285 "Set the current in-buffer hash to HASH."
1286 (org-with-wide-buffer
1287 (goto-char (org-babel-where-is-src-block-result nil info
))
1288 (looking-at org-babel-result-regexp
)
1289 (goto-char (match-beginning 1))
1290 (mapc #'delete-overlay
(overlays-at (point)))
1291 (forward-char org-babel-hash-show
)
1292 (mapc #'delete-overlay
(overlays-at (point)))
1293 (replace-match hash nil nil nil
1)
1295 (org-babel-hide-hash)))
1297 (defun org-babel-hide-hash ()
1298 "Hide the hash in the current results line.
1299 Only the initial `org-babel-hash-show' characters of the hash
1300 will remain visible."
1301 (add-to-invisibility-spec '(org-babel-hide-hash . t
))
1303 (when (and (re-search-forward org-babel-result-regexp nil t
)
1305 (let* ((start (match-beginning 1))
1306 (hide-start (+ org-babel-hash-show start
))
1308 (hash (match-string 1))
1310 (setq ov1
(make-overlay start hide-start
))
1311 (setq ov2
(make-overlay hide-start end
))
1312 (overlay-put ov2
'invisible
'org-babel-hide-hash
)
1313 (overlay-put ov1
'babel-hash hash
)))))
1315 (defun org-babel-hide-all-hashes ()
1316 "Hide the hash in the current buffer.
1317 Only the initial `org-babel-hash-show' characters of each hash
1318 will remain visible. This function should be called as part of
1319 the `org-mode-hook'."
1321 (while (and (not org-babel-hash-show-time
)
1322 (re-search-forward org-babel-result-regexp nil t
))
1323 (goto-char (match-beginning 0))
1324 (org-babel-hide-hash)
1325 (goto-char (match-end 0)))))
1326 (add-hook 'org-mode-hook
'org-babel-hide-all-hashes
)
1328 (defun org-babel-hash-at-point (&optional point
)
1329 "Return the value of the hash at POINT.
1331 The hash is also added as the last element of the kill ring.
1332 This can be called with `\\[org-ctrl-c-ctrl-c]'."
1334 (let ((hash (car (delq nil
(mapcar
1335 (lambda (ol) (overlay-get ol
'babel-hash
))
1336 (overlays-at (or point
(point))))))))
1337 (when hash
(kill-new hash
) (message hash
))))
1339 (defun org-babel-result-hide-spec ()
1340 "Hide portions of results lines.
1341 Add `org-babel-hide-result' as an invisibility spec for hiding
1342 portions of results lines."
1343 (add-to-invisibility-spec '(org-babel-hide-result . t
)))
1344 (add-hook 'org-mode-hook
'org-babel-result-hide-spec
)
1346 (defvar org-babel-hide-result-overlays nil
1347 "Overlays hiding results.")
1349 (defun org-babel-result-hide-all ()
1350 "Fold all results in the current buffer."
1352 (org-babel-show-result-all)
1354 (while (re-search-forward org-babel-result-regexp nil t
)
1355 (save-excursion (goto-char (match-beginning 0))
1356 (org-babel-hide-result-toggle-maybe)))))
1358 (defun org-babel-show-result-all ()
1359 "Unfold all results in the current buffer."
1360 (mapc 'delete-overlay org-babel-hide-result-overlays
)
1361 (setq org-babel-hide-result-overlays nil
))
1364 (defun org-babel-hide-result-toggle-maybe ()
1365 "Toggle visibility of result at point."
1367 (let ((case-fold-search t
))
1369 (beginning-of-line 1)
1370 (looking-at org-babel-result-regexp
))
1371 (progn (org-babel-hide-result-toggle)
1372 t
) ;; to signal that we took action
1373 nil
))) ;; to signal that we did not
1375 (defun org-babel-hide-result-toggle (&optional force
)
1376 "Toggle the visibility of the current result."
1380 (if (re-search-forward org-babel-result-regexp nil t
)
1381 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
1383 (while (looking-at org-babel-multi-line-header-regexp
)
1385 (goto-char (- (org-babel-result-end) 1)) (point)))
1387 (if (memq t
(mapcar (lambda (overlay)
1388 (eq (overlay-get overlay
'invisible
)
1389 'org-babel-hide-result
))
1390 (overlays-at start
)))
1391 (when (or (not force
) (eq force
'off
))
1393 (when (member ov org-babel-hide-result-overlays
)
1394 (setq org-babel-hide-result-overlays
1395 (delq ov org-babel-hide-result-overlays
)))
1396 (when (eq (overlay-get ov
'invisible
)
1397 'org-babel-hide-result
)
1398 (delete-overlay ov
)))
1399 (overlays-at start
)))
1400 (setq ov
(make-overlay start end
))
1401 (overlay-put ov
'invisible
'org-babel-hide-result
)
1402 ;; make the block accessible to isearch
1404 ov
'isearch-open-invisible
1406 (when (member ov org-babel-hide-result-overlays
)
1407 (setq org-babel-hide-result-overlays
1408 (delq ov org-babel-hide-result-overlays
)))
1409 (when (eq (overlay-get ov
'invisible
)
1410 'org-babel-hide-result
)
1411 (delete-overlay ov
))))
1412 (push ov org-babel-hide-result-overlays
)))
1413 (error "Not looking at a result line"))))
1415 ;; org-tab-after-check-for-cycling-hook
1416 (add-hook 'org-tab-first-hook
'org-babel-hide-result-toggle-maybe
)
1417 ;; Remove overlays when changing major mode
1418 (add-hook 'org-mode-hook
1419 (lambda () (add-hook 'change-major-mode-hook
1420 'org-babel-show-result-all
'append
'local
)))
1422 (defvar org-file-properties
)
1423 (defun org-babel-params-from-properties (&optional lang
)
1424 "Retrieve parameters specified as properties.
1425 Return a list of association lists of source block params
1426 specified in the properties of the current outline entry."
1429 ;; header arguments specified with the header-args property at
1431 (org-babel-parse-header-arguments
1432 (org-entry-get org-babel-current-src-block-location
1435 (and lang
; language-specific header arguments at point of call
1436 (org-babel-parse-header-arguments
1437 (org-entry-get org-babel-current-src-block-location
1438 (concat "header-args:" lang
)
1441 (defun org-babel-balanced-split (string alts
)
1442 "Split STRING on instances of ALTS.
1443 ALTS is a character, or cons of two character options where each
1444 option may be either the numeric code of a single character or
1445 a list of character alternatives. For example, to split on
1446 balanced instances of \"[ \t]:\", set ALTS to ((32 9) . 58)."
1449 (goto-char (point-min))
1450 (let ((splitp (lambda (past next
)
1451 ;; Non-nil when there should be a split after NEXT
1452 ;; character. PAST is the character before NEXT.
1454 (`(,(and first
(pred consp
)) .
,(and second
(pred consp
)))
1455 (and (memq past first
) (memq next second
)))
1456 (`(,first .
,(and second
(pred consp
)))
1457 (and (eq past first
) (memq next second
)))
1458 (`(,(and first
(pred consp
)) .
,second
)
1459 (and (memq past first
) (eq next second
)))
1460 (`(,first .
,second
)
1461 (and (eq past first
) (eq next second
)))
1462 ((pred (eq next
)) t
)
1468 ((funcall splitp
(char-before) (char-after))
1469 ;; There is a split after point. If ALTS is two-folds,
1470 ;; remove last parsed character as it belongs to ALTS.
1471 (when (consp alts
) (pop partial
))
1472 ;; Include elements parsed so far in RESULTS and flush
1475 (push (apply #'string
(nreverse partial
)) result
)
1478 ((memq (char-after) '(?\
( ?\
[))
1479 ;; Include everything between balanced brackets.
1480 (let* ((origin (point))
1481 (after (char-after))
1482 (openings (list after
)))
1484 (while (and openings
(re-search-forward "[]()]" nil t
))
1485 (pcase (char-before)
1486 ((and match
(or ?\
[ ?\
()) (push match openings
))
1487 (?\
] (when (eq ?\
[ (car openings
)) (pop openings
)))
1488 (_ (when (eq ?\
( (car openings
)) (pop openings
)))))
1491 (nconc (nreverse (string-to-list
1492 (buffer-substring origin
(point))))
1494 ;; Un-balanced bracket. Backtrack.
1495 (push after partial
)
1496 (goto-char (1+ origin
)))))
1497 ((and (eq ?
\" (char-after)) (not (eq ?
\\ (char-before))))
1498 ;; Include everything from current double quote to next
1499 ;; non-escaped double quote.
1500 (let ((origin (point)))
1501 (if (re-search-forward "[^\\]\"" nil t
)
1503 (nconc (nreverse (string-to-list
1504 (buffer-substring origin
(point))))
1506 ;; No closing double quote. Backtrack.
1509 (t (push (char-after) partial
)
1511 ;; Add pending parsing and return result.
1512 (when partial
(push (apply #'string
(nreverse partial
)) result
))
1513 (nreverse result
))))
1515 (defun org-babel-join-splits-near-ch (ch list
)
1516 "Join splits where \"=\" is on either end of the split."
1517 (let ((last= (lambda (str) (= ch
(aref str
(1- (length str
))))))
1518 (first= (lambda (str) (= ch
(aref str
0)))))
1520 (cl-reduce (lambda (acc el
)
1521 (let ((head (car acc
)))
1522 (if (and head
(or (funcall last
= head
) (funcall first
= el
)))
1523 (cons (concat head el
) (cdr acc
))
1525 list
:initial-value nil
))))
1527 (defun org-babel-parse-header-arguments (arg-string)
1528 "Parse a string of header arguments returning an alist."
1529 (when (> (length arg-string
) 0)
1530 (org-babel-parse-multiple-vars
1535 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1537 (cons (intern (match-string 1 arg
))
1538 (org-babel-read (org-babel-chomp (match-string 2 arg
))))
1539 (cons (intern (org-babel-chomp arg
)) nil
)))
1540 (let ((raw (org-babel-balanced-split arg-string
'((32 9) .
58))))
1541 (cons (car raw
) (mapcar (lambda (r) (concat ":" r
)) (cdr raw
)))))))))
1543 (defun org-babel-parse-multiple-vars (header-arguments)
1544 "Expand multiple variable assignments behind a single :var keyword.
1546 This allows expression of multiple variables with one :var as
1549 #+PROPERTY: var foo=1, bar=2"
1551 (mapc (lambda (pair)
1552 (if (eq (car pair
) :var
)
1553 (mapcar (lambda (v) (push (cons :var
(org-trim v
)) results
))
1554 (org-babel-join-splits-near-ch
1555 61 (org-babel-balanced-split (cdr pair
) 32)))
1556 (push pair results
)))
1558 (nreverse results
)))
1560 (defun org-babel-process-params (params)
1561 "Expand variables in PARAMS and add summary parameters."
1562 (let* ((processed-vars (mapcar (lambda (el)
1565 (org-babel-ref-parse el
)))
1566 (org-babel--get-vars params
)))
1567 (vars-and-names (if (and (assq :colname-names params
)
1568 (assq :rowname-names params
))
1569 (list processed-vars
)
1570 (org-babel-disassemble-tables
1572 (cdr (assq :hlines params
))
1573 (cdr (assq :colnames params
))
1574 (cdr (assq :rownames params
)))))
1575 (raw-result (or (cdr (assq :results params
)) ""))
1576 (result-params (delete-dups
1578 (split-string (if (stringp raw-result
)
1580 (eval raw-result t
)))
1581 (cdr (assq :result-params params
))))))
1583 (mapcar (lambda (var) (cons :var var
)) (car vars-and-names
))
1585 (cons :colname-names
(or (cdr (assq :colname-names params
))
1586 (cadr vars-and-names
)))
1587 (cons :rowname-names
(or (cdr (assq :rowname-names params
))
1588 (cl-caddr vars-and-names
)))
1589 (cons :result-params result-params
)
1590 (cons :result-type
(cond ((member "output" result-params
) 'output
)
1591 ((member "value" result-params
) 'value
)
1594 (lambda (x) (memq (car x
) '(:colname-names
:rowname-names
:result-params
1595 :result-type
:var
)))
1598 ;; row and column names
1599 (defun org-babel-del-hlines (table)
1600 "Remove all `hline's from TABLE."
1601 (remq 'hline table
))
1603 (defun org-babel-get-colnames (table)
1604 "Return the column names of TABLE.
1605 Return a cons cell, the `car' of which contains the TABLE less
1606 colnames, and the `cdr' of which contains a list of the column
1608 (if (eq 'hline
(nth 1 table
))
1609 (cons (cddr table
) (car table
))
1610 (cons (cdr table
) (car table
))))
1612 (defun org-babel-get-rownames (table)
1613 "Return the row names of TABLE.
1614 Return a cons cell, the `car' of which contains the TABLE less
1615 rownames, and the `cdr' of which contains a list of the rownames.
1616 Note: this function removes any hlines in TABLE."
1617 (let* ((table (org-babel-del-hlines table
))
1618 (rownames (funcall (lambda ()
1624 (setq tp
(cdr tp
))))
1626 (cons table rownames
)))
1628 (defun org-babel-put-colnames (table colnames
)
1629 "Add COLNAMES to TABLE if they exist."
1630 (if colnames
(apply 'list colnames
'hline table
) table
))
1632 (defun org-babel-put-rownames (table rownames
)
1633 "Add ROWNAMES to TABLE if they exist."
1635 (mapcar (lambda (row)
1637 (cons (or (pop rownames
) "") row
)
1641 (defun org-babel-pick-name (names selector
)
1642 "Select one out of an alist of row or column names.
1643 SELECTOR can be either a list of names in which case those names
1644 will be returned directly, or an index into the list NAMES in
1645 which case the indexed names will be return."
1646 (if (listp selector
)
1649 (if (and selector
(symbolp selector
) (not (equal t selector
)))
1650 (cdr (assoc selector names
))
1651 (if (integerp selector
)
1652 (nth (- selector
1) names
)
1653 (cdr (car (last names
))))))))
1655 (defun org-babel-disassemble-tables (vars hlines colnames rownames
)
1656 "Parse tables for further processing.
1657 Process the variables in VARS according to the HLINES,
1658 ROWNAMES and COLNAMES header arguments. Return a list consisting
1659 of the vars, cnames and rnames."
1660 (let (cnames rnames
)
1664 (when (listp (cdr var
))
1665 (when (and (not (equal colnames
"no"))
1666 (or colnames
(and (eq (nth 1 (cdr var
)) 'hline
)
1667 (not (member 'hline
(cddr (cdr var
)))))))
1668 (let ((both (org-babel-get-colnames (cdr var
))))
1669 (setq cnames
(cons (cons (car var
) (cdr both
))
1671 (setq var
(cons (car var
) (car both
)))))
1672 (when (and rownames
(not (equal rownames
"no")))
1673 (let ((both (org-babel-get-rownames (cdr var
))))
1674 (setq rnames
(cons (cons (car var
) (cdr both
))
1676 (setq var
(cons (car var
) (car both
)))))
1677 (when (and hlines
(not (equal hlines
"yes")))
1678 (setq var
(cons (car var
) (org-babel-del-hlines (cdr var
))))))
1681 (reverse cnames
) (reverse rnames
))))
1683 (defun org-babel-reassemble-table (table colnames rownames
)
1684 "Add column and row names to a table.
1685 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1686 to the table for reinsertion to org-mode."
1688 (let ((table (if (and rownames
(= (length table
) (length rownames
)))
1689 (org-babel-put-rownames table rownames
) table
)))
1690 (if (and colnames
(listp (car table
)) (= (length (car table
))
1692 (org-babel-put-colnames table colnames
) table
))
1695 (defun org-babel-where-is-src-block-head (&optional src-block
)
1696 "Find where the current source block begins.
1698 If optional argument SRC-BLOCK is `src-block' type element, find
1699 its current beginning instead.
1701 Return the point at the beginning of the current source block.
1702 Specifically at the beginning of the #+BEGIN_SRC line. Also set
1703 match-data relatively to `org-babel-src-block-regexp', which see.
1704 If the point is not on a source block then return nil."
1705 (let ((element (or src-block
(org-element-at-point))))
1706 (when (eq (org-element-type element
) 'src-block
)
1707 (let ((end (org-element-property :end element
)))
1708 (org-with-wide-buffer
1709 ;; Ensure point is not on a blank line after the block.
1711 (skip-chars-forward " \r\t\n" end
)
1712 (when (< (point) end
)
1713 (prog1 (goto-char (org-element-property :post-affiliated element
))
1714 (looking-at org-babel-src-block-regexp
))))))))
1717 (defun org-babel-goto-src-block-head ()
1718 "Go to the beginning of the current code block."
1720 (let ((head (org-babel-where-is-src-block-head)))
1721 (if head
(goto-char head
) (error "Not currently in a code block"))))
1724 (defun org-babel-goto-named-src-block (name)
1725 "Go to a named source-code block."
1727 (let ((completion-ignore-case t
)
1728 (case-fold-search t
)
1729 (all-block-names (org-babel-src-block-names)))
1730 (list (completing-read
1731 "source-block name: " all-block-names nil t
1732 (let* ((context (org-element-context))
1733 (type (org-element-type context
))
1735 (and (memq type
'(inline-src-block src-block
))
1736 (org-in-regexp (org-babel-noweb-wrap)))))
1740 (+ (car noweb-ref
) (length org-babel-noweb-wrap-start
))
1741 (- (cdr noweb-ref
) (length org-babel-noweb-wrap-end
))))
1742 ((memq type
'(babel-call inline-babel-call
)) ;#+CALL:
1743 (org-element-property :call context
))
1744 ((car (org-element-property :results context
))) ;#+RESULTS:
1745 ((let ((symbol (thing-at-point 'symbol
))) ;Symbol.
1747 (member-ignore-case symbol all-block-names
)
1750 (let ((point (org-babel-find-named-block name
)))
1752 ;; Taken from `org-open-at-point'.
1753 (progn (org-mark-ring-push) (goto-char point
) (org-show-context))
1754 (message "source-code block `%s' not found in this buffer" name
))))
1756 (defun org-babel-find-named-block (name)
1757 "Find a named source-code block.
1758 Return the location of the source block identified by source
1759 NAME, or nil if no such block exists. Set match data according
1760 to `org-babel-named-src-block-regexp'."
1762 (goto-char (point-min))
1764 (org-next-block 1 nil
(org-babel-named-src-block-regexp-for-name name
)))))
1766 (defun org-babel-src-block-names (&optional file
)
1767 "Returns the names of source blocks in FILE or the current buffer."
1768 (when file
(find-file file
))
1770 (goto-char (point-min))
1771 (let ((re (org-babel-named-src-block-regexp-for-name))
1773 (while (ignore-errors (org-next-block 1 nil re
))
1774 (push (match-string-no-properties 9) names
))
1778 (defun org-babel-goto-named-result (name)
1779 "Go to a named result."
1781 (let ((completion-ignore-case t
))
1782 (list (completing-read "Source-block name: "
1783 (org-babel-result-names) nil t
))))
1784 (let ((point (org-babel-find-named-result name
)))
1786 ;; taken from `org-open-at-point'
1787 (progn (goto-char point
) (org-show-context))
1788 (message "result `%s' not found in this buffer" name
))))
1790 (defun org-babel-find-named-result (name)
1791 "Find a named result.
1792 Return the location of the result named NAME in the current
1793 buffer or nil if no such result exists."
1795 (goto-char (point-min))
1796 (let ((case-fold-search t
)
1797 (re (format "^[ \t]*#\\+%s.*?:[ \t]*%s[ \t]*$"
1798 org-babel-results-keyword
1799 (regexp-quote name
))))
1801 (while (re-search-forward re nil t
)
1802 (let ((element (org-element-at-point)))
1803 (when (or (eq (org-element-type element
) 'keyword
)
1805 (org-element-property :post-affiliated element
)))
1806 (throw :found
(line-beginning-position)))))))))
1808 (defun org-babel-result-names (&optional file
)
1809 "Returns the names of results in FILE or the current buffer."
1811 (when file
(find-file file
)) (goto-char (point-min))
1812 (let ((case-fold-search t
) names
)
1813 (while (re-search-forward org-babel-result-w-name-regexp nil t
)
1814 (setq names
(cons (match-string-no-properties 9) names
)))
1818 (defun org-babel-next-src-block (&optional arg
)
1819 "Jump to the next source block.
1820 With optional prefix argument ARG, jump forward ARG many source blocks."
1822 (org-next-block arg nil org-babel-src-block-regexp
))
1825 (defun org-babel-previous-src-block (&optional arg
)
1826 "Jump to the previous source block.
1827 With optional prefix argument ARG, jump backward ARG many source blocks."
1829 (org-previous-block arg org-babel-src-block-regexp
))
1831 (defvar org-babel-load-languages
)
1834 (defun org-babel-mark-block ()
1835 "Mark current src block."
1837 (let ((head (org-babel-where-is-src-block-head)))
1841 (looking-at org-babel-src-block-regexp
))
1842 (push-mark (match-end 5) nil t
)
1843 (goto-char (match-beginning 5)))))
1845 (defun org-babel-demarcate-block (&optional arg
)
1846 "Wrap or split the code in the region or on the point.
1847 When called from inside of a code block the current block is
1848 split. When called from outside of a code block a new code block
1849 is created. In both cases if the region is demarcated and if the
1850 region is not active then the point is demarcated."
1852 (let* ((info (org-babel-get-src-block-info 'light
))
1853 (start (org-babel-where-is-src-block-head))
1854 (block (and start
(match-string 0)))
1855 (headers (and start
(match-string 4)))
1856 (stars (concat (make-string (or (org-current-level) 1) ?
*) " "))
1857 (lower-case-p (and block
1858 (let (case-fold-search)
1859 (string-match-p "#\\+begin_src" block
)))))
1865 (let ((lang (nth 0 info
))
1866 (indent (make-string (org-get-indentation) ?\s
)))
1867 (when (string-match "^[[:space:]]*$"
1868 (buffer-substring (point-at-bol)
1870 (delete-region (point-at-bol) (point-at-eol)))
1872 (if (looking-at "^") "" "\n")
1873 indent
(funcall (if lower-case-p
'downcase
'upcase
) "#+end_src\n")
1874 (if arg stars indent
) "\n"
1875 indent
(funcall (if lower-case-p
'downcase
'upcase
) "#+begin_src ")
1877 (if (> (length headers
) 1)
1878 (concat " " headers
) headers
)
1879 (if (looking-at "[\n\r]")
1881 (concat "\n" (make-string (current-column) ?
)))))))
1882 (move-end-of-line 2))
1883 (sort (if (org-region-active-p) (list (mark) (point)) (list (point))) #'>))
1884 (let ((start (point))
1885 (lang (completing-read
1887 (mapcar #'symbol-name
1889 (append (mapcar #'car org-babel-load-languages
)
1890 (mapcar (lambda (el) (intern (car el
)))
1891 org-src-lang-modes
))))))
1892 (body (delete-and-extract-region
1893 (if (org-region-active-p) (mark) (point)) (point))))
1894 (insert (concat (if (looking-at "^") "" "\n")
1895 (if arg
(concat stars
"\n") "")
1896 (funcall (if lower-case-p
'downcase
'upcase
) "#+begin_src ")
1899 (if (or (= (length body
) 0)
1900 (string-suffix-p "\r" body
)
1901 (string-suffix-p "\n" body
)) "" "\n")
1902 (funcall (if lower-case-p
'downcase
'upcase
) "#+end_src\n")))
1903 (goto-char start
) (move-end-of-line 1)))))
1905 (defun org-babel--insert-results-keyword (name hash
)
1906 "Insert RESULTS keyword with NAME value at point.
1907 If NAME is nil, results are anonymous. HASH is a string used as
1908 the results hash, or nil. Leave point before the keyword."
1909 (save-excursion (insert "\n")) ;open line to indent.
1912 (insert (concat "#+" org-babel-results-keyword
1913 (cond ((not hash
) nil
)
1914 (org-babel-hash-show-time
1916 (format-time-string "<%F %T>")
1918 (t (format "[%s]" hash
)))
1920 (when name
(concat " " name
))
1922 ;; Make sure results are going to be followed by at least one blank
1923 ;; line so they do not get merged with the next element, e.g.,
1928 ;; : fixed-width area, unrelated to the above.
1929 (unless (looking-at "^[ \t]*$") (save-excursion (insert "\n")))
1930 (beginning-of-line 0)
1931 (when hash
(org-babel-hide-hash)))
1933 (defun org-babel--clear-results-maybe (hash)
1934 "Clear results when hash doesn't match HASH.
1936 When results hash does not match HASH, remove RESULTS keyword at
1937 point, along with related contents. Do nothing if HASH is nil.
1939 Return a non-nil value if results were cleared. In this case,
1940 leave point where new results should be inserted."
1942 (looking-at org-babel-result-regexp
)
1943 (unless (string= (match-string 1) hash
)
1944 (let* ((e (org-element-at-point))
1945 (post (copy-marker (org-element-property :post-affiliated e
))))
1949 (goto-char (org-element-property :end e
))
1950 (skip-chars-backward " \t\n")
1951 (line-beginning-position 2)))
1952 ;; Delete RESULT keyword. However, if RESULTS keyword is
1953 ;; orphaned, ignore this part. The deletion above already
1955 (unless (= (point) post
)
1956 (delete-region (line-beginning-position)
1957 (line-beginning-position 2)))
1959 (set-marker post nil
)
1962 (defun org-babel-where-is-src-block-result (&optional insert _info hash
)
1963 "Find where the current source block results begin.
1965 Return the point at the beginning of the result of the current
1966 source block, specifically at the beginning of the results line.
1968 If no result exists for this block return nil, unless optional
1969 argument INSERT is non-nil. In this case, create a results line
1970 following the source block and return the position at its
1971 beginning. In the case of inline code, remove the results part
1974 If optional argument HASH is a string, remove contents related to
1975 RESULTS keyword if its hash is different. Then update the latter
1977 (let ((context (org-element-context)))
1979 (org-with-wide-buffer
1980 (pcase (org-element-type context
)
1981 ((or `inline-babel-call
`inline-src-block
)
1982 ;; Results for inline objects are located right after them.
1983 ;; There is no RESULTS line to insert either.
1984 (let ((limit (org-element-property
1985 :contents-end
(org-element-property :parent context
))))
1986 (goto-char (org-element-property :end context
))
1987 (skip-chars-forward " \t\n" limit
)
1991 (let ((result (org-element-context)))
1992 (and (eq (org-element-type result
) 'macro
)
1993 (string= (org-element-property :key result
)
1995 (if (not insert
) (point)
1999 (goto-char (org-element-property :end result
))
2000 (skip-chars-backward " \t")
2003 ((or `babel-call
`src-block
)
2004 (let* ((name (org-element-property :name context
))
2005 (named-results (and name
(org-babel-find-named-result name
))))
2006 (goto-char (or named-results
(org-element-property :end context
)))
2008 ;; Existing results named after the current source.
2010 (when (org-babel--clear-results-maybe hash
)
2011 (org-babel--insert-results-keyword name hash
))
2012 (throw :found
(point)))
2013 ;; Named results expect but none to be found.
2015 ;; No possible anonymous results at the very end of
2016 ;; buffer or outside CONTEXT parent.
2018 (or (org-element-property
2019 :contents-end
(org-element-property :parent context
))
2021 ;; Check if next element is an anonymous result below
2022 ;; the current block.
2023 ((let* ((next (org-element-at-point))
2024 (end (save-excursion
2026 (org-element-property :post-affiliated next
))
2027 (line-end-position)))
2028 (empty-result-re (concat org-babel-result-regexp
"$"))
2029 (case-fold-search t
))
2030 (re-search-forward empty-result-re end t
))
2032 (when (org-babel--clear-results-maybe hash
)
2033 (org-babel--insert-results-keyword nil hash
))
2034 (throw :found
(point))))))
2035 ;; Ignore other elements.
2036 (_ (throw :found nil
))))
2037 ;; No result found. Insert a RESULTS keyword below element, if
2038 ;; appropriate. In this case, ensure there is an empty line
2039 ;; after the previous element.
2042 (goto-char (min (org-element-property :end context
) (point-max)))
2043 (skip-chars-backward " \t\n")
2045 (unless (bolp) (insert "\n"))
2047 (org-babel--insert-results-keyword
2048 (org-element-property :name context
) hash
)
2051 (defun org-babel-read-element (element)
2052 "Read ELEMENT into emacs-lisp.
2053 Return nil if ELEMENT cannot be read."
2054 (org-with-wide-buffer
2055 (goto-char (org-element-property :post-affiliated element
))
2056 (pcase (org-element-type element
)
2058 (let ((v (org-trim (org-element-property :value element
))))
2059 (or (org-babel--string-to-number v
) v
)))
2060 (`table
(org-babel-read-table))
2061 (`plain-list
(org-babel-read-list))
2063 (let ((v (org-element-property :value element
)))
2064 (if (or org-src-preserve-indentation
2065 (org-element-property :preserve-indent element
))
2067 (org-remove-indentation v
))))
2069 (org-remove-indentation (org-element-property :value element
)))
2071 ;; Treat paragraphs containing a single link specially.
2072 (skip-chars-forward " \t")
2073 (if (and (looking-at org-bracket-link-regexp
)
2075 (goto-char (match-end 0))
2076 (skip-chars-forward " \r\t\n")
2077 (<= (org-element-property :end element
)
2079 (org-babel-read-link)
2080 (buffer-substring-no-properties
2081 (org-element-property :contents-begin element
)
2082 (org-element-property :contents-end element
))))
2083 ((or `center-block
`quote-block
`verse-block
`special-block
)
2084 (org-remove-indentation
2085 (buffer-substring-no-properties
2086 (org-element-property :contents-begin element
)
2087 (org-element-property :contents-end element
))))
2090 (defun org-babel-read-result ()
2091 "Read the result at point into emacs-lisp."
2092 (and (not (save-excursion
2094 (looking-at-p "[ \t]*$")))
2095 (org-babel-read-element (org-element-at-point))))
2097 (defun org-babel-read-table ()
2098 "Read the table at point into emacs-lisp."
2099 (mapcar (lambda (row)
2100 (if (and (symbolp row
) (equal row
'hline
)) row
2101 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
)) row
)))
2102 (org-table-to-lisp)))
2104 (defun org-babel-read-list ()
2105 "Read the list at point into emacs-lisp."
2106 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
))
2107 (cdr (org-list-to-lisp))))
2109 (defvar org-link-types-re
)
2110 (defun org-babel-read-link ()
2111 "Read the link at point into emacs-lisp.
2112 If the path of the link is a file path it is expanded using
2113 `expand-file-name'."
2114 (let* ((case-fold-search t
)
2115 (raw (and (looking-at org-bracket-link-regexp
)
2116 (org-no-properties (match-string 1))))
2117 (type (and (string-match org-link-types-re raw
)
2118 (match-string 1 raw
))))
2120 ((not type
) (expand-file-name raw
))
2121 ((string= type
"file")
2122 (and (string-match "file\\(.*\\):\\(.+\\)" raw
)
2123 (expand-file-name (match-string 2 raw
))))
2126 (defun org-babel-format-result (result &optional sep
)
2127 "Format RESULT for writing to file."
2128 (let ((echo-res (lambda (r) (if (stringp r
) r
(format "%S" r
)))))
2132 result
(list :sep
(or sep
"\t") :fmt echo-res
))
2134 (funcall echo-res result
))))
2136 (defun org-babel-insert-result (result &optional result-params info hash lang
)
2137 "Insert RESULT into the current buffer.
2139 By default RESULT is inserted after the end of the current source
2140 block. The RESULT of an inline source block usually will be
2141 wrapped inside a `results' macro and placed on the same line as
2142 the inline source block. The macro is stripped upon export.
2143 Multiline and non-scalar RESULTS from inline source blocks are
2144 not allowed. With optional argument RESULT-PARAMS controls
2145 insertion of results in the Org mode file. RESULT-PARAMS can
2146 take the following values:
2148 replace - (default option) insert results after the source block
2149 or inline source block replacing any previously
2152 silent -- no results are inserted into the Org buffer but
2153 the results are echoed to the minibuffer and are
2154 ingested by Emacs (a potentially time consuming
2157 file ---- the results are interpreted as a file path, and are
2158 inserted into the buffer using the Org file syntax.
2160 list ---- the results are interpreted as an Org list.
2162 raw ----- results are added directly to the Org file. This is
2163 a good option if you code block will output Org
2166 drawer -- results are added directly to the Org file as with
2167 \"raw\", but are wrapped in a RESULTS drawer or results
2168 macro, allowing them to later be replaced or removed
2171 org ----- results are added inside of a \"src_org{}\" or \"#+BEGIN_SRC
2172 org\" block depending on whether the current source block is
2173 inline or not. They are not comma-escaped when inserted,
2174 but Org syntax here will be discarded when exporting the
2177 html ---- results are added inside of a #+BEGIN_EXPORT HTML block
2178 or html export snippet depending on whether the current
2179 source block is inline or not. This is a good option
2180 if your code block will output html formatted text.
2182 latex --- results are added inside of a #+BEGIN_EXPORT LATEX
2183 block or latex export snippet depending on whether the
2184 current source block is inline or not. This is a good
2185 option if your code block will output latex formatted
2188 code ---- the results are extracted in the syntax of the source
2189 code of the language being evaluated and are added
2190 inside of a source block with the source-code language
2191 set appropriately. Also, source block inlining is
2192 preserved in this case. Note this relies on the
2193 optional LANG argument.
2195 list ---- the results are rendered as a list. This option not
2196 allowed for inline src blocks.
2198 table --- the results are rendered as a table. This option not
2199 allowed for inline src blocks.
2201 INFO may provide the values of these header arguments (in the
2202 `header-arguments-alist' see the docstring for
2203 `org-babel-get-src-block-info'):
2205 :file --- the name of the file to which output should be written.
2207 :wrap --- the effect is similar to `latex' in RESULT-PARAMS but
2208 using the argument supplied to specify the export block
2210 (cond ((stringp result
)
2211 (setq result
(org-no-properties result
))
2212 (when (member "file" result-params
)
2213 (setq result
(org-babel-result-to-file
2214 result
(when (assq :file-desc
(nth 2 info
))
2215 (or (cdr (assq :file-desc
(nth 2 info
)))
2218 (t (setq result
(format "%S" result
))))
2219 (if (and result-params
(member "silent" result-params
))
2220 (progn (message (replace-regexp-in-string "%" "%%" (format "%S" result
)))
2222 (let ((inline (let ((context (org-element-context)))
2223 (and (memq (org-element-type context
)
2224 '(inline-babel-call inline-src-block
))
2228 (or (and (member "table" result-params
) "`:results table'")
2229 (and (listp result
) "list result")
2230 (and (string-match-p "\n." result
) "multiline result")
2231 (and (member "list" result-params
) "`:results list'"))))
2233 (user-error "Inline error: %s cannot be used" warning
))))
2235 (let* ((visible-beg (point-min-marker))
2236 (visible-end (copy-marker (point-max) t
))
2237 (inline (let ((context (org-element-context)))
2238 (and (memq (org-element-type context
)
2239 '(inline-babel-call inline-src-block
))
2241 (existing-result (org-babel-where-is-src-block-result t nil hash
))
2242 (results-switches (cdr (assq :results_switches
(nth 2 info
))))
2243 ;; When results exist outside of the current visible
2244 ;; region of the buffer, be sure to widen buffer to
2246 (outside-scope (and existing-result
2248 (or (> visible-beg existing-result
)
2249 (<= visible-end existing-result
))))
2251 ;; Ensure non-inline results end in a newline.
2252 (when (and (org-string-nw-p result
)
2254 (not (string-equal (substring result -
1) "\n")))
2255 (setq result
(concat result
"\n")))
2258 (when outside-scope
(widen))
2259 (if existing-result
(goto-char existing-result
)
2260 (goto-char (org-element-property :end inline
))
2261 (skip-chars-backward " \t"))
2263 (setq indent
(org-get-indentation))
2268 ;; Make sure new results are separated from the
2269 ;; source code by one space.
2270 (unless existing-result
2272 (setq beg
(point))))
2273 ((member "replace" result-params
)
2274 (delete-region (point) (org-babel-result-end)))
2275 ((member "append" result-params
)
2276 (goto-char (org-babel-result-end)) (setq beg
(point-marker)))
2277 ((member "prepend" result-params
))) ; already there
2278 (setq results-switches
2279 (if results-switches
(concat " " results-switches
) ""))
2280 (let ((wrap (lambda (start finish
&optional no-escape no-newlines
2281 inline-start inline-finish
)
2283 (setq start inline-start
)
2284 (setq finish inline-finish
)
2285 (setq no-newlines t
))
2287 (insert (concat finish
(unless no-newlines
"\n")))
2289 (insert (concat start
(unless no-newlines
"\n")))
2291 (org-escape-code-in-region (min (point) end
) end
))
2293 (unless no-newlines
(goto-char (point-at-eol)))
2294 (setq end
(point-marker))))
2297 ;; Non-nil when result R can be turned into
2300 (null (cdr (last r
)))
2302 (lambda (e) (or (atom e
) (null (cdr (last e
)))))
2304 ;; insert results based on type
2306 ;; Do nothing for an empty result.
2308 ;; Insert a list if preferred.
2309 ((member "list" result-params
)
2312 (org-list-to-generic
2316 (list (if (stringp e
) e
(format "%S" e
))))
2317 (if (listp result
) result
2318 (split-string result
"\n" t
))))
2319 '(:splicep nil
:istart
"- " :iend
"\n")))
2321 ;; Try hard to print RESULT as a table. Give up if
2322 ;; it contains an improper list.
2323 ((funcall tabulablep result
)
2325 (insert (concat (orgtbl-to-orgtbl
2328 (or (eq e
'hline
) (listp e
)))
2335 (when (org-at-table-p) (org-table-align))
2336 (goto-char (org-table-end)))
2337 ;; Print verbatim a list that cannot be turned into
2339 ((listp result
) (insert (format "%s\n" result
)))
2340 ((member "file" result-params
)
2342 (setq result
(org-macro-escape-arguments result
)))
2344 ((and inline
(not (member "raw" result-params
)))
2345 (insert (org-macro-escape-arguments
2346 (org-babel-chomp result
"\n"))))
2347 (t (goto-char beg
) (insert result
)))
2348 (setq end
(point-marker))
2349 ;; possibly wrap result
2351 ((assq :wrap
(nth 2 info
))
2352 (let ((name (or (cdr (assq :wrap
(nth 2 info
))) "RESULTS")))
2353 (funcall wrap
(concat "#+BEGIN_" name
)
2354 (concat "#+END_" (car (org-split-string name
)))
2355 nil nil
(concat "{{{results(@@" name
":") "@@)}}}")))
2356 ((member "html" result-params
)
2357 (funcall wrap
"#+BEGIN_EXPORT html" "#+END_EXPORT" nil nil
2358 "{{{results(@@html:" "@@)}}}"))
2359 ((member "latex" result-params
)
2360 (funcall wrap
"#+BEGIN_EXPORT latex" "#+END_EXPORT" nil nil
2361 "{{{results(@@latex:" "@@)}}}"))
2362 ((member "org" result-params
)
2363 (goto-char beg
) (when (org-at-table-p) (org-cycle))
2364 (funcall wrap
"#+BEGIN_SRC org" "#+END_SRC" nil nil
2365 "{{{results(src_org{" "})}}}"))
2366 ((member "code" result-params
)
2367 (let ((lang (or lang
"none")))
2368 (funcall wrap
(format "#+BEGIN_SRC %s%s" lang results-switches
)
2370 (format "{{{results(src_%s[%s]{" lang results-switches
)
2372 ((member "raw" result-params
)
2373 (goto-char beg
) (when (org-at-table-p) (org-cycle)))
2374 ((or (member "drawer" result-params
)
2375 ;; Stay backward compatible with <7.9.2
2376 (member "wrap" result-params
))
2377 (goto-char beg
) (when (org-at-table-p) (org-cycle))
2378 (funcall wrap
":RESULTS:" ":END:" 'no-escape nil
2379 "{{{results(" ")}}}"))
2380 ((and inline
(member "file" result-params
))
2381 (funcall wrap nil nil nil nil
"{{{results(" ")}}}"))
2382 ((and (not (funcall tabulablep result
))
2383 (not (member "file" result-params
)))
2384 (let ((org-babel-inline-result-wrap
2385 ;; Hard code {{{results(...)}}} on top of customization.
2386 (format "{{{results(%s)}}}"
2387 org-babel-inline-result-wrap
)))
2388 (org-babel-examplify-region beg end results-switches inline
)
2389 (setq end
(point))))))
2390 ;; Possibly indent results in par with #+results line.
2391 (when (and (not inline
) (numberp indent
) (> indent
0)
2392 ;; In this case `table-align' does the work
2394 (not (and (listp result
)
2395 (member "append" result-params
))))
2396 (indent-rigidly beg end indent
))
2398 (if (member "value" result-params
)
2399 (message "Code block returned no value.")
2400 (message "Code block produced no output."))
2401 (message "Code block evaluation complete.")))
2402 (when outside-scope
(narrow-to-region visible-beg visible-end
))
2403 (set-marker visible-beg nil
)
2404 (set-marker visible-end nil
)))))))
2406 (defun org-babel-remove-result (&optional info keep-keyword
)
2407 "Remove the result of the current source block."
2409 (let ((location (org-babel-where-is-src-block-result nil info
)))
2412 (goto-char location
)
2413 (when (looking-at (concat org-babel-result-regexp
".*$"))
2415 (if keep-keyword
(1+ (match-end 0)) (1- (match-beginning 0)))
2416 (progn (forward-line 1) (org-babel-result-end))))))))
2418 (defun org-babel-remove-inline-result (&optional datum
)
2419 "Remove the result of the current inline-src-block or babel call.
2420 The result must be wrapped in a `results' macro to be removed.
2421 Leading white space is trimmed."
2423 (let* ((el (or datum
(org-element-context))))
2424 (when (memq (org-element-type el
) '(inline-src-block inline-babel-call
))
2425 (org-with-wide-buffer
2426 (goto-char (org-element-property :end el
))
2427 (skip-chars-backward " \t")
2428 (let ((result (save-excursion
2431 (org-element-property
2432 :contents-end
(org-element-property :parent el
)))
2433 (org-element-context))))
2434 (when (and (eq (org-element-type result
) 'macro
)
2435 (string= (org-element-property :key result
) "results"))
2436 (delete-region ; And leading whitespace.
2438 (progn (goto-char (org-element-property :end result
))
2439 (skip-chars-backward " \t\n")
2442 (defun org-babel-remove-result-one-or-many (x)
2443 "Remove the result of the current source block.
2444 If called with a prefix argument, remove all result blocks
2448 (org-babel-map-src-blocks nil
(org-babel-remove-result))
2449 (org-babel-remove-result)))
2451 (defun org-babel-result-end ()
2452 "Return the point at the end of the current set of results."
2455 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
2456 ((org-at-item-p) (let* ((struct (org-list-struct))
2457 (prvs (org-list-prevs-alist struct
)))
2458 (org-list-get-list-end (point-at-bol) struct prvs
)))
2459 ((let ((case-fold-search t
)) (looking-at "^\\([ \t]*\\):results:"))
2460 (progn (re-search-forward (concat "^" (match-string 1) ":END:"))
2461 (forward-char 1) (point)))
2463 (let ((case-fold-search t
))
2464 (if (looking-at (concat "[ \t]*#\\+begin_\\([^ \t\n\r]+\\)"))
2465 (progn (re-search-forward (concat "[ \t]*#\\+end_" (match-string 1))
2468 (while (looking-at "[ \t]*\\(: \\|:$\\|\\[\\[\\)")
2472 (defun org-babel-result-to-file (result &optional description
)
2473 "Convert RESULT into an `org-mode' link with optional DESCRIPTION.
2474 If the `default-directory' is different from the containing
2475 file's directory then expand relative links."
2476 (when (stringp result
)
2477 (format "[[file:%s]%s]"
2478 (if (and default-directory
2480 (not (string= (expand-file-name default-directory
)
2482 (file-name-directory buffer-file-name
)))))
2483 (expand-file-name result default-directory
)
2485 (if description
(concat "[" description
"]") ""))))
2487 (defun org-babel-examplify-region (beg end
&optional results-switches inline
)
2488 "Comment out region using the inline `==' or `: ' org example quote."
2492 (if org-babel-uppercase-example-markers
(upcase str
) str
))))
2496 (insert (format org-babel-inline-result-wrap
2497 (delete-and-extract-region beg end
))))
2498 (let ((size (count-lines beg end
)))
2500 (cond ((= size
0)) ; do nothing for an empty result
2501 ((< size org-babel-min-lines-for-block-output
)
2504 (beginning-of-line 1) (insert ": ") (forward-line 1)))
2507 (insert (if results-switches
2509 (funcall maybe-cap
"#+begin_example")
2511 (funcall maybe-cap
"#+begin_example\n")))
2513 (if (markerp end
) (goto-char end
) (forward-char (- end beg
)))
2514 (org-escape-code-in-region p
(point)))
2515 (insert (funcall maybe-cap
"#+end_example\n")))))))))
2517 (defun org-babel-update-block-body (new-body)
2518 "Update the body of the current code block to NEW-BODY."
2519 (let ((element (org-element-at-point)))
2520 (unless (eq (org-element-type element
) 'src-block
)
2521 (error "Not in a source block"))
2522 (goto-char (org-babel-where-is-src-block-head element
))
2523 (let* ((ind (org-get-indentation))
2524 (body-start (line-beginning-position 2))
2525 (body (org-element-normalize-string
2526 (if (or org-src-preserve-indentation
2527 (org-element-property :preserve-indent element
))
2530 (insert (org-remove-indentation new-body
))
2534 (+ ind org-edit-src-content-indentation
))
2535 (buffer-string))))))
2536 (delete-region body-start
2537 (org-with-wide-buffer
2538 (goto-char (org-element-property :end element
))
2539 (skip-chars-backward " \t\n")
2540 (line-beginning-position)))
2541 (goto-char body-start
)
2544 (defun org-babel-merge-params (&rest plists
)
2545 "Combine all parameter association lists in PLISTS.
2546 Later elements of PLISTS override the values of previous elements.
2547 This takes into account some special considerations for certain
2548 parameters when merging lists."
2549 (let* ((results-exclusive-groups
2550 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2551 (cdr (assq 'results org-babel-common-header-args-w-values
))))
2552 (exports-exclusive-groups
2553 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2554 (cdr (assq 'exports org-babel-common-header-args-w-values
))))
2556 (lambda (exclusive-groups &rest result-params
)
2557 ;; Maintain exclusivity of mutually exclusive parameters,
2558 ;; as defined in EXCLUSIVE-GROUPS while merging lists in
2561 (dolist (new-params result-params
(delete-dups output
))
2562 (dolist (new-param new-params
)
2563 (dolist (exclusive-group exclusive-groups
)
2564 (when (member new-param exclusive-group
)
2565 (setq output
(cl-remove-if
2566 (lambda (o) (member o exclusive-group
))
2568 (push new-param output
))))))
2569 (variable-index 0) ;Handle positional arguments.
2571 params
;Final parameters list.
2572 ;; Some keywords accept multiple values. We need to treat
2574 vars results exports
)
2575 (dolist (plist plists
)
2576 (dolist (pair plist
)
2580 ((listp value
) (car value
))
2581 ((string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*=" value
)
2582 (intern (match-string 1 value
)))
2587 (append (if (not (assoc name vars
)) vars
2588 (push name clearnames
)
2589 (cl-remove-if (lambda (p) (equal name
(car p
)))
2591 (list (cons name pair
)))))
2592 ((and vars
(nth variable-index vars
))
2593 ;; If no name is given and we already have named
2594 ;; variables then assign to named variables in order.
2595 (let ((name (car (nth variable-index vars
))))
2596 ;; Clear out colnames and rownames for replace vars.
2597 (push name clearnames
)
2598 (setf (cddr (nth variable-index vars
))
2599 (concat (symbol-name name
) "=" value
))
2600 (cl-incf variable-index
)))
2601 (t (error "Variable \"%s\" must be assigned a default value"
2603 (`(:results .
,value
)
2604 (setq results
(funcall merge
2605 results-exclusive-groups
2608 (if (stringp value
) value
(eval value t
))))))
2609 (`(,(or :file
:file-ext
) .
,value
)
2610 ;; `:file' and `:file-ext' are regular keywords but they
2611 ;; imply a "file" `:results' and a "results" `:exports'.
2614 (funcall merge results-exclusive-groups results
'("file")))
2615 (unless (or (member "both" exports
)
2616 (member "none" exports
)
2617 (member "code" exports
))
2620 exports-exclusive-groups exports
'("results"))))
2621 (push pair params
)))
2622 (`(:exports .
,value
)
2623 (setq exports
(funcall merge
2624 exports-exclusive-groups
2626 (split-string (or value
"")))))
2627 ;; Regular keywords: any value overwrites the previous one.
2628 (_ (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))))
2629 ;; Handle `:var' and clear out colnames and rownames for replaced
2631 (setq params
(nconc (mapcar (lambda (v) (cons :var
(cddr v
))) vars
)
2633 (dolist (name clearnames
)
2634 (dolist (param '(:colname-names
:rowname-names
))
2635 (when (assq param params
)
2636 (setf (cdr (assq param params
))
2637 (cl-remove-if (lambda (pair) (equal name
(car pair
)))
2638 (cdr (assq param params
))))
2640 (cl-remove-if (lambda (pair) (and (equal (car pair
) param
)
2643 ;; Handle other special keywords, which accept multiple values.
2644 (setq params
(nconc (list (cons :results
(mapconcat #'identity results
" "))
2645 (cons :exports
(mapconcat #'identity exports
" ")))
2647 ;; Return merged params.
2650 (defvar org-babel-use-quick-and-dirty-noweb-expansion nil
2651 "Set to true to use regular expressions to expand noweb references.
2652 This results in much faster noweb reference expansion but does
2653 not properly allow code blocks to inherit the \":noweb-ref\"
2654 header argument from buffer or subtree wide properties.")
2656 (defun org-babel-noweb-p (params context
)
2657 "Check if PARAMS require expansion in CONTEXT.
2658 CONTEXT may be one of :tangle, :export or :eval."
2659 (let ((allowed-values (cl-case context
2660 (:tangle
'("yes" "tangle" "no-export" "strip-export"))
2661 (:eval
'("yes" "no-export" "strip-export" "eval"))
2662 (:export
'("yes")))))
2663 (cl-some (lambda (v) (member v allowed-values
))
2664 (split-string (or (cdr (assq :noweb params
)) "")))))
2666 (defun org-babel-expand-noweb-references (&optional info parent-buffer
)
2667 "Expand Noweb references in the body of the current source code block.
2669 For example the following reference would be replaced with the
2670 body of the source-code block named `example-block'.
2674 Note that any text preceding the <<foo>> construct on a line will
2675 be interposed between the lines of the replacement text. So for
2676 example if <<foo>> is placed behind a comment, then the entire
2677 replacement text will also be commented.
2679 This function must be called from inside of the buffer containing
2680 the source-code block which holds BODY.
2682 In addition the following syntax can be used to insert the
2683 results of evaluating the source-code block named `example-block'.
2687 Any optional arguments can be passed to example-block by placing
2688 the arguments inside the parenthesis following the convention
2689 defined by `org-babel-lob'. For example
2691 <<example-block(a=9)>>
2693 would set the value of argument \"a\" equal to \"9\". Note that
2694 these arguments are not evaluated in the current source-code
2695 block but are passed literally to the \"example-block\"."
2696 (let* ((parent-buffer (or parent-buffer
(current-buffer)))
2697 (info (or info
(org-babel-get-src-block-info 'light
)))
2700 (ob-nww-start org-babel-noweb-wrap-start
)
2701 (ob-nww-end org-babel-noweb-wrap-end
)
2702 (comment (string= "noweb" (cdr (assq :comments
(nth 2 info
)))))
2703 (rx-prefix (concat "\\(" org-babel-src-name-regexp
"\\|"
2704 ":noweb-ref[ \t]+" "\\)"))
2706 (nb-add (lambda (text) (setq new-body
(concat new-body text
))))
2707 (c-wrap (lambda (text)
2709 (funcall (intern (concat lang
"-mode")))
2710 (comment-region (point) (progn (insert text
) (point)))
2711 (org-trim (buffer-string)))))
2712 index source-name evaluate prefix
)
2714 (setq-local org-babel-noweb-wrap-start ob-nww-start
)
2715 (setq-local org-babel-noweb-wrap-end ob-nww-end
)
2716 (insert body
) (goto-char (point-min))
2717 (setq index
(point))
2718 (while (and (re-search-forward (org-babel-noweb-wrap) nil t
))
2719 (save-match-data (setf source-name
(match-string 1)))
2720 (save-match-data (setq evaluate
(string-match "(.*)" source-name
)))
2723 (buffer-substring (match-beginning 0)
2725 (beginning-of-line 1) (point)))))
2726 ;; add interval to new-body (removing noweb reference)
2727 (goto-char (match-beginning 0))
2728 (funcall nb-add
(buffer-substring index
(point)))
2729 (goto-char (match-end 0))
2730 (setq index
(point))
2733 (with-current-buffer parent-buffer
2736 (mapconcat ;; Interpose PREFIX between every line.
2740 (let ((raw (org-babel-ref-resolve source-name
)))
2741 (if (stringp raw
) raw
(format "%S" raw
)))
2743 ;; Retrieve from the library of babel.
2744 (nth 2 (assoc (intern source-name
)
2745 org-babel-library-of-babel
))
2746 ;; Return the contents of headlines literally.
2748 (when (org-babel-ref-goto-headline-id source-name
)
2749 (org-babel-ref-headline-body)))
2750 ;; Find the expansion of reference in this buffer.
2751 (let ((rx (concat rx-prefix source-name
"[ \t\n]"))
2754 (goto-char (point-min))
2755 (if org-babel-use-quick-and-dirty-noweb-expansion
2756 (while (re-search-forward rx nil t
)
2757 (let* ((i (org-babel-get-src-block-info 'light
))
2758 (body (org-babel-expand-noweb-references i
))
2759 (sep (or (cdr (assq :noweb-sep
(nth 2 i
)))
2762 (let ((cs (org-babel-tangle-comment-links i
)))
2763 (concat (funcall c-wrap
(car cs
)) "\n"
2765 (funcall c-wrap
(cadr cs
))))
2767 (setq expansion
(cons sep
(cons full expansion
)))))
2768 (org-babel-map-src-blocks nil
2769 (let ((i (org-babel-get-src-block-info 'light
)))
2770 (when (equal (or (cdr (assq :noweb-ref
(nth 2 i
)))
2773 (let* ((body (org-babel-expand-noweb-references i
))
2774 (sep (or (cdr (assq :noweb-sep
(nth 2 i
)))
2777 (let ((cs (org-babel-tangle-comment-links i
)))
2778 (concat (funcall c-wrap
(car cs
)) "\n"
2780 (funcall c-wrap
(cadr cs
))))
2783 (cons sep
(cons full expansion
)))))))))
2785 (mapconcat #'identity
(nreverse (cdr expansion
)) "")))
2786 ;; Possibly raise an error if named block doesn't exist.
2787 (if (or org-babel-noweb-error-all-langs
2788 (member lang org-babel-noweb-error-langs
))
2790 (org-babel-noweb-wrap source-name
)
2791 "could not be resolved (see "
2792 "`org-babel-noweb-error-langs')"))
2794 "[\n\r]") (concat "\n" prefix
))))))
2795 (funcall nb-add
(buffer-substring index
(point-max))))
2798 (defun org-babel--script-escape-inner (str)
2799 (let (in-single in-double backslash out
)
2806 (setq backslash nil
)
2808 ((and in-single
(eq ch ?
'))
2809 ;; Escaped single quote inside single quoted string:
2810 ;; emit just a single quote, since we've changed the
2811 ;; outer quotes to double.
2814 ;; Escaped double quote
2816 ;; This should be interpreted as backslash+quote,
2817 ;; not an escape. Emit a three backslashes
2818 ;; followed by a quote (because one layer of
2819 ;; quoting will be stripped by `org-babel-read').
2820 (append (list ch ?
\\ ?
\\ ?
\\) out
)
2821 ;; Otherwise we are in a double-quoted string. Emit
2822 ;; a single escaped quote
2823 (append (list ch ?
\\) out
)))
2825 ;; Escaped backslash: emit a single escaped backslash
2826 (append (list ?
\\ ?
\\) out
))
2827 ;; Other: emit a quoted backslash followed by whatever
2828 ;; the character was (because one layer of quoting will
2829 ;; be stripped by `org-babel-read').
2830 (t (append (list ch ?
\\ ?
\\) out
))))
2832 (?\
[ (if (or in-double in-single
)
2835 (?\
] (if (or in-double in-single
)
2838 (?\
{ (if (or in-double in-single
)
2841 (?\
} (if (or in-double in-single
)
2844 (?
, (if (or in-double in-single
)
2845 (cons ?
, out
) (cons ?\s out
)))
2848 (setq in-single
(not in-single
)) (cons ?
\" out
)))
2850 (append (list ?
\" ?
\\) out
)
2851 (setq in-double
(not in-double
)) (cons ?
\" out
)))
2852 (?
\\ (unless (or in-single in-double
)
2853 (error "Can't handle backslash outside string in `org-babel-script-escape'"))
2856 (t (cons ch out
))))))
2857 (string-to-list str
))
2858 (when (or in-single in-double
)
2859 (error "Unterminated string in `org-babel-script-escape'"))
2860 (apply #'string
(reverse out
))))
2862 (defun org-babel-script-escape (str &optional force
)
2863 "Safely convert tables into elisp lists."
2864 (unless (stringp str
)
2865 (error "`org-babel-script-escape' expects a string"))
2868 ((and (> (length str
) 2)
2869 (or (and (string-equal "[" (substring str
0 1))
2870 (string-equal "]" (substring str -
1)))
2871 (and (string-equal "{" (substring str
0 1))
2872 (string-equal "}" (substring str -
1)))
2873 (and (string-equal "(" (substring str
0 1))
2874 (string-equal ")" (substring str -
1)))))
2876 (concat "'" (org-babel--script-escape-inner str
)))
2878 (and (> (length str
) 2)
2879 (or (and (string-equal "'" (substring str
0 1))
2880 (string-equal "'" (substring str -
1)))
2881 ;; We need to pass double-quoted strings
2882 ;; through the backslash-twiddling bits, even
2883 ;; though we don't need to change their
2885 (and (string-equal "\"" (substring str
0 1))
2886 (string-equal "\"" (substring str -
1))))))
2887 (org-babel--script-escape-inner str
))
2889 (condition-case nil
(org-babel-read escaped
) (error escaped
))))
2891 (defun org-babel-read (cell &optional inhibit-lisp-eval
)
2892 "Convert the string value of CELL to a number if appropriate.
2893 Otherwise if CELL looks like lisp (meaning it starts with a
2894 \"(\", \"\\='\", \"\\=`\" or a \"[\") then read and evaluate it as
2895 lisp, otherwise return it unmodified as a string. Optional
2896 argument INHIBIT-LISP-EVAL inhibits lisp evaluation for
2897 situations in which is it not appropriate."
2898 (cond ((not (org-string-nw-p cell
)) cell
)
2899 ((org-babel--string-to-number cell
))
2900 ((and (not inhibit-lisp-eval
)
2901 (or (memq (string-to-char cell
) '(?\
( ?
' ?
` ?\
[))
2902 (string= cell
"*this*")))
2903 (eval (read cell
) t
))
2904 ((eq (string-to-char cell
) ?
\") (read cell
))
2905 (t (org-no-properties cell
))))
2907 (defun org-babel--string-to-number (string)
2908 "If STRING represents a number return its value.
2909 Otherwise return nil."
2910 (and (string-match-p "\\`-?[0-9]*\\.?[0-9]*\\'" string
)
2911 (string-to-number string
)))
2913 (defun org-babel-import-elisp-from-file (file-name &optional separator
)
2914 "Read the results located at FILE-NAME into an elisp table.
2915 If the table is trivial, then return it as a scalar."
2917 (save-window-excursion
2921 (org-table-import file-name separator
)
2922 (delete-file file-name
)
2923 (setq result
(mapcar (lambda (row)
2924 (mapcar #'org-babel-string-read row
))
2925 (org-table-to-lisp))))
2926 (error (message "Error reading results: %s" err
) nil
)))
2927 (if (null (cdr result
)) ;; if result is trivial vector, then scalarize it
2928 (if (consp (car result
))
2929 (if (null (cdr (car result
)))
2935 (defun org-babel-string-read (cell)
2936 "Strip nested \"s from around strings."
2937 (org-babel-read (or (and (stringp cell
)
2938 (string-match "\\\"\\(.+\\)\\\"" cell
)
2939 (match-string 1 cell
))
2942 (defun org-babel-chomp (string &optional regexp
)
2943 "Strip a trailing space or carriage return from STRING.
2944 The default regexp used is \"[ \\f\\t\\n\\r\\v]\" but another one
2945 can be specified as the REGEXP argument."
2946 (let ((regexp (or regexp
"[ \f\t\n\r\v]")))
2947 (while (and (> (length string
) 0)
2948 (string-match regexp
(substring string -
1)))
2949 (setq string
(substring string
0 -
1)))
2952 (defun org-babel-process-file-name (name &optional no-quote-p
)
2953 "Prepare NAME to be used in an external process.
2954 If NAME specifies a remote location, the remote portion of the
2955 name is removed, since in that case the process will be executing
2956 remotely. The file name is then processed by `expand-file-name'.
2957 Unless second argument NO-QUOTE-P is non-nil, the file name is
2958 additionally processed by `shell-quote-argument'"
2959 (let ((f (org-babel-local-file-name (expand-file-name name
))))
2960 (if no-quote-p f
(shell-quote-argument f
))))
2962 (defvar org-babel-temporary-directory
)
2963 (unless (or noninteractive
(boundp 'org-babel-temporary-directory
))
2964 (defvar org-babel-temporary-directory
2965 (or (and (boundp 'org-babel-temporary-directory
)
2966 (file-exists-p org-babel-temporary-directory
)
2967 org-babel-temporary-directory
)
2968 (make-temp-file "babel-" t
))
2969 "Directory to hold temporary files created to execute code blocks.
2970 Used by `org-babel-temp-file'. This directory will be removed on
2973 (defcustom org-babel-remote-temporary-directory
"/tmp/"
2974 "Directory to hold temporary files on remote hosts."
2978 (defmacro org-babel-result-cond
(result-params scalar-form
&rest table-forms
)
2979 "Call the code to parse raw string results according to RESULT-PARAMS."
2981 (debug (form form
&rest form
)))
2982 (org-with-gensyms (params)
2983 `(let ((,params
,result-params
))
2984 (unless (member "none" ,params
)
2985 (if (or (member "scalar" ,params
)
2986 (member "verbatim" ,params
)
2987 (member "html" ,params
)
2988 (member "code" ,params
)
2989 (member "pp" ,params
)
2990 (member "file" ,params
)
2991 (and (or (member "output" ,params
)
2992 (member "raw" ,params
)
2993 (member "org" ,params
)
2994 (member "drawer" ,params
))
2995 (not (member "table" ,params
))))
2998 (def-edebug-spec org-babel-result-cond
(form form body
))
3000 (defun org-babel-temp-file (prefix &optional suffix
)
3001 "Create a temporary file in the `org-babel-temporary-directory'.
3002 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
3003 value of `temporary-file-directory' temporarily set to the value
3004 of `org-babel-temporary-directory'."
3005 (if (file-remote-p default-directory
)
3007 (concat (file-remote-p default-directory
)
3009 prefix org-babel-remote-temporary-directory
))))
3010 (make-temp-file prefix nil suffix
))
3011 (let ((temporary-file-directory
3012 (or (and (boundp 'org-babel-temporary-directory
)
3013 (file-exists-p org-babel-temporary-directory
)
3014 org-babel-temporary-directory
)
3015 temporary-file-directory
)))
3016 (make-temp-file prefix nil suffix
))))
3018 (defun org-babel-remove-temporary-directory ()
3019 "Remove `org-babel-temporary-directory' on Emacs shutdown."
3020 (when (and (boundp 'org-babel-temporary-directory
)
3021 (file-exists-p org-babel-temporary-directory
))
3022 ;; taken from `delete-directory' in files.el
3025 (mapc (lambda (file)
3026 ;; This test is equivalent to
3027 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
3028 ;; but more efficient
3029 (if (eq t
(car (file-attributes file
)))
3030 (delete-directory file
)
3031 (delete-file file
)))
3032 ;; We do not want to delete "." and "..".
3033 (directory-files org-babel-temporary-directory
'full
3034 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
3035 (delete-directory org-babel-temporary-directory
))
3037 (message "Failed to remove temporary Org-babel directory %s"
3038 (if (boundp 'org-babel-temporary-directory
)
3039 org-babel-temporary-directory
3040 "[directory not defined]"))))))
3042 (add-hook 'kill-emacs-hook
'org-babel-remove-temporary-directory
)
3044 (defun org-babel-one-header-arg-safe-p (pair safe-list
)
3045 "Determine if the PAIR is a safe babel header arg according to SAFE-LIST.
3047 For the format of SAFE-LIST, see `org-babel-safe-header-args'."
3049 (keywordp (car pair
))
3050 (stringp (cdr pair
))
3052 (memq (car pair
) safe-list
)
3053 (let ((entry (assq (car pair
) safe-list
)))
3056 (cond ((functionp (cdr entry
))
3057 (funcall (cdr entry
) (cdr pair
)))
3058 ((listp (cdr entry
))
3059 (member (cdr pair
) (cdr entry
)))
3062 (defun org-babel-generate-file-param (src-name params
)
3063 "Calculate the filename for source block results.
3065 The directory is calculated from the :output-dir property of the
3066 source block; if not specified, use the current directory.
3068 If the source block has a #+NAME and the :file parameter does not
3069 contain any period characters, then the :file parameter is
3070 treated as an extension, and the output file name is the
3071 concatenation of the directory (as calculated above), the block
3072 name, a period, and the parameter value as a file extension.
3073 Otherwise, the :file parameter is treated as a full file name,
3074 and the output file name is the directory (as calculated above)
3075 plus the parameter value."
3076 (let* ((file-cons (assq :file params
))
3077 (file-ext-cons (assq :file-ext params
))
3078 (file-ext (cdr-safe file-ext-cons
))
3079 (dir (cdr-safe (assq :output-dir params
)))
3081 ;; create the output-dir if it does not exist
3083 (make-directory dir t
))
3085 ;; :file given; add :output-dir if given
3087 (setcdr file-cons
(concat (file-name-as-directory dir
) (cdr file-cons
))))
3088 ;; :file not given; compute from name and :file-ext if possible
3089 (when (and src-name file-ext
)
3091 (setq fname
(concat (file-name-as-directory (or dir
""))
3092 src-name
"." file-ext
))
3093 (setq fname
(concat src-name
"." file-ext
)))
3094 (setq params
(cons (cons :file fname
) params
))))
3097 (defun org-babel-graphical-output-file (params)
3098 "File where a babel block should send graphical output, per PARAMS.
3099 Return nil if no graphical output is expected. Raise an error if
3100 the output file is ill-defined."
3101 (let ((file (cdr (assq :file params
))))
3102 (cond (file (and (member "graphics" (cdr (assq :result-params params
)))
3104 ((assq :file-ext params
)
3105 (user-error ":file-ext given but no :file generated; did you forget \
3107 (t (user-error "No :file header argument given; cannot create \
3108 graphical result")))))
3110 (defun org-babel-make-language-alias (new old
)
3111 "Make source blocks of type NEW aliases for those of type OLD.
3113 NEW and OLD should be strings. This function should be called
3114 after the babel API for OLD-type source blocks is fully defined.
3116 Callers of this function will probably want to add an entry to
3117 `org-src-lang-modes' as well."
3118 (dolist (fn '("execute" "expand-body" "prep-session"
3119 "variable-assignments" "load-session"))
3120 (let ((sym (intern-soft (concat "org-babel-" fn
":" old
))))
3121 (when (and sym
(fboundp sym
))
3122 (defalias (intern (concat "org-babel-" fn
":" new
)) sym
))))
3123 ;; Technically we don't need a `dolist' for just one variable, but
3124 ;; we keep it for symmetry/ease of future expansion.
3125 (dolist (var '("default-header-args"))
3126 (let ((sym (intern-soft (concat "org-babel-" var
":" old
))))
3127 (when (and sym
(boundp sym
))
3128 (defvaralias (intern (concat "org-babel-" var
":" new
)) sym
)))))
3130 (defun org-babel-strip-quotes (string)
3131 "Strip \\\"s from around a string, if applicable."
3132 (org-unbracket-string "\"" "\"" string
))
3137 ;; generated-autoload-file: "org-loaddefs.el"
3140 ;;; ob-core.el ends here