1 ;;; ob-core.el --- Working with Code Blocks -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2009-2016 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 (defun org-babel-noweb-wrap (&optional regexp
)
175 (concat org-babel-noweb-wrap-start
176 (or regexp
"\\([^ \t\n].+?[^ \t]\\|[^ \t\n]\\)")
177 org-babel-noweb-wrap-end
))
179 (defvar org-babel-src-name-regexp
180 "^[ \t]*#\\+name:[ \t]*"
181 "Regular expression used to match a source name line.")
183 (defvar org-babel-multi-line-header-regexp
184 "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
185 "Regular expression used to match multi-line header arguments.")
187 (defvar org-babel-src-block-regexp
189 ;; (1) indentation (2) lang
190 "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
192 "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
193 ;; (4) header arguments
196 "\\([^\000]*?\n\\)??[ \t]*#\\+end_src")
197 "Regexp used to identify code blocks.")
199 (defun org-babel--get-vars (params)
200 "Return the babel variable assignments in PARAMS.
202 PARAMS is a quasi-alist of header args, whcih may contain
203 multiple entries for the key `:var'. This function returns a
204 list of the cdr of all the `:var' entries."
206 (cl-remove-if-not (lambda (x) (eq (car x
) :var
)) params
)))
208 (defvar org-babel-exp-reference-buffer nil
209 "Buffer containing original contents of the exported buffer.
210 This is used by Babel to resolve references in source blocks.
211 Its value is dynamically bound during export.")
213 (defun org-babel-check-confirm-evaluate (info)
214 "Check whether INFO allows code block evaluation.
216 Returns nil if evaluation is disallowed, t if it is
217 unconditionally allowed, and the symbol `query' if the user
218 should be asked whether to allow evaluation."
219 (let* ((headers (nth 2 info
))
220 (eval (or (cdr (assq :eval headers
))
221 (when (assq :noeval headers
) "no")))
222 (eval-no (member eval
'("no" "never")))
223 (export org-babel-exp-reference-buffer
)
224 (eval-no-export (and export
(member eval
'("no-export" "never-export"))))
225 (noeval (or eval-no eval-no-export
))
226 (query (or (equal eval
"query")
227 (and export
(equal eval
"query-export"))
228 (if (functionp org-confirm-babel-evaluate
)
230 (goto-char (nth 5 info
))
231 (funcall org-confirm-babel-evaluate
232 ;; language, code block body
233 (nth 0 info
) (nth 1 info
)))
234 org-confirm-babel-evaluate
))))
240 (defun org-babel-check-evaluate (info)
241 "Check if code block INFO should be evaluated.
243 Do not query the user, but do display an informative message if
244 evaluation is blocked. Returns non-nil if evaluation is not blocked."
245 (let ((evalp (org-babel-check-confirm-evaluate info
)))
247 (message "Evaluation of this %s code-block%sis disabled."
249 (let ((name (nth 4 info
))) (if name
(format " (%s) " name
) ""))))
252 ;; Dynamically scoped for asynchronous export.
253 (defvar org-babel-confirm-evaluate-answer-no
)
255 (defun org-babel-confirm-evaluate (info)
256 "Confirm evaluation of the code block INFO.
258 This query can also be suppressed by setting the value of
259 `org-confirm-babel-evaluate' to nil, in which case all future
260 interactive code block evaluations will proceed without any
261 confirmation from the user.
263 Note disabling confirmation may result in accidental evaluation
264 of potentially harmful code.
266 The variable `org-babel-confirm-evaluate-answer-no' is used by
267 the async export process, which requires a non-interactive
268 environment, to override this check."
269 (let* ((evalp (org-babel-check-confirm-evaluate info
))
272 (name-string (if name
(format " (%s) " name
) " ")))
277 (and (not (bound-and-true-p
278 org-babel-confirm-evaluate-answer-no
))
280 (format "Evaluate this %s code block%son your system? "
283 (message "Evaluation of this %s code-block%sis aborted."
286 (x (error "Unexpected value `%s' from `org-babel-check-confirm-evaluate'" x
)))))
289 (defun org-babel-execute-safely-maybe ()
290 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
291 (org-babel-execute-maybe)))
293 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-execute-safely-maybe
)
296 (defun org-babel-execute-maybe ()
298 (or (org-babel-execute-src-block-maybe)
299 (org-babel-lob-execute-maybe)))
301 (defmacro org-babel-when-in-src-block
(&rest body
)
302 "Execute BODY if point is in a source block and return t.
304 Otherwise do nothing and return nil."
305 `(if (memq (org-element-type (org-element-context))
306 '(inline-src-block src-block
))
312 (defun org-babel-execute-src-block-maybe ()
313 "Conditionally execute a source block.
314 Detect if this is context for a Babel src-block and if so
315 then run `org-babel-execute-src-block'."
317 (org-babel-when-in-src-block
318 (org-babel-eval-wipe-error-buffer)
319 (org-babel-execute-src-block current-prefix-arg
)))
322 (defun org-babel-view-src-block-info ()
323 "Display information on the current source block.
324 This includes header arguments, language and name, and is largely
325 a window into the `org-babel-get-src-block-info' function."
327 (let ((info (org-babel-get-src-block-info 'light
))
328 (full (lambda (it) (> (length it
) 0)))
329 (printf (lambda (fmt &rest args
) (princ (apply #'format fmt args
)))))
331 (with-help-window (help-buffer)
332 (let ((name (nth 4 info
))
334 (switches (nth 3 info
))
335 (header-args (nth 2 info
)))
336 (when name
(funcall printf
"Name: %s\n" name
))
337 (when lang
(funcall printf
"Lang: %s\n" lang
))
338 (funcall printf
"Properties:\n")
339 (funcall printf
"\t:header-args \t%s\n" (org-entry-get (point) "header-args" t
))
340 (funcall printf
"\t:header-args:%s \t%s\n" lang
(org-entry-get (point) (concat "header-args:" lang
) t
))
342 (when (funcall full switches
) (funcall printf
"Switches: %s\n" switches
))
343 (funcall printf
"Header Arguments:\n")
344 (dolist (pair (sort header-args
345 (lambda (a b
) (string< (symbol-name (car a
))
346 (symbol-name (car b
))))))
347 (when (funcall full
(format "%s" (cdr pair
)))
348 (funcall printf
"\t%S%s\t%s\n"
350 (if (> (length (format "%S" (car pair
))) 7) "" "\t")
354 (defun org-babel-expand-src-block-maybe ()
355 "Conditionally expand a source block.
356 Detect if this is context for a org-babel src-block and if so
357 then run `org-babel-expand-src-block'."
359 (org-babel-when-in-src-block
360 (org-babel-expand-src-block current-prefix-arg
)))
363 (defun org-babel-load-in-session-maybe ()
364 "Conditionally load a source block in a session.
365 Detect if this is context for a org-babel src-block and if so
366 then run `org-babel-load-in-session'."
368 (org-babel-when-in-src-block
369 (org-babel-load-in-session current-prefix-arg
)))
371 (add-hook 'org-metaup-hook
'org-babel-load-in-session-maybe
)
374 (defun org-babel-pop-to-session-maybe ()
375 "Conditionally pop to a session.
376 Detect if this is context for a org-babel src-block and if so
377 then run `org-babel-switch-to-session'."
379 (org-babel-when-in-src-block
380 (org-babel-switch-to-session current-prefix-arg
)))
382 (add-hook 'org-metadown-hook
'org-babel-pop-to-session-maybe
)
384 (defconst org-babel-common-header-args-w-values
385 '((cache .
((no yes
)))
387 (colnames .
((nil no yes
)))
388 (comments .
((no link yes org both noweb
)))
390 (eval .
((yes no no-export strip-export never-export eval never
392 (exports .
((code results both none
)))
397 (hlines .
((no yes
)))
398 (mkdirp .
((yes no
)))
401 (noweb .
((yes no tangle no-export strip-export
)))
405 (padline .
((yes no
)))
408 (results .
((file list vector table scalar verbatim
)
409 (raw html latex org code pp drawer
)
410 (replace silent none append prepend
)
412 (rownames .
((no yes
)))
416 (tangle .
((tangle yes no
:any
)))
417 (tangle-mode .
((#o755
#o555
#o444
:any
)))
421 (defconst org-babel-header-arg-names
422 (mapcar #'car org-babel-common-header-args-w-values
)
423 "Common header arguments used by org-babel.
424 Note that individual languages may define their own language
425 specific header arguments as well.")
427 (defconst org-babel-safe-header-args
428 '(:cache
:colnames
:comments
:exports
:epilogue
:hlines
:noeval
429 :noweb
:noweb-ref
:noweb-sep
:padline
:prologue
:rownames
430 :sep
:session
:tangle
:wrap
431 (:eval .
("never" "query"))
432 (:results .
(lambda (str) (not (string-match "file" str
)))))
433 "A list of safe header arguments for babel source blocks.
435 The list can have entries of the following forms:
436 - :ARG -> :ARG is always a safe header arg
437 - (:ARG . (VAL1 VAL2 ...)) -> :ARG is safe as a header arg if it is
438 `equal' to one of the VALs.
439 - (:ARG . FN) -> :ARG is safe as a header arg if the function FN
440 returns non-nil. FN is passed one
441 argument, the value of the header arg
444 (defmacro org-babel-header-args-safe-fn
(safe-list)
445 "Return a function that determines whether a list of header args are safe.
448 \(put \\='org-babel-default-header-args \\='safe-local-variable
449 (org-babel-header-args-safe-p org-babel-safe-header-args)
451 This allows org-babel languages to extend the list of safe values for
452 their `org-babel-default-header-args:foo' variable.
454 For the format of SAFE-LIST, see `org-babel-safe-header-args'."
460 (org-babel-one-header-arg-safe-p pair
,safe-list
)))
463 (defvar org-babel-default-header-args
464 '((:session .
"none") (:results .
"replace") (:exports .
"code")
465 (:cache .
"no") (:noweb .
"no") (:hlines .
"no") (:tangle .
"no"))
466 "Default arguments to use when evaluating a source block.")
467 (put 'org-babel-default-header-args
'safe-local-variable
468 (org-babel-header-args-safe-fn org-babel-safe-header-args
))
470 (defvar org-babel-default-inline-header-args
471 '((:session .
"none") (:results .
"replace")
472 (:exports .
"results") (:hlines .
"yes"))
473 "Default arguments to use when evaluating an inline source block.")
474 (put 'org-babel-default-inline-header-args
'safe-local-variable
475 (org-babel-header-args-safe-fn org-babel-safe-header-args
))
477 (defconst org-babel-name-regexp
478 (format "^[ \t]*#\\+%s:[ \t]*"
479 ;; FIXME: TBLNAME is for backward compatibility.
480 (regexp-opt '("NAME" "TBLNAME")))
481 "Regexp matching a NAME keyword.")
483 (defconst org-babel-result-regexp
484 (format "^[ \t]*#\\+%s\\(?:\\[\\(?:%S\\)?\\([[:alnum:]]+\\)\\]\\)?:[ \t]*"
485 org-babel-results-keyword
486 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>")
487 "Regular expression used to match result lines.
488 If the results are associated with a hash key then the hash will
489 be saved in match group 1.")
491 (defconst org-babel-result-w-name-regexp
492 (concat org-babel-result-regexp
"\\(?9:[^ \t\n\r\v\f]+\\)")
493 "Regexp matching a RESULTS keyword with a name.
494 Name is saved in match group 9.")
496 (defvar org-babel-min-lines-for-block-output
10
497 "The minimum number of lines for block output.
498 If number of lines of output is equal to or exceeds this
499 value, the output is placed in a #+begin_example...#+end_example
500 block. Otherwise the output is marked as literal by inserting
501 colons at the starts of the lines. This variable only takes
502 effect if the :results output option is in effect.")
504 (defvar org-babel-noweb-error-all-langs nil
505 "Raise errors when noweb references don't resolve.
506 Also see `org-babel-noweb-error-langs' to control noweb errors on
507 a language by language bases.")
509 (defvar org-babel-noweb-error-langs nil
510 "Languages for which Babel will raise literate programming errors.
511 List of languages for which errors should be raised when the
512 source code block satisfying a noweb reference in this language
513 can not be resolved. Also see `org-babel-noweb-error-all-langs'
514 to raise errors for all languages.")
516 (defvar org-babel-hash-show
4
517 "Number of initial characters to show of a hidden results hash.")
519 (defvar org-babel-hash-show-time nil
520 "Non-nil means show the time the code block was evaluated in the result hash.")
522 (defvar org-babel-after-execute-hook nil
523 "Hook for functions to be called after `org-babel-execute-src-block'")
525 (defun org-babel-named-src-block-regexp-for-name (&optional name
)
526 "This generates a regexp used to match a src block named NAME.
527 If NAME is nil, match any name. Matched name is then put in
528 match group 9. Other match groups are defined in
529 `org-babel-src-block-regexp'."
530 (concat org-babel-src-name-regexp
531 (concat (if name
(regexp-quote name
) "\\(?9:.*?\\)") "[ \t]*" )
532 "\\(?:\n[ \t]*#\\+\\S-+:.*\\)*?"
534 (substring org-babel-src-block-regexp
1)))
536 (defun org-babel-named-data-regexp-for-name (name)
537 "This generates a regexp used to match data named NAME."
538 (concat org-babel-name-regexp
(regexp-quote name
) "[ \t]*$"))
540 (defun org-babel--normalize-body (datum)
541 "Normalize body for element or object DATUM.
542 DATUM is a source block element or an inline source block object.
543 Remove final newline character and spurious indentation."
544 (let* ((value (org-element-property :value datum
))
545 (body (if (string-suffix-p "\n" value
)
546 (substring value
0 -
1)
548 (cond ((eq (org-element-type datum
) 'inline-src-block
)
549 ;; Newline characters and indentation in an inline
550 ;; src-block are not meaningful, since they could come from
551 ;; some paragraph filling. Treat them as a white space.
552 (replace-regexp-in-string "\n[ \t]*" " " body
))
553 ((or org-src-preserve-indentation
554 (org-element-property :preserve-indent datum
))
556 (t (org-remove-indentation body
)))))
559 (defvar org-babel-current-src-block-location nil
560 "Marker pointing to the src block currently being executed.
561 This may also point to a call line or an inline code block. If
562 multiple blocks are being executed (e.g., in chained execution
563 through use of the :var header argument) this marker points to
564 the outer-most code block.")
568 (defun org-babel-get-src-block-info (&optional light datum
)
569 "Extract information from a source block or inline source block.
571 Optional argument LIGHT does not resolve remote variable
572 references; a process which could likely result in the execution
573 of other code blocks.
575 By default, consider the block at point. However, when optional
576 argument DATUM is provided, extract information from that parsed
579 Return nil if point is not on a source block. Otherwise, return
580 a list with the following pattern:
582 (language body arguments switches name start coderef)"
583 (let* ((datum (or datum
(org-element-context)))
584 (type (org-element-type datum
))
585 (inline (eq type
'inline-src-block
)))
586 (when (memq type
'(inline-src-block src-block
))
587 (let* ((lang (org-element-property :language datum
))
588 (lang-headers (intern
589 (concat "org-babel-default-header-args:" lang
)))
590 (name (org-element-property :name datum
))
594 (org-babel--normalize-body datum
)
595 (apply #'org-babel-merge-params
596 (if inline org-babel-default-inline-header-args
597 org-babel-default-header-args
)
598 (and (boundp lang-headers
) (eval lang-headers t
))
600 ;; If DATUM is provided, make sure we get node
601 ;; properties applicable to its location within
603 (org-with-point-at (org-element-property :begin datum
)
604 (org-babel-params-from-properties lang
))
605 (mapcar #'org-babel-parse-header-arguments
606 (cons (org-element-property :parameters datum
)
607 (org-element-property :header datum
)))))
608 (or (org-element-property :switches datum
) "")
610 (org-element-property (if inline
:begin
:post-affiliated
)
612 (and (not inline
) (org-src-coderef-format datum
)))))
614 (setf (nth 2 info
) (org-babel-process-params (nth 2 info
))))
615 (setf (nth 2 info
) (org-babel-generate-file-param name
(nth 2 info
)))
619 (defun org-babel-execute-src-block (&optional arg info params
)
620 "Execute the current source code block.
621 Insert the results of execution into the buffer. Source code
622 execution and the collection and formatting of results can be
623 controlled through a variety of header arguments.
625 With prefix argument ARG, force re-execution even if an existing
626 result cached in the buffer would otherwise have been returned.
628 Optionally supply a value for INFO in the form returned by
629 `org-babel-get-src-block-info'.
631 Optionally supply a value for PARAMS which will be merged with
632 the header arguments specified at the front of the source code
635 (let* ((org-babel-current-src-block-location
636 (or org-babel-current-src-block-location
638 (org-babel-where-is-src-block-head)))
639 (info (if info
(copy-tree info
) (org-babel-get-src-block-info))))
640 ;; Merge PARAMS with INFO before considering source block
641 ;; evaluation since both could disagree.
642 (cl-callf org-babel-merge-params
(nth 2 info
) params
)
643 (when (org-babel-check-evaluate info
)
644 (cl-callf org-babel-process-params
(nth 2 info
))
645 (let* ((params (nth 2 info
))
646 (cache (let ((c (cdr (assq :cache params
))))
647 (and (not arg
) c
(string= "yes" c
))))
648 (new-hash (and cache
(org-babel-sha1-hash info
)))
649 (old-hash (and cache
(org-babel-current-result-hash)))
650 (current-cache (and new-hash
(equal new-hash old-hash
))))
653 (save-excursion ;Return cached result.
654 (goto-char (org-babel-where-is-src-block-result nil info
))
656 (skip-chars-forward " \t")
657 (let ((result (org-babel-read-result)))
658 (message (replace-regexp-in-string "%" "%%" (format "%S" result
)))
660 ((org-babel-confirm-evaluate info
)
661 (let* ((lang (nth 0 info
))
662 (result-params (cdr (assq :result-params params
)))
663 ;; Expand noweb references in BODY and remove any
666 (let ((coderef (nth 6 info
))
668 (if (org-babel-noweb-p params
:eval
)
669 (org-babel-expand-noweb-references info
)
671 (if (not coderef
) expand
672 (replace-regexp-in-string
673 (org-src-coderef-regexp coderef
) "" expand nil nil
1))))
674 (dir (cdr (assq :dir params
)))
676 (or (and dir
(file-name-as-directory (expand-file-name dir
)))
678 (cmd (intern (concat "org-babel-execute:" lang
)))
680 (unless (fboundp cmd
)
681 (error "No org-babel-execute function for %s!" lang
))
682 (message "executing %s code block%s..."
684 (let ((name (nth 4 info
)))
685 (if name
(format " (%s)" name
) "")))
686 (if (member "none" result-params
)
687 (progn (funcall cmd body params
)
688 (message "result silenced"))
690 (let ((r (funcall cmd body params
)))
691 (if (and (eq (cdr (assq :result-type params
)) 'value
)
692 (or (member "vector" result-params
)
693 (member "table" result-params
))
697 (let ((file (cdr (assq :file params
))))
698 ;; If non-empty result and :file then write to :file.
702 (insert (org-babel-format-result
703 result
(cdr (assq :sep params
))))))
705 ;; Possibly perform post process provided its
706 ;; appropriate. Dynamically bind "*this*" to the
707 ;; actual results of the block.
708 (let ((post (cdr (assq :post params
))))
710 (let ((*this
* (if (not file
) result
711 (org-babel-result-to-file
713 (let ((desc (assq :file-desc params
)))
714 (and desc
(or (cdr desc
) result
)))))))
715 (setq result
(org-babel-ref-resolve post
))
717 (setq result-params
(remove "file" result-params
))))))
718 (org-babel-insert-result
719 result result-params info new-hash lang
)))
720 (run-hooks 'org-babel-after-execute-hook
)
723 (defun org-babel-expand-body:generic
(body params
&optional var-lines
)
724 "Expand BODY with PARAMS.
725 Expand a block of code with org-babel according to its header
726 arguments. This generic implementation of body expansion is
727 called for languages which have not defined their own specific
728 org-babel-expand-body:lang function."
729 (let ((pro (cdr (assq :prologue params
)))
730 (epi (cdr (assq :epilogue params
))))
731 (mapconcat #'identity
732 (append (when pro
(list pro
))
735 (when epi
(list epi
)))
739 (defun org-babel-expand-src-block (&optional _arg info params
)
740 "Expand the current source code block.
741 Expand according to the source code block's header
742 arguments and pop open the results in a preview buffer."
744 (let* ((info (or info
(org-babel-get-src-block-info)))
746 (params (setf (nth 2 info
)
747 (sort (org-babel-merge-params (nth 2 info
) params
)
748 (lambda (el1 el2
) (string< (symbol-name (car el1
))
749 (symbol-name (car el2
)))))))
750 (body (setf (nth 1 info
)
751 (if (org-babel-noweb-p params
:eval
)
752 (org-babel-expand-noweb-references info
) (nth 1 info
))))
753 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
754 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
757 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
758 (org-babel-expand-body:generic
759 body params
(and (fboundp assignments-cmd
)
760 (funcall assignments-cmd params
))))))
761 (if (called-interactively-p 'any
)
763 expanded
(concat "*Org-Babel Preview " (buffer-name) "[ " lang
" ]*"))
766 (defun org-babel-edit-distance (s1 s2
)
767 "Return the edit (levenshtein) distance between strings S1 S2."
768 (let* ((l1 (length s1
))
770 (dist (vconcat (mapcar (lambda (_) (make-vector (1+ l2
) nil
))
771 (number-sequence 1 (1+ l1
)))))
772 (in (lambda (i j
) (aref (aref dist i
) j
))))
773 (setf (aref (aref dist
0) 0) 0)
774 (dolist (j (number-sequence 1 l2
))
775 (setf (aref (aref dist
0) j
) j
))
776 (dolist (i (number-sequence 1 l1
))
777 (setf (aref (aref dist i
) 0) i
)
778 (dolist (j (number-sequence 1 l2
))
779 (setf (aref (aref dist i
) j
)
781 (1+ (funcall in
(1- i
) j
))
782 (1+ (funcall in i
(1- j
)))
783 (+ (if (equal (aref s1
(1- i
)) (aref s2
(1- j
))) 0 1)
784 (funcall in
(1- i
) (1- j
)))))))
787 (defun org-babel-combine-header-arg-lists (original &rest others
)
788 "Combine a number of lists of header argument names and arguments."
789 (let ((results (copy-sequence original
)))
790 (dolist (new-list others
)
791 (dolist (arg-pair new-list
)
792 (let ((header (car arg-pair
)))
794 (cons arg-pair
(cl-remove-if
795 (lambda (pair) (equal header
(car pair
)))
800 (defun org-babel-check-src-block ()
801 "Check for misspelled header arguments in the current code block."
803 ;; TODO: report malformed code block
804 ;; TODO: report incompatible combinations of header arguments
805 ;; TODO: report uninitialized variables
806 (let ((too-close 2) ;; <- control closeness to report potential match
807 (names (mapcar #'symbol-name org-babel-header-arg-names
)))
808 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg
)) 1))
809 (and (org-babel-where-is-src-block-head)
810 (org-babel-parse-header-arguments
812 (match-string 4))))))
814 (when (and (not (string= header name
))
815 (<= (org-babel-edit-distance header name
) too-close
)
816 (not (member header names
)))
817 (error "Supplied header \"%S\" is suspiciously close to \"%S\""
819 (message "No suspicious header arguments found.")))
822 (defun org-babel-insert-header-arg (&optional header-arg value
)
823 "Insert a header argument selecting from lists of common args and values."
825 (let* ((info (org-babel-get-src-block-info 'light
))
828 (lang-headers (intern (concat "org-babel-header-args:" lang
)))
829 (headers (org-babel-combine-header-arg-lists
830 org-babel-common-header-args-w-values
831 (when (boundp lang-headers
) (eval lang-headers t
))))
832 (header-arg (or header-arg
836 (lambda (header-spec) (symbol-name (car header-spec
)))
838 (vals (cdr (assoc (intern header-arg
) headers
)))
842 (read-from-minibuffer "value: "))
846 (let ((arg (completing-read
849 (mapcar #'symbol-name group
)))))
850 (if (and arg
(not (string= "default" arg
)))
856 (goto-char (point-at-eol))
857 (unless (= (char-before (point)) ?\
) (insert " "))
858 (insert ":" header-arg
) (when value
(insert " " value
)))))
860 ;; Add support for completing-read insertion of header arguments after ":"
861 (defun org-babel-header-arg-expand ()
862 "Call `org-babel-enter-header-arg-w-completion' in appropriate contexts."
863 (when (and (equal (char-before) ?\
:) (org-babel-where-is-src-block-head))
864 (org-babel-enter-header-arg-w-completion (match-string 2))))
866 (defun org-babel-enter-header-arg-w-completion (&optional lang
)
867 "Insert header argument appropriate for LANG with completion."
868 (let* ((lang-headers-var (intern (concat "org-babel-header-args:" lang
)))
869 (lang-headers (when (boundp lang-headers-var
) (eval lang-headers-var t
)))
870 (headers-w-values (org-babel-combine-header-arg-lists
871 org-babel-common-header-args-w-values lang-headers
))
872 (headers (mapcar #'symbol-name
(mapcar #'car headers-w-values
)))
873 (header (org-completing-read "Header Arg: " headers
))
874 (args (cdr (assoc (intern header
) headers-w-values
)))
875 (arg (when (and args
(listp args
))
877 (format "%s: " header
)
878 (mapcar #'symbol-name
(apply #'append args
))))))
879 (insert (concat header
" " (or arg
"")))
882 (add-hook 'org-tab-first-hook
'org-babel-header-arg-expand
)
885 (defun org-babel-load-in-session (&optional _arg info
)
886 "Load the body of the current source-code block.
887 Evaluate the header arguments for the source block before
888 entering the session. After loading the body this pops open the
891 (let* ((info (or info
(org-babel-get-src-block-info)))
893 (params (nth 2 info
))
895 (user-error "No src code block at point")
897 (if (org-babel-noweb-p params
:eval
)
898 (org-babel-expand-noweb-references info
)
900 (session (cdr (assq :session params
)))
901 (dir (cdr (assq :dir params
)))
903 (or (and dir
(file-name-as-directory dir
)) default-directory
))
904 (cmd (intern (concat "org-babel-load-session:" lang
))))
905 (unless (fboundp cmd
)
906 (error "No org-babel-load-session function for %s!" lang
))
907 (pop-to-buffer (funcall cmd session body params
))
911 (defun org-babel-initiate-session (&optional arg info
)
912 "Initiate session for current code block.
913 If called with a prefix argument then resolve any variable
914 references in the header arguments and assign these variables in
915 the session. Copy the body of the code block to the kill ring."
917 (let* ((info (or info
(org-babel-get-src-block-info (not arg
))))
920 (params (nth 2 info
))
921 (session (cdr (assq :session params
)))
922 (dir (cdr (assq :dir params
)))
924 (or (and dir
(file-name-as-directory dir
)) default-directory
))
925 (init-cmd (intern (format "org-babel-%s-initiate-session" lang
)))
926 (prep-cmd (intern (concat "org-babel-prep-session:" lang
))))
927 (when (and (stringp session
) (string= session
"none"))
928 (error "This block is not using a session!"))
929 (unless (fboundp init-cmd
)
930 (error "No org-babel-initiate-session function for %s!" lang
))
931 (with-temp-buffer (insert (org-trim body
))
932 (copy-region-as-kill (point-min) (point-max)))
934 (unless (fboundp prep-cmd
)
935 (error "No org-babel-prep-session function for %s!" lang
))
936 (funcall prep-cmd session params
))
937 (funcall init-cmd session params
)))
940 (defun org-babel-switch-to-session (&optional arg info
)
941 "Switch to the session of the current code block.
942 Uses `org-babel-initiate-session' to start the session. If called
943 with a prefix argument then this is passed on to
944 `org-babel-initiate-session'."
946 (pop-to-buffer (org-babel-initiate-session arg info
))
949 (defalias 'org-babel-pop-to-session
'org-babel-switch-to-session
)
951 (defvar org-src-window-setup
)
954 (defun org-babel-switch-to-session-with-code (&optional arg _info
)
955 "Switch to code buffer and display session."
959 (let ((other-window-buffer (window-buffer (next-window))))
960 (set-window-buffer (next-window) (current-buffer))
961 (set-window-buffer (selected-window) other-window-buffer
))
963 (info (org-babel-get-src-block-info))
964 (org-src-window-setup 'reorganize-frame
))
966 (org-babel-switch-to-session arg info
))
968 (funcall swap-windows
)))
971 (defmacro org-babel-do-in-edit-buffer
(&rest body
)
972 "Evaluate BODY in edit buffer if there is a code block at point.
973 Return t if a code block was found at point, nil otherwise."
974 `(let ((org-src-window-setup 'switch-invisibly
))
975 (when (and (org-babel-where-is-src-block-head)
977 (unwind-protect (progn ,@body
)
980 (def-edebug-spec org-babel-do-in-edit-buffer
(body))
982 (defun org-babel-do-key-sequence-in-edit-buffer (key)
983 "Read key sequence and execute the command in edit buffer.
984 Enter a key sequence to be executed in the language major-mode
985 edit buffer. For example, TAB will alter the contents of the
986 Org code block according to the effect of TAB in the language
987 major mode buffer. For languages that support interactive
988 sessions, this can be used to send code from the Org buffer
989 to the session for evaluation using the native major mode
990 evaluation mechanisms."
991 (interactive "kEnter key-sequence to execute in edit buffer: ")
992 (org-babel-do-in-edit-buffer
994 (key-binding (or key
(read-key-sequence nil
))))))
996 (defvar org-bracket-link-regexp
)
998 (defun org-babel-active-location-p ()
999 (memq (org-element-type (save-match-data (org-element-context)))
1000 '(babel-call inline-babel-call inline-src-block src-block
)))
1003 (defun org-babel-open-src-block-result (&optional re-run
)
1004 "If `point' is on a src block then open the results of the
1005 source code block, otherwise return nil. With optional prefix
1006 argument RE-RUN the source-code block is evaluated even if
1007 results already exist."
1009 (let ((info (org-babel-get-src-block-info 'light
)))
1012 ;; go to the results, if there aren't any then run the block
1013 (goto-char (or (and (not re-run
) (org-babel-where-is-src-block-result))
1014 (progn (org-babel-execute-src-block)
1015 (org-babel-where-is-src-block-result))))
1017 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
1019 (if (looking-at org-bracket-link-regexp
)
1022 (let ((r (org-babel-format-result
1023 (org-babel-read-result) (cdr (assq :sep
(nth 2 info
))))))
1024 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
1025 (delete-region (point-min) (point-max))
1030 (defmacro org-babel-map-src-blocks
(file &rest body
)
1031 "Evaluate BODY forms on each source-block in FILE.
1032 If FILE is nil evaluate BODY forms on source blocks in current
1033 buffer. During evaluation of BODY the following local variables
1034 are set relative to the currently matched code block.
1036 full-block ------- string holding the entirety of the code block
1037 beg-block -------- point at the beginning of the code block
1038 end-block -------- point at the end of the matched code block
1039 lang ------------- string holding the language of the code block
1040 beg-lang --------- point at the beginning of the lang
1041 end-lang --------- point at the end of the lang
1042 switches --------- string holding the switches
1043 beg-switches ----- point at the beginning of the switches
1044 end-switches ----- point at the end of the switches
1045 header-args ------ string holding the header-args
1046 beg-header-args -- point at the beginning of the header-args
1047 end-header-args -- point at the end of the header-args
1048 body ------------- string holding the body of the code block
1049 beg-body --------- point at the beginning of the body
1050 end-body --------- point at the end of the body"
1051 (declare (indent 1))
1052 (let ((tempvar (make-symbol "file")))
1053 `(let* ((case-fold-search t
)
1055 (visited-p (or (null ,tempvar
)
1056 (get-file-buffer (expand-file-name ,tempvar
))))
1057 (point (point)) to-be-removed
)
1058 (save-window-excursion
1059 (when ,tempvar
(find-file ,tempvar
))
1060 (setq to-be-removed
(current-buffer))
1061 (goto-char (point-min))
1062 (while (re-search-forward org-babel-src-block-regexp nil t
)
1063 (when (org-babel-active-location-p)
1064 (goto-char (match-beginning 0))
1065 (let ((full-block (match-string 0))
1066 (beg-block (match-beginning 0))
1067 (end-block (match-end 0))
1068 (lang (match-string 2))
1069 (beg-lang (match-beginning 2))
1070 (end-lang (match-end 2))
1071 (switches (match-string 3))
1072 (beg-switches (match-beginning 3))
1073 (end-switches (match-end 3))
1074 (header-args (match-string 4))
1075 (beg-header-args (match-beginning 4))
1076 (end-header-args (match-end 4))
1077 (body (match-string 5))
1078 (beg-body (match-beginning 5))
1079 (end-body (match-end 5)))
1080 ;; Silence byte-compiler in case `body' doesn't use all
1082 (ignore full-block beg-block end-block lang
1083 beg-lang end-lang switches beg-switches
1084 end-switches header-args beg-header-args
1085 end-header-args body beg-body end-body
)
1087 (goto-char end-block
)))))
1088 (unless visited-p
(kill-buffer to-be-removed
))
1089 (goto-char point
))))
1090 (def-edebug-spec org-babel-map-src-blocks
(form body
))
1093 (defmacro org-babel-map-inline-src-blocks
(file &rest body
)
1094 "Evaluate BODY forms on each inline source block in FILE.
1095 If FILE is nil evaluate BODY forms on source blocks in current
1097 (declare (indent 1) (debug (form body
)))
1098 (org-with-gensyms (datum end point tempvar to-be-removed visitedp
)
1099 `(let* ((case-fold-search t
)
1101 (,visitedp
(or (null ,tempvar
)
1102 (get-file-buffer (expand-file-name ,tempvar
))))
1105 (save-window-excursion
1106 (when ,tempvar
(find-file ,tempvar
))
1107 (setq ,to-be-removed
(current-buffer))
1108 (goto-char (point-min))
1109 (while (re-search-forward "src_\\S-" nil t
)
1110 (let ((,datum
(save-match-data (org-element-context))))
1111 (when (eq (org-element-type ,datum
) 'inline-src-block
)
1112 (goto-char (match-beginning 0))
1113 (let ((,end
(copy-marker (org-element-property :end
,datum
))))
1116 (set-marker ,end nil
))))))
1117 (unless ,visitedp
(kill-buffer ,to-be-removed
))
1118 (goto-char ,point
))))
1121 (defmacro org-babel-map-call-lines
(file &rest body
)
1122 "Evaluate BODY forms on each call line in FILE.
1123 If FILE is nil evaluate BODY forms on source blocks in current
1125 (declare (indent 1) (debug (form body
)))
1126 (org-with-gensyms (datum end point tempvar to-be-removed visitedp
)
1127 `(let* ((case-fold-search t
)
1129 (,visitedp
(or (null ,tempvar
)
1130 (get-file-buffer (expand-file-name ,tempvar
))))
1133 (save-window-excursion
1134 (when ,tempvar
(find-file ,tempvar
))
1135 (setq ,to-be-removed
(current-buffer))
1136 (goto-char (point-min))
1137 (while (re-search-forward "call_\\S-\\|^[ \t]*#\\+CALL:" nil t
)
1138 (let ((,datum
(save-match-data (org-element-context))))
1139 (when (memq (org-element-type ,datum
)
1140 '(babel-call inline-babel-call
))
1141 (goto-char (match-beginning 0))
1142 (let ((,end
(copy-marker (org-element-property :end
,datum
))))
1145 (set-marker ,end nil
))))))
1146 (unless ,visitedp
(kill-buffer ,to-be-removed
))
1147 (goto-char ,point
))))
1150 (defmacro org-babel-map-executables
(file &rest body
)
1151 "Evaluate BODY forms on each active Babel code in FILE.
1152 If FILE is nil evaluate BODY forms on source blocks in current
1154 (declare (indent 1) (debug (form body
)))
1155 (org-with-gensyms (datum end point tempvar to-be-removed visitedp
)
1156 `(let* ((case-fold-search t
)
1158 (,visitedp
(or (null ,tempvar
)
1159 (get-file-buffer (expand-file-name ,tempvar
))))
1162 (save-window-excursion
1163 (when ,tempvar
(find-file ,tempvar
))
1164 (setq ,to-be-removed
(current-buffer))
1165 (goto-char (point-min))
1166 (while (re-search-forward
1167 "\\(call\\|src\\)_\\|^[ \t]*#\\+\\(BEGIN_SRC\\|CALL:\\)" nil t
)
1168 (let ((,datum
(save-match-data (org-element-context))))
1169 (when (memq (org-element-type ,datum
)
1170 '(babel-call inline-babel-call inline-src-block
1172 (goto-char (match-beginning 0))
1173 (let ((,end
(copy-marker (org-element-property :end
,datum
))))
1176 (set-marker ,end nil
))))))
1177 (unless ,visitedp
(kill-buffer ,to-be-removed
))
1178 (goto-char ,point
))))
1181 (defun org-babel-execute-buffer (&optional arg
)
1182 "Execute source code blocks in a buffer.
1183 Call `org-babel-execute-src-block' on every source block in
1184 the current buffer."
1186 (org-babel-eval-wipe-error-buffer)
1187 (org-save-outline-visibility t
1188 (org-babel-map-executables nil
1189 (if (memq (org-element-type (org-element-context))
1190 '(babel-call inline-babel-call
))
1191 (org-babel-lob-execute-maybe)
1192 (org-babel-execute-src-block arg
)))))
1195 (defun org-babel-execute-subtree (&optional arg
)
1196 "Execute source code blocks in a subtree.
1197 Call `org-babel-execute-src-block' on every source block in
1198 the current subtree."
1202 (org-narrow-to-subtree)
1203 (org-babel-execute-buffer arg
)
1207 (defun org-babel-sha1-hash (&optional info
)
1208 "Generate an sha1 hash based on the value of info."
1210 (let ((print-level nil
)
1211 (info (or info
(org-babel-get-src-block-info))))
1213 (sort (copy-sequence (nth 2 info
))
1214 (lambda (a b
) (string< (car a
) (car b
)))))
1215 (let* ((rm (lambda (lst)
1216 (dolist (p '("replace" "silent" "none"
1217 "append" "prepend"))
1218 (setq lst
(remove p lst
)))
1221 (let ((v (if (and (listp (cdr arg
)) (null (cddr arg
)))
1222 (copy-sequence (cdr arg
))
1224 (when (and v
(not (and (sequencep v
)
1228 ((and (listp v
) ; lists are sorted
1229 (member (car arg
) '(:result-params
)))
1230 (sort (funcall rm v
) #'string
<))
1231 ((and (stringp v
) ; strings are sorted
1232 (member (car arg
) '(:results
:exports
)))
1233 (mapconcat #'identity
(sort (funcall rm
(split-string v
))
1238 (params (nth 2 info
))
1239 (body (if (org-babel-noweb-p params
:eval
)
1240 (org-babel-expand-noweb-references info
) (nth 1 info
)))
1241 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
1242 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
1245 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
1246 (org-babel-expand-body:generic
1247 body params
(and (fboundp assignments-cmd
)
1248 (funcall assignments-cmd params
))))))
1249 (let* ((it (format "%s-%s"
1252 (delq nil
(mapcar (lambda (arg)
1253 (let ((normalized (funcall norm arg
)))
1255 (format "%S" normalized
))))
1259 (when (called-interactively-p 'interactive
) (message hash
))
1262 (defun org-babel-current-result-hash (&optional info
)
1263 "Return the current in-buffer hash."
1264 (let ((result (org-babel-where-is-src-block-result nil info
)))
1266 (org-with-wide-buffer
1268 (looking-at org-babel-result-regexp
)
1269 (match-string-no-properties 1)))))
1271 (defun org-babel-set-current-result-hash (hash info
)
1272 "Set the current in-buffer hash to HASH."
1273 (org-with-wide-buffer
1274 (goto-char (org-babel-where-is-src-block-result nil info
))
1275 (looking-at org-babel-result-regexp
)
1276 (goto-char (match-beginning 1))
1277 (mapc #'delete-overlay
(overlays-at (point)))
1278 (forward-char org-babel-hash-show
)
1279 (mapc #'delete-overlay
(overlays-at (point)))
1280 (replace-match hash nil nil nil
1)
1282 (org-babel-hide-hash)))
1284 (defun org-babel-hide-hash ()
1285 "Hide the hash in the current results line.
1286 Only the initial `org-babel-hash-show' characters of the hash
1287 will remain visible."
1288 (add-to-invisibility-spec '(org-babel-hide-hash . t
))
1290 (when (and (re-search-forward org-babel-result-regexp nil t
)
1292 (let* ((start (match-beginning 1))
1293 (hide-start (+ org-babel-hash-show start
))
1295 (hash (match-string 1))
1297 (setq ov1
(make-overlay start hide-start
))
1298 (setq ov2
(make-overlay hide-start end
))
1299 (overlay-put ov2
'invisible
'org-babel-hide-hash
)
1300 (overlay-put ov1
'babel-hash hash
)))))
1302 (defun org-babel-hide-all-hashes ()
1303 "Hide the hash in the current buffer.
1304 Only the initial `org-babel-hash-show' characters of each hash
1305 will remain visible. This function should be called as part of
1306 the `org-mode-hook'."
1308 (while (and (not org-babel-hash-show-time
)
1309 (re-search-forward org-babel-result-regexp nil t
))
1310 (goto-char (match-beginning 0))
1311 (org-babel-hide-hash)
1312 (goto-char (match-end 0)))))
1313 (add-hook 'org-mode-hook
'org-babel-hide-all-hashes
)
1315 (defun org-babel-hash-at-point (&optional point
)
1316 "Return the value of the hash at POINT.
1318 The hash is also added as the last element of the kill ring.
1319 This can be called with \\[org-ctrl-c-ctrl-c]."
1321 (let ((hash (car (delq nil
(mapcar
1322 (lambda (ol) (overlay-get ol
'babel-hash
))
1323 (overlays-at (or point
(point))))))))
1324 (when hash
(kill-new hash
) (message hash
))))
1325 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-hash-at-point
)
1327 (defun org-babel-result-hide-spec ()
1328 "Hide portions of results lines.
1329 Add `org-babel-hide-result' as an invisibility spec for hiding
1330 portions of results lines."
1331 (add-to-invisibility-spec '(org-babel-hide-result . t
)))
1332 (add-hook 'org-mode-hook
'org-babel-result-hide-spec
)
1334 (defvar org-babel-hide-result-overlays nil
1335 "Overlays hiding results.")
1337 (defun org-babel-result-hide-all ()
1338 "Fold all results in the current buffer."
1340 (org-babel-show-result-all)
1342 (while (re-search-forward org-babel-result-regexp nil t
)
1343 (save-excursion (goto-char (match-beginning 0))
1344 (org-babel-hide-result-toggle-maybe)))))
1346 (defun org-babel-show-result-all ()
1347 "Unfold all results in the current buffer."
1348 (mapc 'delete-overlay org-babel-hide-result-overlays
)
1349 (setq org-babel-hide-result-overlays nil
))
1352 (defun org-babel-hide-result-toggle-maybe ()
1353 "Toggle visibility of result at point."
1355 (let ((case-fold-search t
))
1357 (beginning-of-line 1)
1358 (looking-at org-babel-result-regexp
))
1359 (progn (org-babel-hide-result-toggle)
1360 t
) ;; to signal that we took action
1361 nil
))) ;; to signal that we did not
1363 (defun org-babel-hide-result-toggle (&optional force
)
1364 "Toggle the visibility of the current result."
1368 (if (re-search-forward org-babel-result-regexp nil t
)
1369 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
1371 (while (looking-at org-babel-multi-line-header-regexp
)
1373 (goto-char (- (org-babel-result-end) 1)) (point)))
1375 (if (memq t
(mapcar (lambda (overlay)
1376 (eq (overlay-get overlay
'invisible
)
1377 'org-babel-hide-result
))
1378 (overlays-at start
)))
1379 (when (or (not force
) (eq force
'off
))
1381 (when (member ov org-babel-hide-result-overlays
)
1382 (setq org-babel-hide-result-overlays
1383 (delq ov org-babel-hide-result-overlays
)))
1384 (when (eq (overlay-get ov
'invisible
)
1385 'org-babel-hide-result
)
1386 (delete-overlay ov
)))
1387 (overlays-at start
)))
1388 (setq ov
(make-overlay start end
))
1389 (overlay-put ov
'invisible
'org-babel-hide-result
)
1390 ;; make the block accessible to isearch
1392 ov
'isearch-open-invisible
1394 (when (member ov org-babel-hide-result-overlays
)
1395 (setq org-babel-hide-result-overlays
1396 (delq ov org-babel-hide-result-overlays
)))
1397 (when (eq (overlay-get ov
'invisible
)
1398 'org-babel-hide-result
)
1399 (delete-overlay ov
))))
1400 (push ov org-babel-hide-result-overlays
)))
1401 (error "Not looking at a result line"))))
1403 ;; org-tab-after-check-for-cycling-hook
1404 (add-hook 'org-tab-first-hook
'org-babel-hide-result-toggle-maybe
)
1405 ;; Remove overlays when changing major mode
1406 (add-hook 'org-mode-hook
1407 (lambda () (add-hook 'change-major-mode-hook
1408 'org-babel-show-result-all
'append
'local
)))
1410 (defvar org-file-properties
)
1411 (defun org-babel-params-from-properties (&optional lang
)
1412 "Retrieve parameters specified as properties.
1413 Return a list of association lists of source block params
1414 specified in the properties of the current outline entry."
1417 ;; header arguments specified with the header-args property at
1419 (org-babel-parse-header-arguments
1420 (org-entry-get org-babel-current-src-block-location
1423 (and lang
; language-specific header arguments at point of call
1424 (org-babel-parse-header-arguments
1425 (org-entry-get org-babel-current-src-block-location
1426 (concat "header-args:" lang
)
1429 (defun org-babel-balanced-split (string alts
)
1430 "Split STRING on instances of ALTS.
1431 ALTS is a cons of two character options where each option may be
1432 either the numeric code of a single character or a list of
1433 character alternatives. For example to split on balanced
1434 instances of \"[ \t]:\" set ALTS to ((32 9) . 58)."
1435 (let* ((matches (lambda (ch spec
) (if (listp spec
) (member ch spec
) (equal spec ch
))))
1436 (matched (lambda (ch last
)
1438 (and (funcall matches ch
(cdr alts
))
1439 (funcall matches last
(car alts
)))
1440 (funcall matches ch alts
))))
1441 (balance 0) (last 0)
1443 (mapc (lambda (ch) ; split on [], (), "" balanced instances of [ \t]:
1444 (setq balance
(+ balance
1445 (cond ((or (equal 91 ch
) (equal 40 ch
)) 1)
1446 ((or (equal 93 ch
) (equal 41 ch
)) -
1)
1448 (when (and (equal 34 ch
) (not (equal 92 last
)))
1449 (setq quote
(not quote
)))
1450 (setq partial
(cons ch partial
))
1451 (when (and (= balance
0) (not quote
) (funcall matched ch last
))
1452 (setq lst
(cons (apply #'string
(nreverse
1459 (string-to-list string
))
1460 (nreverse (cons (apply #'string
(nreverse partial
)) lst
))))
1462 (defun org-babel-join-splits-near-ch (ch list
)
1463 "Join splits where \"=\" is on either end of the split."
1464 (let ((last= (lambda (str) (= ch
(aref str
(1- (length str
))))))
1465 (first= (lambda (str) (= ch
(aref str
0)))))
1467 (cl-reduce (lambda (acc el
)
1468 (let ((head (car acc
)))
1469 (if (and head
(or (funcall last
= head
) (funcall first
= el
)))
1470 (cons (concat head el
) (cdr acc
))
1472 list
:initial-value nil
))))
1474 (defun org-babel-parse-header-arguments (arg-string)
1475 "Parse a string of header arguments returning an alist."
1476 (when (> (length arg-string
) 0)
1477 (org-babel-parse-multiple-vars
1482 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1484 (cons (intern (match-string 1 arg
))
1485 (org-babel-read (org-babel-chomp (match-string 2 arg
))))
1486 (cons (intern (org-babel-chomp arg
)) nil
)))
1487 (let ((raw (org-babel-balanced-split arg-string
'((32 9) .
58))))
1488 (cons (car raw
) (mapcar (lambda (r) (concat ":" r
)) (cdr raw
)))))))))
1490 (defun org-babel-parse-multiple-vars (header-arguments)
1491 "Expand multiple variable assignments behind a single :var keyword.
1493 This allows expression of multiple variables with one :var as
1496 #+PROPERTY: var foo=1, bar=2"
1498 (mapc (lambda (pair)
1499 (if (eq (car pair
) :var
)
1500 (mapcar (lambda (v) (push (cons :var
(org-trim v
)) results
))
1501 (org-babel-join-splits-near-ch
1502 61 (org-babel-balanced-split (cdr pair
) 32)))
1503 (push pair results
)))
1505 (nreverse results
)))
1507 (defun org-babel-process-params (params)
1508 "Expand variables in PARAMS and add summary parameters."
1509 (let* ((processed-vars (mapcar (lambda (el)
1512 (org-babel-ref-parse el
)))
1513 (org-babel--get-vars params
)))
1514 (vars-and-names (if (and (assq :colname-names params
)
1515 (assq :rowname-names params
))
1516 (list processed-vars
)
1517 (org-babel-disassemble-tables
1519 (cdr (assq :hlines params
))
1520 (cdr (assq :colnames params
))
1521 (cdr (assq :rownames params
)))))
1522 (raw-result (or (cdr (assq :results params
)) ""))
1523 (result-params (delete-dups
1525 (split-string (if (stringp raw-result
)
1527 (eval raw-result t
)))
1528 (cdr (assq :result-params params
))))))
1530 (mapcar (lambda (var) (cons :var var
)) (car vars-and-names
))
1532 (cons :colname-names
(or (cdr (assq :colname-names params
))
1533 (cadr vars-and-names
)))
1534 (cons :rowname-names
(or (cdr (assq :rowname-names params
))
1535 (cl-caddr vars-and-names
)))
1536 (cons :result-params result-params
)
1537 (cons :result-type
(cond ((member "output" result-params
) 'output
)
1538 ((member "value" result-params
) 'value
)
1541 (lambda (x) (memq (car x
) '(:colname-names
:rowname-names
:result-params
1542 :result-type
:var
)))
1545 ;; row and column names
1546 (defun org-babel-del-hlines (table)
1547 "Remove all `hline's from TABLE."
1548 (remq 'hline table
))
1550 (defun org-babel-get-colnames (table)
1551 "Return the column names of TABLE.
1552 Return a cons cell, the `car' of which contains the TABLE less
1553 colnames, and the `cdr' of which contains a list of the column
1555 (if (equal 'hline
(nth 1 table
))
1556 (cons (cddr table
) (car table
))
1557 (cons (cdr table
) (car table
))))
1559 (defun org-babel-get-rownames (table)
1560 "Return the row names of TABLE.
1561 Return a cons cell, the `car' of which contains the TABLE less
1562 rownames, and the `cdr' of which contains a list of the rownames.
1563 Note: this function removes any hlines in TABLE."
1564 (let* ((table (org-babel-del-hlines table
))
1565 (rownames (funcall (lambda ()
1571 (setq tp
(cdr tp
))))
1573 (cons table rownames
)))
1575 (defun org-babel-put-colnames (table colnames
)
1576 "Add COLNAMES to TABLE if they exist."
1577 (if colnames
(apply 'list colnames
'hline table
) table
))
1579 (defun org-babel-put-rownames (table rownames
)
1580 "Add ROWNAMES to TABLE if they exist."
1582 (mapcar (lambda (row)
1584 (cons (or (pop rownames
) "") row
)
1588 (defun org-babel-pick-name (names selector
)
1589 "Select one out of an alist of row or column names.
1590 SELECTOR can be either a list of names in which case those names
1591 will be returned directly, or an index into the list NAMES in
1592 which case the indexed names will be return."
1593 (if (listp selector
)
1596 (if (and selector
(symbolp selector
) (not (equal t selector
)))
1597 (cdr (assoc selector names
))
1598 (if (integerp selector
)
1599 (nth (- selector
1) names
)
1600 (cdr (car (last names
))))))))
1602 (defun org-babel-disassemble-tables (vars hlines colnames rownames
)
1603 "Parse tables for further processing.
1604 Process the variables in VARS according to the HLINES,
1605 ROWNAMES and COLNAMES header arguments. Return a list consisting
1606 of the vars, cnames and rnames."
1607 (let (cnames rnames
)
1611 (when (listp (cdr var
))
1612 (when (and (not (equal colnames
"no"))
1613 (or colnames
(and (equal (nth 1 (cdr var
)) 'hline
)
1614 (not (member 'hline
(cddr (cdr var
)))))))
1615 (let ((both (org-babel-get-colnames (cdr var
))))
1616 (setq cnames
(cons (cons (car var
) (cdr both
))
1618 (setq var
(cons (car var
) (car both
)))))
1619 (when (and rownames
(not (equal rownames
"no")))
1620 (let ((both (org-babel-get-rownames (cdr var
))))
1621 (setq rnames
(cons (cons (car var
) (cdr both
))
1623 (setq var
(cons (car var
) (car both
)))))
1624 (when (and hlines
(not (equal hlines
"yes")))
1625 (setq var
(cons (car var
) (org-babel-del-hlines (cdr var
))))))
1628 (reverse cnames
) (reverse rnames
))))
1630 (defun org-babel-reassemble-table (table colnames rownames
)
1631 "Add column and row names to a table.
1632 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1633 to the table for reinsertion to org-mode."
1635 (let ((table (if (and rownames
(= (length table
) (length rownames
)))
1636 (org-babel-put-rownames table rownames
) table
)))
1637 (if (and colnames
(listp (car table
)) (= (length (car table
))
1639 (org-babel-put-colnames table colnames
) table
))
1642 (defun org-babel-where-is-src-block-head (&optional src-block
)
1643 "Find where the current source block begins.
1645 If optional argument SRC-BLOCK is `src-block' type element, find
1646 its current beginning instead.
1648 Return the point at the beginning of the current source block.
1649 Specifically at the beginning of the #+BEGIN_SRC line. Also set
1650 match-data relatively to `org-babel-src-block-regexp', which see.
1651 If the point is not on a source block then return nil."
1652 (let ((element (or src-block
(org-element-at-point))))
1653 (when (eq (org-element-type element
) 'src-block
)
1654 (let ((end (org-element-property :end element
)))
1655 (org-with-wide-buffer
1656 ;; Ensure point is not on a blank line after the block.
1658 (skip-chars-forward " \r\t\n" end
)
1659 (when (< (point) end
)
1660 (prog1 (goto-char (org-element-property :post-affiliated element
))
1661 (looking-at org-babel-src-block-regexp
))))))))
1664 (defun org-babel-goto-src-block-head ()
1665 "Go to the beginning of the current code block."
1667 (let ((head (org-babel-where-is-src-block-head)))
1668 (if head
(goto-char head
) (error "Not currently in a code block"))))
1671 (defun org-babel-goto-named-src-block (name)
1672 "Go to a named source-code block."
1674 (let ((completion-ignore-case t
)
1675 (case-fold-search t
)
1676 (all-block-names (org-babel-src-block-names)))
1677 (list (completing-read
1678 "source-block name: " all-block-names nil t
1679 (let* ((context (org-element-context))
1680 (type (org-element-type context
))
1682 (and (memq type
'(inline-src-block src-block
))
1683 (org-in-regexp (org-babel-noweb-wrap)))))
1687 (+ (car noweb-ref
) (length org-babel-noweb-wrap-start
))
1688 (- (cdr noweb-ref
) (length org-babel-noweb-wrap-end
))))
1689 ((memq type
'(babel-call inline-babel-call
)) ;#+CALL:
1690 (org-element-property :call context
))
1691 ((car (org-element-property :results context
))) ;#+RESULTS:
1692 ((let ((symbol (thing-at-point 'symbol
))) ;Symbol.
1694 (member-ignore-case symbol all-block-names
)
1697 (let ((point (org-babel-find-named-block name
)))
1699 ;; Taken from `org-open-at-point'.
1700 (progn (org-mark-ring-push) (goto-char point
) (org-show-context))
1701 (message "source-code block `%s' not found in this buffer" name
))))
1703 (defun org-babel-find-named-block (name)
1704 "Find a named source-code block.
1705 Return the location of the source block identified by source
1706 NAME, or nil if no such block exists. Set match data according
1707 to `org-babel-named-src-block-regexp'."
1709 (goto-char (point-min))
1711 (org-next-block 1 nil
(org-babel-named-src-block-regexp-for-name name
)))))
1713 (defun org-babel-src-block-names (&optional file
)
1714 "Returns the names of source blocks in FILE or the current buffer."
1715 (when file
(find-file file
))
1717 (goto-char (point-min))
1718 (let ((re (org-babel-named-src-block-regexp-for-name))
1720 (while (ignore-errors (org-next-block 1 nil re
))
1721 (push (match-string-no-properties 9) names
))
1725 (defun org-babel-goto-named-result (name)
1726 "Go to a named result."
1728 (let ((completion-ignore-case t
))
1729 (list (completing-read "Source-block name: "
1730 (org-babel-result-names) nil t
))))
1731 (let ((point (org-babel-find-named-result name
)))
1733 ;; taken from `org-open-at-point'
1734 (progn (goto-char point
) (org-show-context))
1735 (message "result `%s' not found in this buffer" name
))))
1737 (defun org-babel-find-named-result (name)
1738 "Find a named result.
1739 Return the location of the result named NAME in the current
1740 buffer or nil if no such result exists."
1742 (goto-char (point-min))
1743 (let ((case-fold-search t
)
1744 (re (format "^[ \t]*#\\+%s.*?:[ \t]*%s[ \t]*$"
1745 org-babel-results-keyword
1746 (regexp-quote name
))))
1748 (while (re-search-forward re nil t
)
1749 (let ((element (org-element-at-point)))
1750 (when (or (eq (org-element-type element
) 'keyword
)
1752 (org-element-property :post-affiliated element
)))
1753 (throw :found
(line-beginning-position)))))))))
1755 (defun org-babel-result-names (&optional file
)
1756 "Returns the names of results in FILE or the current buffer."
1758 (when file
(find-file file
)) (goto-char (point-min))
1759 (let ((case-fold-search t
) names
)
1760 (while (re-search-forward org-babel-result-w-name-regexp nil t
)
1761 (setq names
(cons (match-string-no-properties 9) names
)))
1765 (defun org-babel-next-src-block (&optional arg
)
1766 "Jump to the next source block.
1767 With optional prefix argument ARG, jump forward ARG many source blocks."
1769 (org-next-block arg nil org-babel-src-block-regexp
))
1772 (defun org-babel-previous-src-block (&optional arg
)
1773 "Jump to the previous source block.
1774 With optional prefix argument ARG, jump backward ARG many source blocks."
1776 (org-previous-block arg org-babel-src-block-regexp
))
1778 (defvar org-babel-load-languages
)
1781 (defun org-babel-mark-block ()
1782 "Mark current src block."
1784 (let ((head (org-babel-where-is-src-block-head)))
1788 (looking-at org-babel-src-block-regexp
))
1789 (push-mark (match-end 5) nil t
)
1790 (goto-char (match-beginning 5)))))
1792 (defun org-babel-demarcate-block (&optional arg
)
1793 "Wrap or split the code in the region or on the point.
1794 When called from inside of a code block the current block is
1795 split. When called from outside of a code block a new code block
1796 is created. In both cases if the region is demarcated and if the
1797 region is not active then the point is demarcated."
1799 (let* ((info (org-babel-get-src-block-info 'light
))
1800 (start (org-babel-where-is-src-block-head))
1801 (block (and start
(match-string 0)))
1802 (headers (and start
(match-string 4)))
1803 (stars (concat (make-string (or (org-current-level) 1) ?
*) " "))
1804 (lower-case-p (and block
1805 (let (case-fold-search)
1806 (string-match-p "#\\+begin_src" block
)))))
1812 (let ((lang (nth 0 info
))
1813 (indent (make-string (org-get-indentation) ?\s
)))
1814 (when (string-match "^[[:space:]]*$"
1815 (buffer-substring (point-at-bol)
1817 (delete-region (point-at-bol) (point-at-eol)))
1819 (if (looking-at "^") "" "\n")
1820 indent
(funcall (if lower-case-p
'downcase
'upcase
) "#+end_src\n")
1821 (if arg stars indent
) "\n"
1822 indent
(funcall (if lower-case-p
'downcase
'upcase
) "#+begin_src ")
1824 (if (> (length headers
) 1)
1825 (concat " " headers
) headers
)
1826 (if (looking-at "[\n\r]")
1828 (concat "\n" (make-string (current-column) ?
)))))))
1829 (move-end-of-line 2))
1830 (sort (if (org-region-active-p) (list (mark) (point)) (list (point))) #'>))
1831 (let ((start (point))
1832 (lang (completing-read
1834 (mapcar #'symbol-name
1836 (append (mapcar #'car org-babel-load-languages
)
1837 (mapcar (lambda (el) (intern (car el
)))
1838 org-src-lang-modes
))))))
1839 (body (delete-and-extract-region
1840 (if (org-region-active-p) (mark) (point)) (point))))
1841 (insert (concat (if (looking-at "^") "" "\n")
1842 (if arg
(concat stars
"\n") "")
1843 (funcall (if lower-case-p
'downcase
'upcase
) "#+begin_src ")
1846 (if (or (= (length body
) 0)
1847 (string-suffix-p "\r" body
)
1848 (string-suffix-p "\n" body
)) "" "\n")
1849 (funcall (if lower-case-p
'downcase
'upcase
) "#+end_src\n")))
1850 (goto-char start
) (move-end-of-line 1)))))
1852 (defun org-babel--insert-results-keyword (name hash
)
1853 "Insert RESULTS keyword with NAME value at point.
1854 If NAME is nil, results are anonymous. HASH is a string used as
1855 the results hash, or nil. Leave point before the keyword."
1856 (save-excursion (insert "\n")) ;open line to indent.
1859 (insert (concat "#+" org-babel-results-keyword
1860 (cond ((not hash
) nil
)
1861 (org-babel-hash-show-time
1863 (format-time-string "<%Y-%m-%d %H:%M:%S>")
1865 (t (format "[%s]" hash
)))
1867 (when name
(concat " " name
))
1869 (beginning-of-line -
1)
1870 (when hash
(org-babel-hide-hash)))
1872 (defun org-babel--clear-results-maybe (hash)
1873 "Clear results when hash doesn't match HASH.
1875 When results hash does not match HASH, remove RESULTS keyword at
1876 point, along with related contents. Do nothing if HASH is nil.
1878 Return a non-nil value if results were cleared. In this case,
1879 leave point where new results should be inserted."
1881 (looking-at org-babel-result-regexp
)
1882 (unless (string= (match-string 1) hash
)
1883 (let* ((e (org-element-at-point))
1884 (post (copy-marker (org-element-property :post-affiliated e
))))
1888 (goto-char (org-element-property :end e
))
1889 (skip-chars-backward " \t\n")
1890 (line-beginning-position 2)))
1891 ;; Delete RESULT keyword. However, if RESULTS keyword is
1892 ;; orphaned, ignore this part. The deletion above already
1894 (unless (= (point) post
)
1895 (delete-region (line-beginning-position)
1896 (line-beginning-position 2)))
1898 (set-marker post nil
)))
1901 (defun org-babel-where-is-src-block-result (&optional insert _info hash
)
1902 "Find where the current source block results begin.
1904 Return the point at the beginning of the result of the current
1905 source block, specifically at the beginning of the results line.
1907 If no result exists for this block return nil, unless optional
1908 argument INSERT is non-nil. In this case, create a results line
1909 following the source block and return the position at its
1910 beginning. In the case of inline code, remove the results part
1913 If optional argument HASH is a string, remove contents related to
1914 RESULTS keyword if its hash is different. Then update the latter
1916 (let ((context (org-element-context)))
1918 (org-with-wide-buffer
1919 (pcase (org-element-type context
)
1920 ((or `inline-babel-call
`inline-src-block
)
1921 ;; Results for inline objects are located right after them.
1922 ;; There is no RESULTS line to insert either.
1923 (let ((limit (org-element-property
1924 :contents-end
(org-element-property :parent context
))))
1925 (goto-char (org-element-property :end context
))
1926 (skip-chars-forward " \t\n" limit
)
1930 (let ((result (org-element-context)))
1931 (and (eq (org-element-type result
) 'macro
)
1932 (string= (org-element-property :key result
)
1934 (if (not insert
) (point)
1938 (goto-char (org-element-property :end result
))
1939 (skip-chars-backward " \t")
1942 ((or `babel-call
`src-block
)
1943 (let* ((name (org-element-property :name context
))
1944 (named-results (and name
(org-babel-find-named-result name
))))
1945 (goto-char (or named-results
(org-element-property :end context
)))
1947 ;; Existing results named after the current source.
1949 (when (org-babel--clear-results-maybe hash
)
1950 (org-babel--insert-results-keyword name hash
))
1951 (throw :found
(point)))
1952 ;; Named results expect but none to be found.
1954 ;; No possible anonymous results at the very end of
1955 ;; buffer or outside CONTEXT parent.
1957 (or (org-element-property
1958 :contents-end
(org-element-property :parent context
))
1960 ;; Check if next element is an anonymous result below
1961 ;; the current block.
1962 ((let* ((next (org-element-at-point))
1963 (end (save-excursion
1965 (org-element-property :post-affiliated next
))
1966 (line-end-position)))
1967 (empty-result-re (concat org-babel-result-regexp
"$"))
1968 (case-fold-search t
))
1969 (re-search-forward empty-result-re end t
))
1971 (when (org-babel--clear-results-maybe hash
)
1972 (org-babel--insert-results-keyword nil hash
))
1973 (throw :found
(point))))))
1974 ;; Ignore other elements.
1975 (_ (throw :found nil
))))
1976 ;; No result found. Insert a RESULTS keyword below element, if
1977 ;; appropriate. In this case, ensure there is an empty line
1978 ;; after the previous element.
1981 (goto-char (min (org-element-property :end context
) (point-max)))
1982 (skip-chars-backward " \t\n")
1984 (cond ((not (bolp)) (insert "\n\n"))
1986 (= (org-element-property :post-blank context
) 0))
1989 (org-babel--insert-results-keyword
1990 (org-element-property :name context
) hash
)
1993 (defun org-babel-read-element (element)
1994 "Read ELEMENT into emacs-lisp.
1995 Return nil if ELEMENT cannot be read."
1996 (org-with-wide-buffer
1997 (goto-char (org-element-property :post-affiliated element
))
1998 (pcase (org-element-type element
)
2000 (let ((v (org-trim (org-element-property :value element
))))
2001 (or (org-babel--string-to-number v
) v
)))
2002 (`table
(org-babel-read-table))
2003 (`plain-list
(org-babel-read-list))
2005 (let ((v (org-element-property :value element
)))
2006 (if (or org-src-preserve-indentation
2007 (org-element-property :preserve-indent element
))
2009 (org-remove-indentation v
))))
2011 (org-remove-indentation (org-element-property :value element
)))
2013 ;; Treat paragraphs containing a single link specially.
2014 (skip-chars-forward " \t")
2015 (if (and (looking-at org-bracket-link-regexp
)
2017 (goto-char (match-end 0))
2018 (skip-chars-forward " \r\t\n")
2019 (<= (org-element-property :end element
)
2021 (org-babel-read-link)
2022 (buffer-substring-no-properties
2023 (org-element-property :contents-begin element
)
2024 (org-element-property :contents-end element
))))
2025 ((or `center-block
`quote-block
`verse-block
`special-block
)
2026 (org-remove-indentation
2027 (buffer-substring-no-properties
2028 (org-element-property :contents-begin element
)
2029 (org-element-property :contents-end element
))))
2032 (defun org-babel-read-result ()
2033 "Read the result at point into emacs-lisp."
2034 (and (not (save-excursion
2036 (looking-at-p "[ \t]*$")))
2037 (org-babel-read-element (org-element-at-point))))
2039 (defun org-babel-read-table ()
2040 "Read the table at point into emacs-lisp."
2041 (mapcar (lambda (row)
2042 (if (and (symbolp row
) (equal row
'hline
)) row
2043 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
)) row
)))
2044 (org-table-to-lisp)))
2046 (defun org-babel-read-list ()
2047 "Read the list at point into emacs-lisp."
2048 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
))
2049 (cdr (org-list-to-lisp))))
2051 (defvar org-link-types-re
)
2052 (defun org-babel-read-link ()
2053 "Read the link at point into emacs-lisp.
2054 If the path of the link is a file path it is expanded using
2055 `expand-file-name'."
2056 (let* ((case-fold-search t
)
2057 (raw (and (looking-at org-bracket-link-regexp
)
2058 (org-no-properties (match-string 1))))
2059 (type (and (string-match org-link-types-re raw
)
2060 (match-string 1 raw
))))
2062 ((not type
) (expand-file-name raw
))
2063 ((string= type
"file")
2064 (and (string-match "file\\(.*\\):\\(.+\\)" raw
)
2065 (expand-file-name (match-string 2 raw
))))
2068 (defun org-babel-format-result (result &optional sep
)
2069 "Format RESULT for writing to file."
2070 (let ((echo-res (lambda (r) (if (stringp r
) r
(format "%S" r
)))))
2074 result
(list :sep
(or sep
"\t") :fmt echo-res
))
2076 (funcall echo-res result
))))
2078 (defun org-babel-insert-result (result &optional result-params info hash lang
)
2079 "Insert RESULT into the current buffer.
2081 By default RESULT is inserted after the end of the current source
2082 block. The RESULT of an inline source block usually will be
2083 wrapped inside a `results' macro and placed on the same line as
2084 the inline source block. The macro is stripped upon export.
2085 Multiline and non-scalar RESULTS from inline source blocks are
2086 not allowed. With optional argument RESULT-PARAMS controls
2087 insertion of results in the Org mode file. RESULT-PARAMS can
2088 take the following values:
2090 replace - (default option) insert results after the source block
2091 or inline source block replacing any previously
2094 silent -- no results are inserted into the Org buffer but
2095 the results are echoed to the minibuffer and are
2096 ingested by Emacs (a potentially time consuming
2099 file ---- the results are interpreted as a file path, and are
2100 inserted into the buffer using the Org file syntax.
2102 list ---- the results are interpreted as an Org list.
2104 raw ----- results are added directly to the Org file. This is
2105 a good option if you code block will output Org
2108 drawer -- results are added directly to the Org file as with
2109 \"raw\", but are wrapped in a RESULTS drawer or results
2110 macro, allowing them to later be replaced or removed
2113 org ----- results are added inside of a \"src_org{}\" or \"#+BEGIN_SRC
2114 org\" block depending on whether the current source block is
2115 inline or not. They are not comma-escaped when inserted,
2116 but Org syntax here will be discarded when exporting the
2119 html ---- results are added inside of a #+BEGIN_EXPORT HTML block
2120 or html export snippet depending on whether the current
2121 source block is inline or not. This is a good option
2122 if your code block will output html formatted text.
2124 latex --- results are added inside of a #+BEGIN_EXPORT LATEX
2125 block or latex export snippet depending on whether the
2126 current source block is inline or not. This is a good
2127 option if your code block will output latex formatted
2130 code ---- the results are extracted in the syntax of the source
2131 code of the language being evaluated and are added
2132 inside of a source block with the source-code language
2133 set appropriately. Also, source block inlining is
2134 preserved in this case. Note this relies on the
2135 optional LANG argument.
2137 list ---- the results are rendered as a list. This option not
2138 allowed for inline src blocks.
2140 table --- the results are rendered as a table. This option not
2141 allowed for inline src blocks.
2143 INFO may provide the values of these header arguments (in the
2144 `header-arguments-alist' see the docstring for
2145 `org-babel-get-src-block-info'):
2147 :file --- the name of the file to which output should be written.
2149 :wrap --- the effect is similar to `latex' in RESULT-PARAMS but
2150 using the argument supplied to specify the export block
2152 (cond ((stringp result
)
2153 (setq result
(org-no-properties result
))
2154 (when (member "file" result-params
)
2155 (setq result
(org-babel-result-to-file
2156 result
(when (assq :file-desc
(nth 2 info
))
2157 (or (cdr (assq :file-desc
(nth 2 info
)))
2160 (t (setq result
(format "%S" result
))))
2161 (if (and result-params
(member "silent" result-params
))
2162 (progn (message (replace-regexp-in-string "%" "%%" (format "%S" result
)))
2164 (let ((inline (let ((context (org-element-context)))
2165 (and (memq (org-element-type context
)
2166 '(inline-babel-call inline-src-block
))
2170 (or (and (member "table" result-params
) "`:results table'")
2171 (and (listp result
) "list result")
2172 (and (string-match-p "\n." result
) "multiline result")
2173 (and (member "list" result-params
) "`:results list'"))))
2175 (user-error "Inline error: %s cannot be used" warning
))))
2177 (let* ((visible-beg (point-min-marker))
2178 (visible-end (copy-marker (point-max) t
))
2179 (inline (let ((context (org-element-context)))
2180 (and (memq (org-element-type context
)
2181 '(inline-babel-call inline-src-block
))
2183 (existing-result (org-babel-where-is-src-block-result t nil hash
))
2184 (results-switches (cdr (assq :results_switches
(nth 2 info
))))
2185 ;; When results exist outside of the current visible
2186 ;; region of the buffer, be sure to widen buffer to
2188 (outside-scope (and existing-result
2190 (or (> visible-beg existing-result
)
2191 (<= visible-end existing-result
))))
2193 ;; Ensure non-inline results end in a newline.
2194 (when (and (org-string-nw-p result
)
2196 (not (string-equal (substring result -
1) "\n")))
2197 (setq result
(concat result
"\n")))
2200 (when outside-scope
(widen))
2201 (if existing-result
(goto-char existing-result
)
2202 (goto-char (org-element-property :end inline
))
2203 (skip-chars-backward " \t"))
2205 (setq indent
(org-get-indentation))
2210 ;; Make sure new results are separated from the
2211 ;; source code by one space.
2212 (unless existing-result
2214 (setq beg
(point))))
2215 ((member "replace" result-params
)
2216 (delete-region (point) (org-babel-result-end)))
2217 ((member "append" result-params
)
2218 (goto-char (org-babel-result-end)) (setq beg
(point-marker)))
2219 ((member "prepend" result-params
))) ; already there
2220 (setq results-switches
2221 (if results-switches
(concat " " results-switches
) ""))
2222 (let ((wrap (lambda (start finish
&optional no-escape no-newlines
2223 inline-start inline-finish
)
2225 (setq start inline-start
)
2226 (setq finish inline-finish
)
2227 (setq no-newlines t
))
2229 (insert (concat finish
(unless no-newlines
"\n")))
2231 (insert (concat start
(unless no-newlines
"\n")))
2233 (org-escape-code-in-region (min (point) end
) end
))
2235 (unless no-newlines
(goto-char (point-at-eol)))
2236 (setq end
(point-marker))))
2239 ;; Non-nil when result R can be turned into
2242 (null (cdr (last r
)))
2244 (lambda (e) (or (atom e
) (null (cdr (last e
)))))
2246 ;; insert results based on type
2248 ;; Do nothing for an empty result.
2250 ;; Insert a list if preferred.
2251 ((member "list" result-params
)
2254 (org-list-to-generic
2258 (list (if (stringp e
) e
(format "%S" e
))))
2259 (if (listp result
) result
2260 (split-string result
"\n" t
))))
2261 '(:splicep nil
:istart
"- " :iend
"\n")))
2263 ;; Try hard to print RESULT as a table. Give up if
2264 ;; it contains an improper list.
2265 ((funcall tabulablep result
)
2267 (insert (concat (orgtbl-to-orgtbl
2270 (or (eq e
'hline
) (listp e
)))
2277 (when (org-at-table-p) (org-table-align))
2278 (goto-char (org-table-end)))
2279 ;; Print verbatim a list that cannot be turned into
2281 ((listp result
) (insert (format "%s\n" result
)))
2282 ((member "file" result-params
)
2284 (setq result
(org-macro-escape-arguments result
)))
2286 ((and inline
(not (member "raw" result-params
)))
2287 (insert (org-macro-escape-arguments
2288 (org-babel-chomp result
"\n"))))
2289 (t (goto-char beg
) (insert result
)))
2290 (setq end
(point-marker))
2291 ;; possibly wrap result
2293 ((assq :wrap
(nth 2 info
))
2294 (let ((name (or (cdr (assq :wrap
(nth 2 info
))) "RESULTS")))
2295 (funcall wrap
(concat "#+BEGIN_" name
)
2296 (concat "#+END_" (car (org-split-string name
)))
2297 nil nil
(concat "{{{results(@@" name
":") "@@)}}}")))
2298 ((member "html" result-params
)
2299 (funcall wrap
"#+BEGIN_EXPORT html" "#+END_EXPORT" nil nil
2300 "{{{results(@@html:" "@@)}}}"))
2301 ((member "latex" result-params
)
2302 (funcall wrap
"#+BEGIN_EXPORT latex" "#+END_EXPORT" nil nil
2303 "{{{results(@@latex:" "@@)}}}"))
2304 ((member "org" result-params
)
2305 (goto-char beg
) (when (org-at-table-p) (org-cycle))
2306 (funcall wrap
"#+BEGIN_SRC org" "#+END_SRC" nil nil
2307 "{{{results(src_org{" "})}}}"))
2308 ((member "code" result-params
)
2309 (let ((lang (or lang
"none")))
2310 (funcall wrap
(format "#+BEGIN_SRC %s%s" lang results-switches
)
2312 (format "{{{results(src_%s[%s]{" lang results-switches
)
2314 ((member "raw" result-params
)
2315 (goto-char beg
) (when (org-at-table-p) (org-cycle)))
2316 ((or (member "drawer" result-params
)
2317 ;; Stay backward compatible with <7.9.2
2318 (member "wrap" result-params
))
2319 (goto-char beg
) (when (org-at-table-p) (org-cycle))
2320 (funcall wrap
":RESULTS:" ":END:" 'no-escape nil
2321 "{{{results(" ")}}}"))
2322 ((and inline
(member "file" result-params
))
2323 (funcall wrap nil nil nil nil
"{{{results(" ")}}}"))
2324 ((and (not (funcall tabulablep result
))
2325 (not (member "file" result-params
)))
2326 (let ((org-babel-inline-result-wrap
2327 ;; Hard code {{{results(...)}}} on top of customization.
2328 (format "{{{results(%s)}}}"
2329 org-babel-inline-result-wrap
)))
2330 (org-babel-examplify-region beg end results-switches inline
)
2331 (setq end
(point))))))
2332 ;; Possibly indent results in par with #+results line.
2333 (when (and (not inline
) (numberp indent
) (> indent
0)
2334 ;; In this case `table-align' does the work
2336 (not (and (listp result
)
2337 (member "append" result-params
))))
2338 (indent-rigidly beg end indent
))
2340 (if (member "value" result-params
)
2341 (message "Code block returned no value.")
2342 (message "Code block produced no output."))
2343 (message "Code block evaluation complete.")))
2344 (when outside-scope
(narrow-to-region visible-beg visible-end
))
2345 (set-marker visible-beg nil
)
2346 (set-marker visible-end nil
)))))))
2348 (defun org-babel-remove-result (&optional info keep-keyword
)
2349 "Remove the result of the current source block."
2351 (let ((location (org-babel-where-is-src-block-result nil info
)))
2354 (goto-char location
)
2355 (when (looking-at (concat org-babel-result-regexp
".*$"))
2357 (if keep-keyword
(1+ (match-end 0)) (1- (match-beginning 0)))
2358 (progn (forward-line 1) (org-babel-result-end))))))))
2360 (defun org-babel-remove-inline-result (&optional datum
)
2361 "Remove the result of the current inline-src-block or babel call.
2362 The result must be wrapped in a `results' macro to be removed.
2363 Leading white space is trimmed."
2365 (let* ((el (or datum
(org-element-context))))
2366 (when (memq (org-element-type el
) '(inline-src-block inline-babel-call
))
2367 (org-with-wide-buffer
2368 (goto-char (org-element-property :end el
))
2369 (skip-chars-backward " \t")
2370 (let ((result (save-excursion
2373 (org-element-property
2374 :contents-end
(org-element-property :parent el
)))
2375 (org-element-context))))
2376 (when (and (eq (org-element-type result
) 'macro
)
2377 (string= (org-element-property :key result
) "results"))
2378 (delete-region ; And leading whitespace.
2380 (progn (goto-char (org-element-property :end result
))
2381 (skip-chars-backward " \t\n")
2384 (defun org-babel-remove-result-one-or-many (x)
2385 "Remove the result of the current source block.
2386 If called with a prefix argument, remove all result blocks
2390 (org-babel-map-src-blocks nil
(org-babel-remove-result))
2391 (org-babel-remove-result)))
2393 (defun org-babel-result-end ()
2394 "Return the point at the end of the current set of results."
2397 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
2398 ((org-at-item-p) (let* ((struct (org-list-struct))
2399 (prvs (org-list-prevs-alist struct
)))
2400 (org-list-get-list-end (point-at-bol) struct prvs
)))
2401 ((let ((case-fold-search t
)) (looking-at "^\\([ \t]*\\):results:"))
2402 (progn (re-search-forward (concat "^" (match-string 1) ":END:"))
2403 (forward-char 1) (point)))
2405 (let ((case-fold-search t
))
2406 (if (looking-at (concat "[ \t]*#\\+begin_\\([^ \t\n\r]+\\)"))
2407 (progn (re-search-forward (concat "[ \t]*#\\+end_" (match-string 1))
2410 (while (looking-at "[ \t]*\\(: \\|:$\\|\\[\\[\\)")
2414 (defun org-babel-result-to-file (result &optional description
)
2415 "Convert RESULT into an `org-mode' link with optional DESCRIPTION.
2416 If the `default-directory' is different from the containing
2417 file's directory then expand relative links."
2418 (when (stringp result
)
2419 (format "[[file:%s]%s]"
2420 (if (and default-directory
2422 (not (string= (expand-file-name default-directory
)
2424 (file-name-directory buffer-file-name
)))))
2425 (expand-file-name result default-directory
)
2427 (if description
(concat "[" description
"]") ""))))
2429 (defvar org-babel-capitalize-example-region-markers nil
2430 "Make true to capitalize begin/end example markers inserted by code blocks.")
2432 (defun org-babel-examplify-region (beg end
&optional results-switches inline
)
2433 "Comment out region using the inline `==' or `: ' org example quote."
2437 (if org-babel-capitalize-example-region-markers
(upcase str
) str
))))
2441 (insert (format org-babel-inline-result-wrap
2442 (delete-and-extract-region beg end
))))
2443 (let ((size (count-lines beg end
)))
2445 (cond ((= size
0)) ; do nothing for an empty result
2446 ((< size org-babel-min-lines-for-block-output
)
2449 (beginning-of-line 1) (insert ": ") (forward-line 1)))
2452 (insert (if results-switches
2454 (funcall maybe-cap
"#+begin_example")
2456 (funcall maybe-cap
"#+begin_example\n")))
2457 (if (markerp end
) (goto-char end
) (forward-char (- end beg
)))
2458 (insert (funcall maybe-cap
"#+end_example\n")))))))))
2460 (defun org-babel-update-block-body (new-body)
2461 "Update the body of the current code block to NEW-BODY."
2462 (let ((element (org-element-at-point)))
2463 (unless (eq (org-element-type element
) 'src-block
)
2464 (error "Not in a source block"))
2465 (goto-char (org-babel-where-is-src-block-head element
))
2466 (let* ((ind (org-get-indentation))
2467 (body-start (line-beginning-position 2))
2468 (body (org-element-normalize-string
2469 (if (or org-src-preserve-indentation
2470 (org-element-property :preserve-indent element
))
2473 (insert (org-remove-indentation new-body
))
2477 (+ ind org-edit-src-content-indentation
))
2478 (buffer-string))))))
2479 (delete-region body-start
2480 (org-with-wide-buffer
2481 (goto-char (org-element-property :end element
))
2482 (skip-chars-backward " \t\n")
2483 (line-beginning-position)))
2484 (goto-char body-start
)
2487 (defun org-babel-merge-params (&rest plists
)
2488 "Combine all parameter association lists in PLISTS.
2489 Later elements of PLISTS override the values of previous elements.
2490 This takes into account some special considerations for certain
2491 parameters when merging lists."
2492 (let* ((results-exclusive-groups
2493 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2494 (cdr (assq 'results org-babel-common-header-args-w-values
))))
2495 (exports-exclusive-groups
2496 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2497 (cdr (assq 'exports org-babel-common-header-args-w-values
))))
2499 (lambda (exclusive-groups &rest result-params
)
2500 ;; Maintain exclusivity of mutually exclusive parameters,
2501 ;; as defined in EXCLUSIVE-GROUPS while merging lists in
2504 (dolist (new-params result-params
(delete-dups output
))
2505 (dolist (new-param new-params
)
2506 (dolist (exclusive-group exclusive-groups
)
2507 (when (member new-param exclusive-group
)
2508 (setq output
(cl-remove-if
2509 (lambda (o) (member o exclusive-group
))
2511 (push new-param output
))))))
2512 (variable-index 0) ;Handle positional arguments.
2514 params
;Final parameters list.
2515 ;; Some keywords accept multiple values. We need to treat
2517 vars results exports
)
2518 (dolist (plist plists
)
2519 (dolist (pair plist
)
2523 ((listp value
) (car value
))
2524 ((string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*=" value
)
2525 (intern (match-string 1 value
)))
2530 (append (if (not (assoc name vars
)) vars
2531 (push name clearnames
)
2532 (cl-remove-if (lambda (p) (equal name
(car p
)))
2534 (list (cons name pair
)))))
2535 ((and vars
(nth variable-index vars
))
2536 ;; If no name is given and we already have named
2537 ;; variables then assign to named variables in order.
2538 (let ((name (car (nth variable-index vars
))))
2539 ;; Clear out colnames and rownames for replace vars.
2540 (push name clearnames
)
2541 (setf (cddr (nth variable-index vars
))
2542 (concat (symbol-name name
) "=" value
))
2543 (cl-incf variable-index
)))
2544 (t (error "Variable \"%s\" must be assigned a default value"
2546 (`(:results .
,value
)
2547 (setq results
(funcall merge
2548 results-exclusive-groups
2551 (if (stringp value
) value
(eval value t
))))))
2552 (`(,(or :file
:file-ext
) .
,value
)
2553 ;; `:file' and `:file-ext' are regular keywords but they
2554 ;; imply a "file" `:results' and a "results" `:exports'.
2557 (funcall merge results-exclusive-groups results
'("file")))
2558 (unless (or (member "both" exports
)
2559 (member "none" exports
)
2560 (member "code" exports
))
2563 exports-exclusive-groups exports
'("results"))))
2564 (push pair params
)))
2565 (`(:exports .
,value
)
2566 (setq exports
(funcall merge
2567 exports-exclusive-groups
2569 (split-string (or value
"")))))
2570 ;; Regular keywords: any value overwrites the previous one.
2571 (_ (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))))
2572 ;; Handle `:var' and clear out colnames and rownames for replaced
2574 (setq params
(nconc (mapcar (lambda (v) (cons :var
(cddr v
))) vars
)
2576 (dolist (name clearnames
)
2577 (dolist (param '(:colname-names
:rowname-names
))
2578 (when (assq param params
)
2579 (setf (cdr (assq param params
))
2580 (cl-remove-if (lambda (pair) (equal name
(car pair
)))
2581 (cdr (assq param params
))))
2583 (cl-remove-if (lambda (pair) (and (equal (car pair
) param
)
2586 ;; Handle other special keywords, which accept multiple values.
2587 (setq params
(nconc (list (cons :results
(mapconcat #'identity results
" "))
2588 (cons :exports
(mapconcat #'identity exports
" ")))
2590 ;; Return merged params.
2593 (defvar org-babel-use-quick-and-dirty-noweb-expansion nil
2594 "Set to true to use regular expressions to expand noweb references.
2595 This results in much faster noweb reference expansion but does
2596 not properly allow code blocks to inherit the \":noweb-ref\"
2597 header argument from buffer or subtree wide properties.")
2599 (defun org-babel-noweb-p (params context
)
2600 "Check if PARAMS require expansion in CONTEXT.
2601 CONTEXT may be one of :tangle, :export or :eval."
2602 (let ((allowed-values (cl-case context
2603 (:tangle
'("yes" "tangle" "no-export" "strip-export"))
2604 (:eval
'("yes" "no-export" "strip-export" "eval"))
2605 (:export
'("yes")))))
2606 (cl-some (lambda (v) (member v allowed-values
))
2607 (split-string (or (cdr (assq :noweb params
)) "")))))
2609 (defun org-babel-expand-noweb-references (&optional info parent-buffer
)
2610 "Expand Noweb references in the body of the current source code block.
2612 For example the following reference would be replaced with the
2613 body of the source-code block named `example-block'.
2617 Note that any text preceding the <<foo>> construct on a line will
2618 be interposed between the lines of the replacement text. So for
2619 example if <<foo>> is placed behind a comment, then the entire
2620 replacement text will also be commented.
2622 This function must be called from inside of the buffer containing
2623 the source-code block which holds BODY.
2625 In addition the following syntax can be used to insert the
2626 results of evaluating the source-code block named `example-block'.
2630 Any optional arguments can be passed to example-block by placing
2631 the arguments inside the parenthesis following the convention
2632 defined by `org-babel-lob'. For example
2634 <<example-block(a=9)>>
2636 would set the value of argument \"a\" equal to \"9\". Note that
2637 these arguments are not evaluated in the current source-code
2638 block but are passed literally to the \"example-block\"."
2639 (let* ((parent-buffer (or parent-buffer
(current-buffer)))
2640 (info (or info
(org-babel-get-src-block-info 'light
)))
2643 (ob-nww-start org-babel-noweb-wrap-start
)
2644 (ob-nww-end org-babel-noweb-wrap-end
)
2645 (comment (string= "noweb" (cdr (assq :comments
(nth 2 info
)))))
2646 (rx-prefix (concat "\\(" org-babel-src-name-regexp
"\\|"
2647 ":noweb-ref[ \t]+" "\\)"))
2649 (nb-add (lambda (text) (setq new-body
(concat new-body text
))))
2650 (c-wrap (lambda (text)
2652 (funcall (intern (concat lang
"-mode")))
2653 (comment-region (point) (progn (insert text
) (point)))
2654 (org-trim (buffer-string)))))
2655 index source-name evaluate prefix
)
2657 (setq-local org-babel-noweb-wrap-start ob-nww-start
)
2658 (setq-local org-babel-noweb-wrap-end ob-nww-end
)
2659 (insert body
) (goto-char (point-min))
2660 (setq index
(point))
2661 (while (and (re-search-forward (org-babel-noweb-wrap) nil t
))
2662 (save-match-data (setf source-name
(match-string 1)))
2663 (save-match-data (setq evaluate
(string-match "(.*)" source-name
)))
2666 (buffer-substring (match-beginning 0)
2668 (beginning-of-line 1) (point)))))
2669 ;; add interval to new-body (removing noweb reference)
2670 (goto-char (match-beginning 0))
2671 (funcall nb-add
(buffer-substring index
(point)))
2672 (goto-char (match-end 0))
2673 (setq index
(point))
2676 (with-current-buffer parent-buffer
2679 (mapconcat ;; Interpose PREFIX between every line.
2683 (let ((raw (org-babel-ref-resolve source-name
)))
2684 (if (stringp raw
) raw
(format "%S" raw
)))
2686 ;; Retrieve from the library of babel.
2687 (nth 2 (assoc (intern source-name
)
2688 org-babel-library-of-babel
))
2689 ;; Return the contents of headlines literally.
2691 (when (org-babel-ref-goto-headline-id source-name
)
2692 (org-babel-ref-headline-body)))
2693 ;; Find the expansion of reference in this buffer.
2694 (let ((rx (concat rx-prefix source-name
"[ \t\n]"))
2697 (goto-char (point-min))
2698 (if org-babel-use-quick-and-dirty-noweb-expansion
2699 (while (re-search-forward rx nil t
)
2700 (let* ((i (org-babel-get-src-block-info 'light
))
2701 (body (org-babel-expand-noweb-references i
))
2702 (sep (or (cdr (assq :noweb-sep
(nth 2 i
)))
2705 (let ((cs (org-babel-tangle-comment-links i
)))
2706 (concat (funcall c-wrap
(car cs
)) "\n"
2708 (funcall c-wrap
(cadr cs
))))
2710 (setq expansion
(cons sep
(cons full expansion
)))))
2711 (org-babel-map-src-blocks nil
2712 (let ((i (org-babel-get-src-block-info 'light
)))
2713 (when (equal (or (cdr (assq :noweb-ref
(nth 2 i
)))
2716 (let* ((body (org-babel-expand-noweb-references i
))
2717 (sep (or (cdr (assq :noweb-sep
(nth 2 i
)))
2720 (let ((cs (org-babel-tangle-comment-links i
)))
2721 (concat (funcall c-wrap
(car cs
)) "\n"
2723 (funcall c-wrap
(cadr cs
))))
2726 (cons sep
(cons full expansion
)))))))))
2728 (mapconcat #'identity
(nreverse (cdr expansion
)) "")))
2729 ;; Possibly raise an error if named block doesn't exist.
2730 (if (or org-babel-noweb-error-all-langs
2731 (member lang org-babel-noweb-error-langs
))
2733 (org-babel-noweb-wrap source-name
)
2734 "could not be resolved (see "
2735 "`org-babel-noweb-error-langs')"))
2737 "[\n\r]") (concat "\n" prefix
))))))
2738 (funcall nb-add
(buffer-substring index
(point-max))))
2741 (defun org-babel--script-escape-inner (str)
2742 (let (in-single in-double backslash out
)
2749 (setq backslash nil
)
2751 ((and in-single
(eq ch ?
'))
2752 ;; Escaped single quote inside single quoted string:
2753 ;; emit just a single quote, since we've changed the
2754 ;; outer quotes to double.
2757 ;; Escaped double quote
2759 ;; This should be interpreted as backslash+quote,
2760 ;; not an escape. Emit a three backslashes
2761 ;; followed by a quote (because one layer of
2762 ;; quoting will be stripped by `org-babel-read').
2763 (append (list ch ?
\\ ?
\\ ?
\\) out
)
2764 ;; Otherwise we are in a double-quoted string. Emit
2765 ;; a single escaped quote
2766 (append (list ch ?
\\) out
)))
2768 ;; Escaped backslash: emit a single escaped backslash
2769 (append (list ?
\\ ?
\\) out
))
2770 ;; Other: emit a quoted backslash followed by whatever
2771 ;; the character was (because one layer of quoting will
2772 ;; be stripped by `org-babel-read').
2773 (t (append (list ch ?
\\ ?
\\) out
))))
2775 (?\
[ (if (or in-double in-single
)
2778 (?\
] (if (or in-double in-single
)
2781 (?\
{ (if (or in-double in-single
)
2784 (?\
} (if (or in-double in-single
)
2787 (?
, (if (or in-double in-single
)
2788 (cons ?
, out
) (cons ?\s out
)))
2791 (setq in-single
(not in-single
)) (cons ?
\" out
)))
2793 (append (list ?
\" ?
\\) out
)
2794 (setq in-double
(not in-double
)) (cons ?
\" out
)))
2795 (?
\\ (unless (or in-single in-double
)
2796 (error "Can't handle backslash outside string in `org-babel-script-escape'"))
2799 (t (cons ch out
))))))
2800 (string-to-list str
))
2801 (when (or in-single in-double
)
2802 (error "Unterminated string in `org-babel-script-escape'"))
2803 (apply #'string
(reverse out
))))
2805 (defun org-babel-script-escape (str &optional force
)
2806 "Safely convert tables into elisp lists."
2807 (unless (stringp str
)
2808 (error "`org-babel-script-escape' expects a string"))
2811 ((and (> (length str
) 2)
2812 (or (and (string-equal "[" (substring str
0 1))
2813 (string-equal "]" (substring str -
1)))
2814 (and (string-equal "{" (substring str
0 1))
2815 (string-equal "}" (substring str -
1)))
2816 (and (string-equal "(" (substring str
0 1))
2817 (string-equal ")" (substring str -
1)))))
2819 (concat "'" (org-babel--script-escape-inner str
)))
2821 (and (> (length str
) 2)
2822 (or (and (string-equal "'" (substring str
0 1))
2823 (string-equal "'" (substring str -
1)))
2824 ;; We need to pass double-quoted strings
2825 ;; through the backslash-twiddling bits, even
2826 ;; though we don't need to change their
2828 (and (string-equal "\"" (substring str
0 1))
2829 (string-equal "\"" (substring str -
1))))))
2830 (org-babel--script-escape-inner str
))
2832 (condition-case nil
(org-babel-read escaped
) (error escaped
))))
2834 (defun org-babel-read (cell &optional inhibit-lisp-eval
)
2835 "Convert the string value of CELL to a number if appropriate.
2836 Otherwise if CELL looks like lisp (meaning it starts with a
2837 \"(\", \"\\='\", \"\\=`\" or a \"[\") then read and evaluate it as
2838 lisp, otherwise return it unmodified as a string. Optional
2839 argument INHIBIT-LISP-EVAL inhibits lisp evaluation for
2840 situations in which is it not appropriate."
2841 (if (and (stringp cell
) (not (equal cell
"")))
2842 (or (org-babel--string-to-number cell
)
2843 (if (and (not inhibit-lisp-eval
)
2844 (or (member (substring cell
0 1) '("(" "'" "`" "["))
2845 (string= cell
"*this*")))
2846 (eval (read cell
) t
)
2847 (if (string= (substring cell
0 1) "\"")
2849 (progn (set-text-properties 0 (length cell
) nil cell
) cell
))))
2852 (defun org-babel--string-to-number (string)
2853 "If STRING represents a number return its value.
2855 Otherwise return nil."
2856 (when (string-match "\\`-?[0-9]*\\.?[0-9]*\\'" string
)
2857 (string-to-number string
)))
2858 (define-obsolete-function-alias 'org-babel-number-p
'org-babel--string-to-number
"Org 9.0")
2860 (defun org-babel-import-elisp-from-file (file-name &optional separator
)
2861 "Read the results located at FILE-NAME into an elisp table.
2862 If the table is trivial, then return it as a scalar."
2864 (save-window-excursion
2868 (org-table-import file-name separator
)
2869 (delete-file file-name
)
2870 (setq result
(mapcar (lambda (row)
2871 (mapcar #'org-babel-string-read row
))
2872 (org-table-to-lisp))))
2873 (error (message "Error reading results: %s" err
) nil
)))
2874 (if (null (cdr result
)) ;; if result is trivial vector, then scalarize it
2875 (if (consp (car result
))
2876 (if (null (cdr (car result
)))
2882 (defun org-babel-string-read (cell)
2883 "Strip nested \"s from around strings."
2884 (org-babel-read (or (and (stringp cell
)
2885 (string-match "\\\"\\(.+\\)\\\"" cell
)
2886 (match-string 1 cell
))
2889 (defun org-babel-chomp (string &optional regexp
)
2890 "Strip a trailing space or carriage return from STRING.
2891 The default regexp used is \"[ \\f\\t\\n\\r\\v]\" but another one
2892 can be specified as the REGEXP argument."
2893 (let ((regexp (or regexp
"[ \f\t\n\r\v]")))
2894 (while (and (> (length string
) 0)
2895 (string-match regexp
(substring string -
1)))
2896 (setq string
(substring string
0 -
1)))
2899 (defun org-babel-local-file-name (file)
2900 "Return the local name component of FILE."
2901 (or (file-remote-p file
'localname
) file
))
2903 (defun org-babel-process-file-name (name &optional no-quote-p
)
2904 "Prepare NAME to be used in an external process.
2905 If NAME specifies a remote location, the remote portion of the
2906 name is removed, since in that case the process will be executing
2907 remotely. The file name is then processed by `expand-file-name'.
2908 Unless second argument NO-QUOTE-P is non-nil, the file name is
2909 additionally processed by `shell-quote-argument'"
2910 (let ((f (org-babel-local-file-name (expand-file-name name
))))
2911 (if no-quote-p f
(shell-quote-argument f
))))
2913 (defvar org-babel-temporary-directory
)
2914 (unless (or noninteractive
(boundp 'org-babel-temporary-directory
))
2915 (defvar org-babel-temporary-directory
2916 (or (and (boundp 'org-babel-temporary-directory
)
2917 (file-exists-p org-babel-temporary-directory
)
2918 org-babel-temporary-directory
)
2919 (make-temp-file "babel-" t
))
2920 "Directory to hold temporary files created to execute code blocks.
2921 Used by `org-babel-temp-file'. This directory will be removed on
2924 (defcustom org-babel-remote-temporary-directory
"/tmp/"
2925 "Directory to hold temporary files on remote hosts."
2929 (defmacro org-babel-result-cond
(result-params scalar-form
&rest table-forms
)
2930 "Call the code to parse raw string results according to RESULT-PARAMS."
2932 (debug (form form
&rest form
)))
2933 (org-with-gensyms (params)
2934 `(let ((,params
,result-params
))
2935 (unless (member "none" ,params
)
2936 (if (or (member "scalar" ,params
)
2937 (member "verbatim" ,params
)
2938 (member "html" ,params
)
2939 (member "code" ,params
)
2940 (member "pp" ,params
)
2941 (member "file" ,params
)
2942 (and (or (member "output" ,params
)
2943 (member "raw" ,params
)
2944 (member "org" ,params
)
2945 (member "drawer" ,params
))
2946 (not (member "table" ,params
))))
2949 (def-edebug-spec org-babel-result-cond
(form form body
))
2951 (defun org-babel-temp-file (prefix &optional suffix
)
2952 "Create a temporary file in the `org-babel-temporary-directory'.
2953 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2954 value of `temporary-file-directory' temporarily set to the value
2955 of `org-babel-temporary-directory'."
2956 (if (file-remote-p default-directory
)
2958 (concat (file-remote-p default-directory
)
2960 prefix org-babel-remote-temporary-directory
))))
2961 (make-temp-file prefix nil suffix
))
2962 (let ((temporary-file-directory
2963 (or (and (boundp 'org-babel-temporary-directory
)
2964 (file-exists-p org-babel-temporary-directory
)
2965 org-babel-temporary-directory
)
2966 temporary-file-directory
)))
2967 (make-temp-file prefix nil suffix
))))
2969 (defun org-babel-remove-temporary-directory ()
2970 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2971 (when (and (boundp 'org-babel-temporary-directory
)
2972 (file-exists-p org-babel-temporary-directory
))
2973 ;; taken from `delete-directory' in files.el
2976 (mapc (lambda (file)
2977 ;; This test is equivalent to
2978 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2979 ;; but more efficient
2980 (if (eq t
(car (file-attributes file
)))
2981 (delete-directory file
)
2982 (delete-file file
)))
2983 ;; We do not want to delete "." and "..".
2984 (directory-files org-babel-temporary-directory
'full
2985 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2986 (delete-directory org-babel-temporary-directory
))
2988 (message "Failed to remove temporary Org-babel directory %s"
2989 (if (boundp 'org-babel-temporary-directory
)
2990 org-babel-temporary-directory
2991 "[directory not defined]"))))))
2993 (add-hook 'kill-emacs-hook
'org-babel-remove-temporary-directory
)
2995 (defun org-babel-one-header-arg-safe-p (pair safe-list
)
2996 "Determine if the PAIR is a safe babel header arg according to SAFE-LIST.
2998 For the format of SAFE-LIST, see `org-babel-safe-header-args'."
3000 (keywordp (car pair
))
3001 (stringp (cdr pair
))
3003 (memq (car pair
) safe-list
)
3004 (let ((entry (assq (car pair
) safe-list
)))
3007 (cond ((functionp (cdr entry
))
3008 (funcall (cdr entry
) (cdr pair
)))
3009 ((listp (cdr entry
))
3010 (member (cdr pair
) (cdr entry
)))
3013 (defun org-babel-generate-file-param (src-name params
)
3014 "Calculate the filename for source block results.
3016 The directory is calculated from the :output-dir property of the
3017 source block; if not specified, use the current directory.
3019 If the source block has a #+NAME and the :file parameter does not
3020 contain any period characters, then the :file parameter is
3021 treated as an extension, and the output file name is the
3022 concatenation of the directory (as calculated above), the block
3023 name, a period, and the parameter value as a file extension.
3024 Otherwise, the :file parameter is treated as a full file name,
3025 and the output file name is the directory (as calculated above)
3026 plus the parameter value."
3027 (let* ((file-cons (assq :file params
))
3028 (file-ext-cons (assq :file-ext params
))
3029 (file-ext (cdr-safe file-ext-cons
))
3030 (dir (cdr-safe (assq :output-dir params
)))
3032 ;; create the output-dir if it does not exist
3034 (make-directory dir t
))
3036 ;; :file given; add :output-dir if given
3038 (setcdr file-cons
(concat (file-name-as-directory dir
) (cdr file-cons
))))
3039 ;; :file not given; compute from name and :file-ext if possible
3040 (when (and src-name file-ext
)
3042 (setq fname
(concat (file-name-as-directory (or dir
""))
3043 src-name
"." file-ext
))
3044 (setq fname
(concat src-name
"." file-ext
)))
3045 (setq params
(cons (cons :file fname
) params
))))
3048 (defun org-babel-graphical-output-file (params)
3049 "File where a babel block should send graphical output, per PARAMS.
3050 Return nil if no graphical output is expected. Raise an error if
3051 the output file is ill-defined."
3052 (let ((file (cdr (assq :file params
))))
3053 (cond (file (and (member "graphics" (cdr (assq :result-params params
)))
3055 ((assq :file-ext params
)
3056 (user-error ":file-ext given but no :file generated; did you forget \
3058 (t (user-error "No :file header argument given; cannot create \
3059 graphical result")))))
3061 (defun org-babel-make-language-alias (new old
)
3062 "Make source blocks of type NEW aliases for those of type OLD.
3064 NEW and OLD should be strings. This function should be called
3065 after the babel API for OLD-type source blocks is fully defined.
3067 Callers of this function will probably want to add an entry to
3068 `org-src-lang-modes' as well."
3069 (dolist (fn '("execute" "expand-body" "prep-session"
3070 "variable-assignments" "load-session"))
3071 (let ((sym (intern-soft (concat "org-babel-" fn
":" old
))))
3072 (when (and sym
(fboundp sym
))
3073 (defalias (intern (concat "org-babel-" fn
":" new
)) sym
))))
3074 ;; Technically we don't need a `dolist' for just one variable, but
3075 ;; we keep it for symmetry/ease of future expansion.
3076 (dolist (var '("default-header-args"))
3077 (let ((sym (intern-soft (concat "org-babel-" var
":" old
))))
3078 (when (and sym
(boundp sym
))
3079 (defvaralias (intern (concat "org-babel-" var
":" new
)) sym
)))))
3081 (defun org-babel-strip-quotes (string)
3082 "Strip \\\"s from around a string, if applicable."
3083 (org-unbracket-string "\"" "\"" string
))
3088 ;; generated-autoload-file: "org-loaddefs.el"
3091 ;;; ob-core.el ends here