1 ;;; ob-core.el --- working with code blocks in org-mode
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/>.
33 (defconst org-babel-exeext
34 (if (memq system-type
'(windows-nt cygwin
))
38 (defvar org-babel-library-of-babel
)
39 (defvar org-edit-src-content-indentation
)
40 (defvar org-src-lang-modes
)
41 (defvar org-src-preserve-indentation
)
43 (declare-function outline-show-all
"outline" ())
44 (declare-function org-get-indentation
"org" (&optional line
))
45 (declare-function org-remove-indentation
"org" (code &optional n
))
46 (declare-function org-mark-ring-push
"org" (&optional pos buffer
))
47 (declare-function tramp-compat-make-temp-file
"tramp-compat"
48 (filename &optional dir-flag
))
49 (declare-function tramp-dissect-file-name
"tramp" (name &optional nodefault
))
50 (declare-function tramp-file-name-user
"tramp" (vec))
51 (declare-function tramp-file-name-host
"tramp" (vec))
52 (declare-function with-parsed-tramp-file-name
"tramp" (filename var
&rest body
))
53 (declare-function org-edit-src-code
"org-src" (&optional code edit-buffer-name
))
54 (declare-function org-edit-src-exit
"org-src" ())
55 (declare-function org-get-indentation
"org" (&optional line
))
56 (declare-function org-in-regexp
"org" (regexp &optional nlines visually
))
57 (declare-function org-open-at-point
"org" (&optional in-emacs reference-buffer
))
58 (declare-function org-save-outline-visibility
"org-macs" (use-markers &rest body
))
59 (declare-function org-outline-overlay-data
"org" (&optional use-markers
))
60 (declare-function org-set-outline-overlay-data
"org" (data))
61 (declare-function org-narrow-to-subtree
"org" ())
62 (declare-function org-split-string
"org" (string &optional separators
))
63 (declare-function org-entry-get
"org"
64 (pom property
&optional inherit literal-nil
))
65 (declare-function org-indent-line
"org" ())
66 (declare-function org-make-options-regexp
"org" (kwds &optional extra
))
67 (declare-function org-do-remove-indentation
"org" (&optional n
))
68 (declare-function org-next-block
"org" (arg &optional backward block-regexp
))
69 (declare-function org-previous-block
"org" (arg &optional block-regexp
))
70 (declare-function org-show-context
"org" (&optional key
))
71 (declare-function org-at-table-p
"org" (&optional table-type
))
72 (declare-function org-cycle
"org" (&optional arg
))
73 (declare-function org-uniquify
"org" (list))
74 (declare-function org-current-level
"org" ())
75 (declare-function org-table-import
"org-table" (file arg
))
76 (declare-function org-add-hook
"org-compat"
77 (hook function
&optional append local
))
78 (declare-function org-table-align
"org-table" ())
79 (declare-function org-table-end
"org-table" (&optional table-type
))
80 (declare-function orgtbl-to-generic
"org-table" (table params
))
81 (declare-function orgtbl-to-orgtbl
"org-table" (table params
))
82 (declare-function org-babel-tangle-comment-links
"ob-tangle" (&optional info
))
83 (declare-function org-babel-ref-split-args
"ob-ref" (arg-string))
84 (declare-function org-babel-ref-parse
"ob-ref" (assignment))
85 (declare-function org-babel-ref-resolve
"ob-ref" (ref))
86 (declare-function org-babel-ref-goto-headline-id
"ob-ref" (id))
87 (declare-function org-babel-ref-headline-body
"ob-ref" ())
88 (declare-function org-babel-lob-execute-maybe
"ob-lob" ())
89 (declare-function org-number-sequence
"org-compat" (from &optional to inc
))
90 (declare-function org-at-item-p
"org-list" ())
91 (declare-function org-list-to-generic
"org-list" (LIST PARAMS
))
92 (declare-function org-list-to-lisp
"org-list" (&optional delete
))
93 (declare-function org-list-struct
"org-list" ())
94 (declare-function org-list-prevs-alist
"org-list" (struct))
95 (declare-function org-list-get-list-end
"org-list" (item struct prevs
))
96 (declare-function org-completing-read
"org" (&rest args
))
97 (declare-function org-escape-code-in-region
"org-src" (beg end
))
98 (declare-function org-unescape-code-in-string
"org-src" (s))
99 (declare-function org-table-to-lisp
"org-table" (&optional txt
))
100 (declare-function org-reverse-string
"org" (string))
101 (declare-function org-element-context
"org-element" (&optional element
))
102 (declare-function org-element-type
"org-element" (element))
103 (declare-function org-element-at-point
"org-element" ())
104 (declare-function org-element-normalize-string
"org-element" (s))
105 (declare-function org-element-property
"org-element" (property element
))
106 (declare-function org-macro-escape-arguments
"org-macro" (&rest args
))
108 (defgroup org-babel nil
109 "Code block evaluation and management in `org-mode' documents."
113 (defcustom org-confirm-babel-evaluate t
114 "Confirm before evaluation.
116 Require confirmation before interactively evaluating code
117 blocks in Org-mode buffers. The default value of this variable
118 is t, meaning confirmation is required for any code block
119 evaluation. This variable can be set to nil to inhibit any
120 future confirmation requests. This variable can also be set to a
121 function which takes two arguments the language of the code block
122 and the body of the code block. Such a function should then
123 return a non-nil value if the user should be prompted for
124 execution or nil if no prompt is required.
126 Warning: Disabling confirmation may result in accidental
127 evaluation of potentially harmful code. It may be advisable
128 remove code block execution from \\[org-ctrl-c-ctrl-c] \
129 as further protection
130 against accidental code block evaluation. The
131 `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
132 remove code block execution from the \\[org-ctrl-c-ctrl-c] keybinding."
135 :type
'(choice boolean function
))
136 ;; don't allow this variable to be changed through file settings
137 (put 'org-confirm-babel-evaluate
'safe-local-variable
(lambda (x) (eq x t
)))
139 (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
141 Remove code block evaluation from the \\[org-ctrl-c-ctrl-c] key binding."
146 (defcustom org-babel-results-keyword
"RESULTS"
147 "Keyword used to name results generated by code blocks.
148 It should be \"RESULTS\". However any capitalization may be
152 :package-version
'(Org .
"8.0")
156 (eq (compare-strings "RESULTS" nil nil v nil nil t
)
159 (defcustom org-babel-noweb-wrap-start
"<<"
160 "String used to begin a noweb reference in a code block.
161 See also `org-babel-noweb-wrap-end'."
165 (defcustom org-babel-noweb-wrap-end
">>"
166 "String used to end a noweb reference in a code block.
167 See also `org-babel-noweb-wrap-start'."
171 (defcustom org-babel-inline-result-wrap
"=%s="
172 "Format string used to wrap inline results.
173 This string must include a \"%s\" which will be replaced by the results."
176 (put 'org-babel-inline-result-wrap
180 (string-match-p "%s" value
))))
182 (defun org-babel-noweb-wrap (&optional regexp
)
183 (concat org-babel-noweb-wrap-start
184 (or regexp
"\\([^ \t\n].+?[^ \t]\\|[^ \t\n]\\)")
185 org-babel-noweb-wrap-end
))
187 (defvar org-babel-src-name-regexp
188 "^[ \t]*#\\+name:[ \t]*"
189 "Regular expression used to match a source name line.")
191 (defvar org-babel-multi-line-header-regexp
192 "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
193 "Regular expression used to match multi-line header arguments.")
195 (defvar org-babel-src-block-regexp
197 ;; (1) indentation (2) lang
198 "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
200 "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
201 ;; (4) header arguments
204 "\\([^\000]*?\n\\)??[ \t]*#\\+end_src")
205 "Regexp used to identify code blocks.")
207 (defun org-babel--get-vars (params)
208 "Return the babel variable assignments in PARAMS.
210 PARAMS is a quasi-alist of header args, whcih may contain
211 multiple entries for the key `:var'. This function returns a
212 list of the cdr of all the `:var' entries."
214 (cl-remove-if-not (lambda (x) (eq (car x
) :var
)) params
)))
216 (defvar org-babel-exp-reference-buffer nil
217 "Buffer containing original contents of the exported buffer.
218 This is used by Babel to resolve references in source blocks.
219 Its value is dynamically bound during export.")
221 (defun org-babel-check-confirm-evaluate (info)
222 "Check whether INFO allows code block evaluation.
224 Returns nil if evaluation is disallowed, t if it is
225 unconditionally allowed, and the symbol `query' if the user
226 should be asked whether to allow evaluation."
227 (let* ((headers (nth 2 info
))
228 (eval (or (cdr (assq :eval headers
))
229 (when (assq :noeval headers
) "no")))
230 (eval-no (member eval
'("no" "never")))
231 (export org-babel-exp-reference-buffer
)
232 (eval-no-export (and export
(member eval
'("no-export" "never-export"))))
233 (noeval (or eval-no eval-no-export
))
234 (query (or (equal eval
"query")
235 (and export
(equal eval
"query-export"))
236 (if (functionp org-confirm-babel-evaluate
)
238 (goto-char (nth 5 info
))
239 (funcall org-confirm-babel-evaluate
240 ;; language, code block body
241 (nth 0 info
) (nth 1 info
)))
242 org-confirm-babel-evaluate
))))
248 (defun org-babel-check-evaluate (info)
249 "Check if code block INFO should be evaluated.
251 Do not query the user, but do display an informative message if
252 evaluation is blocked. Returns non-nil if evaluation is not blocked."
253 (let ((evalp (org-babel-check-confirm-evaluate info
)))
255 (message "Evaluation of this %s code-block%sis disabled."
257 (let ((name (nth 4 info
))) (if name
(format " (%s) " name
) ""))))
260 ;; Dynamically scoped for asynchronous export.
261 (defvar org-babel-confirm-evaluate-answer-no
)
263 (defun org-babel-confirm-evaluate (info)
264 "Confirm evaluation of the code block INFO.
266 This query can also be suppressed by setting the value of
267 `org-confirm-babel-evaluate' to nil, in which case all future
268 interactive code block evaluations will proceed without any
269 confirmation from the user.
271 Note disabling confirmation may result in accidental evaluation
272 of potentially harmful code.
274 The variable `org-babel-confirm-evaluate-answer-no' is used by
275 the async export process, which requires a non-interactive
276 environment, to override this check."
277 (let* ((evalp (org-babel-check-confirm-evaluate info
))
280 (name-string (if name
(format " (%s) " name
) " ")))
285 (and (not (org-bound-and-true-p
286 org-babel-confirm-evaluate-answer-no
))
288 (format "Evaluate this %s code block%son your system? "
291 (message "Evaluation of this %s code-block%sis aborted."
294 (x (error "Unexpected value `%s' from `org-babel-check-confirm-evaluate'" x
)))))
297 (defun org-babel-execute-safely-maybe ()
298 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
299 (org-babel-execute-maybe)))
301 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-execute-safely-maybe
)
304 (defun org-babel-execute-maybe ()
306 (or (org-babel-execute-src-block-maybe)
307 (org-babel-lob-execute-maybe)))
309 (defmacro org-babel-when-in-src-block
(&rest body
)
310 "Execute BODY if point is in a source block and return t.
312 Otherwise do nothing and return nil."
313 `(if (memq (org-element-type (org-element-context))
314 '(inline-src-block src-block
))
320 (defun org-babel-execute-src-block-maybe ()
321 "Conditionally execute a source block.
322 Detect if this is context for a Babel src-block and if so
323 then run `org-babel-execute-src-block'."
325 (org-babel-when-in-src-block
326 (org-babel-eval-wipe-error-buffer)
327 (org-babel-execute-src-block current-prefix-arg
)))
330 (defun org-babel-view-src-block-info ()
331 "Display information on the current source block.
332 This includes header arguments, language and name, and is largely
333 a window into the `org-babel-get-src-block-info' function."
335 (let ((info (org-babel-get-src-block-info 'light
))
336 (full (lambda (it) (> (length it
) 0)))
337 (printf (lambda (fmt &rest args
) (princ (apply #'format fmt args
)))))
339 (with-help-window (help-buffer)
340 (let ((name (nth 4 info
))
342 (switches (nth 3 info
))
343 (header-args (nth 2 info
)))
344 (when name
(funcall printf
"Name: %s\n" name
))
345 (when lang
(funcall printf
"Lang: %s\n" lang
))
346 (funcall printf
"Properties:\n")
347 (funcall printf
"\t:header-args \t%s\n" (org-entry-get (point) "header-args" t
))
348 (funcall printf
"\t:header-args:%s \t%s\n" lang
(org-entry-get (point) (concat "header-args:" lang
) t
))
350 (when (funcall full switches
) (funcall printf
"Switches: %s\n" switches
))
351 (funcall printf
"Header Arguments:\n")
352 (dolist (pair (sort header-args
353 (lambda (a b
) (string< (symbol-name (car a
))
354 (symbol-name (car b
))))))
355 (when (funcall full
(format "%s" (cdr pair
)))
356 (funcall printf
"\t%S%s\t%s\n"
358 (if (> (length (format "%S" (car pair
))) 7) "" "\t")
362 (defun org-babel-expand-src-block-maybe ()
363 "Conditionally expand a source block.
364 Detect if this is context for a org-babel src-block and if so
365 then run `org-babel-expand-src-block'."
367 (org-babel-when-in-src-block
368 (org-babel-expand-src-block current-prefix-arg
)))
371 (defun org-babel-load-in-session-maybe ()
372 "Conditionally load a source block in a session.
373 Detect if this is context for a org-babel src-block and if so
374 then run `org-babel-load-in-session'."
376 (org-babel-when-in-src-block
377 (org-babel-load-in-session current-prefix-arg
)))
379 (add-hook 'org-metaup-hook
'org-babel-load-in-session-maybe
)
382 (defun org-babel-pop-to-session-maybe ()
383 "Conditionally pop to a session.
384 Detect if this is context for a org-babel src-block and if so
385 then run `org-babel-switch-to-session'."
387 (org-babel-when-in-src-block
388 (org-babel-switch-to-session current-prefix-arg
)))
390 (add-hook 'org-metadown-hook
'org-babel-pop-to-session-maybe
)
392 (defconst org-babel-common-header-args-w-values
393 '((cache .
((no yes
)))
395 (colnames .
((nil no yes
)))
396 (comments .
((no link yes org both noweb
)))
398 (eval .
((yes no no-export strip-export never-export eval never
400 (exports .
((code results both none
)))
405 (hlines .
((no yes
)))
406 (mkdirp .
((yes no
)))
409 (noweb .
((yes no tangle no-export strip-export
)))
413 (padline .
((yes no
)))
416 (results .
((file list vector table scalar verbatim
)
417 (raw html latex org code pp drawer
)
418 (replace silent none append prepend
)
420 (rownames .
((no yes
)))
424 (tangle .
((tangle yes no
:any
)))
425 (tangle-mode .
((#o755
#o555
#o444
:any
)))
429 (defconst org-babel-header-arg-names
430 (mapcar #'car org-babel-common-header-args-w-values
)
431 "Common header arguments used by org-babel.
432 Note that individual languages may define their own language
433 specific header arguments as well.")
435 (defconst org-babel-safe-header-args
436 '(:cache
:colnames
:comments
:exports
:epilogue
:hlines
:noeval
437 :noweb
:noweb-ref
:noweb-sep
:padline
:prologue
:rownames
438 :sep
:session
:tangle
:wrap
439 (:eval .
("never" "query"))
440 (:results .
(lambda (str) (not (string-match "file" str
)))))
441 "A list of safe header arguments for babel source blocks.
443 The list can have entries of the following forms:
444 - :ARG -> :ARG is always a safe header arg
445 - (:ARG . (VAL1 VAL2 ...)) -> :ARG is safe as a header arg if it is
446 `equal' to one of the VALs.
447 - (:ARG . FN) -> :ARG is safe as a header arg if the function FN
448 returns non-nil. FN is passed one
449 argument, the value of the header arg
452 (defmacro org-babel-header-args-safe-fn
(safe-list)
453 "Return a function that determines whether a list of header args are safe.
456 \(put \\='org-babel-default-header-args \\='safe-local-variable
457 (org-babel-header-args-safe-p org-babel-safe-header-args)
459 This allows org-babel languages to extend the list of safe values for
460 their `org-babel-default-header-args:foo' variable.
462 For the format of SAFE-LIST, see `org-babel-safe-header-args'."
468 (org-babel-one-header-arg-safe-p pair
,safe-list
)))
471 (defvar org-babel-default-header-args
472 '((:session .
"none") (:results .
"replace") (:exports .
"code")
473 (:cache .
"no") (:noweb .
"no") (:hlines .
"no") (:tangle .
"no"))
474 "Default arguments to use when evaluating a source block.")
475 (put 'org-babel-default-header-args
'safe-local-variable
476 (org-babel-header-args-safe-fn org-babel-safe-header-args
))
478 (defvar org-babel-default-inline-header-args
479 '((:session .
"none") (:results .
"replace")
480 (:exports .
"results") (:hlines .
"yes"))
481 "Default arguments to use when evaluating an inline source block.")
482 (put 'org-babel-default-inline-header-args
'safe-local-variable
483 (org-babel-header-args-safe-fn org-babel-safe-header-args
))
485 (defconst org-babel-name-regexp
486 (format "^[ \t]*#\\+%s:[ \t]*"
487 ;; FIXME: TBLNAME is for backward compatibility.
488 (regexp-opt '("NAME" "TBLNAME")))
489 "Regexp matching a NAME keyword.")
491 (defconst org-babel-result-regexp
492 (format "^[ \t]*#\\+%s\\(?:\\[\\(?:%S\\)?\\([[:alnum:]]+\\)\\]\\)?:[ \t]*"
493 org-babel-results-keyword
494 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>")
495 "Regular expression used to match result lines.
496 If the results are associated with a hash key then the hash will
497 be saved in match group 1.")
499 (defconst org-babel-result-w-name-regexp
500 (concat org-babel-result-regexp
"\\(?9:[^ \t\n\r\v\f]+\\)")
501 "Regexp matching a RESULTS keyword with a name.
502 Name is saved in match group 9.")
504 (defvar org-babel-min-lines-for-block-output
10
505 "The minimum number of lines for block output.
506 If number of lines of output is equal to or exceeds this
507 value, the output is placed in a #+begin_example...#+end_example
508 block. Otherwise the output is marked as literal by inserting
509 colons at the starts of the lines. This variable only takes
510 effect if the :results output option is in effect.")
512 (defvar org-babel-noweb-error-all-langs nil
513 "Raise errors when noweb references don't resolve.
514 Also see `org-babel-noweb-error-langs' to control noweb errors on
515 a language by language bases.")
517 (defvar org-babel-noweb-error-langs nil
518 "Languages for which Babel will raise literate programming errors.
519 List of languages for which errors should be raised when the
520 source code block satisfying a noweb reference in this language
521 can not be resolved. Also see `org-babel-noweb-error-all-langs'
522 to raise errors for all languages.")
524 (defvar org-babel-hash-show
4
525 "Number of initial characters to show of a hidden results hash.")
527 (defvar org-babel-hash-show-time nil
528 "Non-nil means show the time the code block was evaluated in the result hash.")
530 (defvar org-babel-after-execute-hook nil
531 "Hook for functions to be called after `org-babel-execute-src-block'")
533 (defun org-babel-named-src-block-regexp-for-name (&optional name
)
534 "This generates a regexp used to match a src block named NAME.
535 If NAME is nil, match any name. Matched name is then put in
536 match group 9. Other match groups are defined in
537 `org-babel-src-block-regexp'."
538 (concat org-babel-src-name-regexp
539 (concat (if name
(regexp-quote name
) "\\(?9:.*?\\)") "[ \t]*" )
540 "\\(?:\n[ \t]*#\\+\\S-+:.*\\)*?"
542 (substring org-babel-src-block-regexp
1)))
544 (defun org-babel-named-data-regexp-for-name (name)
545 "This generates a regexp used to match data named NAME."
546 (concat org-babel-name-regexp
(regexp-quote name
) "[ \t]*$"))
549 (defvar org-babel-current-src-block-location nil
550 "Marker pointing to the src block currently being executed.
551 This may also point to a call line or an inline code block. If
552 multiple blocks are being executed (e.g., in chained execution
553 through use of the :var header argument) this marker points to
554 the outer-most code block.")
558 (defun org-babel-get-src-block-info (&optional light datum
)
559 "Extract information from a source block or inline source block.
561 Optional argument LIGHT does not resolve remote variable
562 references; a process which could likely result in the execution
563 of other code blocks.
565 By default, consider the block at point. However, when optional
566 argument DATUM is provided, extract information from that parsed
569 Return nil if point is not on a source block. Otherwise, return
570 a list with the following pattern:
572 \(language body header-arguments-alist switches name block-head)"
573 (let* ((datum (or datum
(org-element-context)))
574 (type (org-element-type datum
))
575 (inline (eq type
'inline-src-block
)))
576 (when (memq type
'(inline-src-block src-block
))
577 (let* ((lang (org-element-property :language datum
))
578 (lang-headers (intern
579 (concat "org-babel-default-header-args:" lang
)))
580 (name (org-element-property :name datum
))
584 ;; Normalize contents. In particular, remove spurious
585 ;; indentation and final newline character.
586 (let* ((value (org-element-property :value datum
))
587 (body (if (and (> (length value
) 1)
588 (string-match-p "\n\\'" value
))
589 (substring value
0 -
1)
592 ;; Newline characters and indentation in an
593 ;; inline src-block are not meaningful, since
594 ;; they could come from some paragraph
595 ;; filling. Treat them as a white space.
596 (replace-regexp-in-string "\n[ \t]*" " " body
))
597 ((or org-src-preserve-indentation
598 (org-element-property :preserve-indent datum
))
600 (t (org-remove-indentation body
))))
601 (apply #'org-babel-merge-params
602 (if inline org-babel-default-inline-header-args
603 org-babel-default-header-args
)
604 (and (boundp lang-headers
) (symbol-value lang-headers
))
606 ;; If DATUM is provided, make sure we get node
607 ;; properties applicable to its location within
609 (org-with-wide-buffer
611 (goto-char (org-element-property :begin datum
)))
612 (org-babel-params-from-properties lang
))
613 (mapcar #'org-babel-parse-header-arguments
615 (org-element-property :parameters datum
)
616 (org-element-property :header datum
)))))
617 (or (org-element-property :switches datum
) "")
619 (org-element-property (if inline
:begin
:post-affiliated
)
622 (setf (nth 2 info
) (org-babel-process-params (nth 2 info
))))
623 (setf (nth 2 info
) (org-babel-generate-file-param name
(nth 2 info
)))
627 (defun org-babel-execute-src-block (&optional arg info params
)
628 "Execute the current source code block.
629 Insert the results of execution into the buffer. Source code
630 execution and the collection and formatting of results can be
631 controlled through a variety of header arguments.
633 With prefix argument ARG, force re-execution even if an existing
634 result cached in the buffer would otherwise have been returned.
636 Optionally supply a value for INFO in the form returned by
637 `org-babel-get-src-block-info'.
639 Optionally supply a value for PARAMS which will be merged with
640 the header arguments specified at the front of the source code
643 (let* ((org-babel-current-src-block-location
644 (or org-babel-current-src-block-location
646 (org-babel-where-is-src-block-head)))
647 (info (if info
(copy-tree info
) (org-babel-get-src-block-info))))
648 (cl-callf org-babel-merge-params
(nth 2 info
) params
)
649 (when (org-babel-check-evaluate info
)
650 (cl-callf org-babel-process-params
(nth 2 info
))
651 (let* ((params (nth 2 info
))
652 (cachep (and (not arg
) (cdr (assoc :cache params
))
653 (string= "yes" (cdr (assoc :cache params
)))))
654 (new-hash (when cachep
(org-babel-sha1-hash info
)))
655 (old-hash (when cachep
(org-babel-current-result-hash)))
656 (cache-current-p (and (not arg
) new-hash
657 (equal new-hash old-hash
))))
660 (save-excursion ;; return cached result
661 (goto-char (org-babel-where-is-src-block-result nil info
))
663 (skip-chars-forward " \t")
664 (let ((result (org-babel-read-result)))
665 (message (replace-regexp-in-string
666 "%" "%%" (format "%S" result
)))
668 ((org-babel-confirm-evaluate info
)
669 (let* ((lang (nth 0 info
))
670 (result-params (cdr (assoc :result-params params
)))
671 (body (setf (nth 1 info
)
672 (if (org-babel-noweb-p params
:eval
)
673 (org-babel-expand-noweb-references info
)
675 (dir (cdr (assoc :dir params
)))
677 (or (and dir
(file-name-as-directory (expand-file-name dir
)))
679 (cmd (intern (concat "org-babel-execute:" lang
)))
681 (unless (fboundp cmd
)
682 (error "No org-babel-execute function for %s!" lang
))
683 (message "executing %s code block%s..."
685 (if (nth 4 info
) (format " (%s)" (nth 4 info
)) ""))
686 (if (member "none" result-params
)
688 (funcall cmd body params
)
689 (message "result silenced")
692 (let ((result (funcall cmd body params
)))
693 (if (and (eq (cdr (assoc :result-type params
))
695 (or (member "vector" result-params
)
696 (member "table" result-params
))
697 (not (listp result
)))
698 (list (list result
)) result
)))
699 ;; If non-empty result and :file then write to :file.
700 (when (cdr (assoc :file params
))
702 (with-temp-file (cdr (assoc :file params
))
704 (org-babel-format-result
705 result
(cdr (assoc :sep
(nth 2 info
)))))))
706 (setq result
(cdr (assoc :file params
))))
707 ;; Possibly perform post process provided its appropriate.
708 (when (cdr (assoc :post params
))
709 (let ((*this
* (if (cdr (assoc :file params
))
710 (org-babel-result-to-file
711 (cdr (assoc :file params
))
712 (when (assoc :file-desc params
)
713 (or (cdr (assoc :file-desc params
))
716 (setq result
(org-babel-ref-resolve
717 (cdr (assoc :post params
))))
718 (when (cdr (assoc :file params
))
720 (remove "file" result-params
)))))
721 (org-babel-insert-result
722 result result-params info new-hash lang
))
723 (run-hooks 'org-babel-after-execute-hook
)
726 (defun org-babel-expand-body:generic
(body params
&optional var-lines
)
727 "Expand BODY with PARAMS.
728 Expand a block of code with org-babel according to its header
729 arguments. This generic implementation of body expansion is
730 called for languages which have not defined their own specific
731 org-babel-expand-body:lang function."
732 (let ((pro (cdr (assoc :prologue params
)))
733 (epi (cdr (assoc :epilogue params
))))
734 (mapconcat #'identity
735 (append (when pro
(list pro
))
738 (when epi
(list epi
)))
742 (defun org-babel-expand-src-block (&optional _arg info params
)
743 "Expand the current source code block.
744 Expand according to the source code block's header
745 arguments and pop open the results in a preview buffer."
747 (let* ((info (or info
(org-babel-get-src-block-info)))
749 (params (setf (nth 2 info
)
750 (sort (org-babel-merge-params (nth 2 info
) params
)
751 (lambda (el1 el2
) (string< (symbol-name (car el1
))
752 (symbol-name (car el2
)))))))
753 (body (setf (nth 1 info
)
754 (if (org-babel-noweb-p params
:eval
)
755 (org-babel-expand-noweb-references info
) (nth 1 info
))))
756 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
757 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
760 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
761 (org-babel-expand-body:generic
762 body params
(and (fboundp assignments-cmd
)
763 (funcall assignments-cmd params
))))))
764 (if (org-called-interactively-p 'any
)
766 expanded
(concat "*Org-Babel Preview " (buffer-name) "[ " lang
" ]*"))
769 (defun org-babel-edit-distance (s1 s2
)
770 "Return the edit (levenshtein) distance between strings S1 S2."
771 (let* ((l1 (length s1
))
773 (dist (vconcat (mapcar (lambda (_) (make-vector (1+ l2
) nil
))
774 (number-sequence 1 (1+ l1
)))))
775 (in (lambda (i j
) (aref (aref dist i
) j
))))
776 (setf (aref (aref dist
0) 0) 0)
777 (dolist (j (number-sequence 1 l2
))
778 (setf (aref (aref dist
0) j
) j
))
779 (dolist (i (number-sequence 1 l1
))
780 (setf (aref (aref dist i
) 0) i
)
781 (dolist (j (number-sequence 1 l2
))
782 (setf (aref (aref dist i
) j
)
784 (1+ (funcall in
(1- i
) j
))
785 (1+ (funcall in i
(1- j
)))
786 (+ (if (equal (aref s1
(1- i
)) (aref s2
(1- j
))) 0 1)
787 (funcall in
(1- i
) (1- j
)))))))
790 (defun org-babel-combine-header-arg-lists (original &rest others
)
791 "Combine a number of lists of header argument names and arguments."
792 (let ((results (copy-sequence original
)))
793 (dolist (new-list others
)
794 (dolist (arg-pair new-list
)
795 (let ((header (car arg-pair
)))
797 (cons arg-pair
(cl-remove-if
798 (lambda (pair) (equal header
(car pair
)))
803 (defun org-babel-check-src-block ()
804 "Check for misspelled header arguments in the current code block."
806 ;; TODO: report malformed code block
807 ;; TODO: report incompatible combinations of header arguments
808 ;; TODO: report uninitialized variables
809 (let ((too-close 2) ;; <- control closeness to report potential match
810 (names (mapcar #'symbol-name org-babel-header-arg-names
)))
811 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg
)) 1))
812 (and (org-babel-where-is-src-block-head)
813 (org-babel-parse-header-arguments
815 (match-string 4))))))
817 (when (and (not (string= header name
))
818 (<= (org-babel-edit-distance header name
) too-close
)
819 (not (member header names
)))
820 (error "Supplied header \"%S\" is suspiciously close to \"%S\""
822 (message "No suspicious header arguments found.")))
825 (defun org-babel-insert-header-arg (&optional header-arg value
)
826 "Insert a header argument selecting from lists of common args and values."
828 (let* ((info (org-babel-get-src-block-info 'light
))
831 (lang-headers (intern (concat "org-babel-header-args:" lang
)))
832 (headers (org-babel-combine-header-arg-lists
833 org-babel-common-header-args-w-values
834 (when (boundp lang-headers
) (eval lang-headers
))))
835 (header-arg (or header-arg
839 (lambda (header-spec) (symbol-name (car header-spec
)))
841 (vals (cdr (assoc (intern header-arg
) headers
)))
845 (read-from-minibuffer "value: "))
849 (let ((arg (completing-read
852 (mapcar #'symbol-name group
)))))
853 (if (and arg
(not (string= "default" arg
)))
859 (goto-char (point-at-eol))
860 (unless (= (char-before (point)) ?\
) (insert " "))
861 (insert ":" header-arg
) (when value
(insert " " value
)))))
863 ;; Add support for completing-read insertion of header arguments after ":"
864 (defun org-babel-header-arg-expand ()
865 "Call `org-babel-enter-header-arg-w-completion' in appropriate contexts."
866 (when (and (equal (char-before) ?\
:) (org-babel-where-is-src-block-head))
867 (org-babel-enter-header-arg-w-completion (match-string 2))))
869 (defun org-babel-enter-header-arg-w-completion (&optional lang
)
870 "Insert header argument appropriate for LANG with completion."
871 (let* ((lang-headers-var (intern (concat "org-babel-header-args:" lang
)))
872 (lang-headers (when (boundp lang-headers-var
) (eval lang-headers-var
)))
873 (headers-w-values (org-babel-combine-header-arg-lists
874 org-babel-common-header-args-w-values lang-headers
))
875 (headers (mapcar #'symbol-name
(mapcar #'car headers-w-values
)))
876 (header (org-completing-read "Header Arg: " headers
))
877 (args (cdr (assoc (intern header
) headers-w-values
)))
878 (arg (when (and args
(listp args
))
880 (format "%s: " header
)
881 (mapcar #'symbol-name
(apply #'append args
))))))
882 (insert (concat header
" " (or arg
"")))
885 (add-hook 'org-tab-first-hook
'org-babel-header-arg-expand
)
888 (defun org-babel-load-in-session (&optional _arg info
)
889 "Load the body of the current source-code block.
890 Evaluate the header arguments for the source block before
891 entering the session. After loading the body this pops open the
894 (let* ((info (or info
(org-babel-get-src-block-info)))
896 (params (nth 2 info
))
898 (user-error "No src code block at point")
900 (if (org-babel-noweb-p params
:eval
)
901 (org-babel-expand-noweb-references info
)
903 (session (cdr (assoc :session params
)))
904 (dir (cdr (assoc :dir params
)))
906 (or (and dir
(file-name-as-directory dir
)) default-directory
))
907 (cmd (intern (concat "org-babel-load-session:" lang
))))
908 (unless (fboundp cmd
)
909 (error "No org-babel-load-session function for %s!" lang
))
910 (pop-to-buffer (funcall cmd session body params
))
914 (defun org-babel-initiate-session (&optional arg info
)
915 "Initiate session for current code block.
916 If called with a prefix argument then resolve any variable
917 references in the header arguments and assign these variables in
918 the session. Copy the body of the code block to the kill ring."
920 (let* ((info (or info
(org-babel-get-src-block-info (not arg
))))
923 (params (nth 2 info
))
924 (session (cdr (assoc :session params
)))
925 (dir (cdr (assoc :dir params
)))
927 (or (and dir
(file-name-as-directory dir
)) default-directory
))
928 (init-cmd (intern (format "org-babel-%s-initiate-session" lang
)))
929 (prep-cmd (intern (concat "org-babel-prep-session:" lang
))))
930 (if (and (stringp session
) (string= session
"none"))
931 (error "This block is not using a session!"))
932 (unless (fboundp init-cmd
)
933 (error "No org-babel-initiate-session function for %s!" lang
))
934 (with-temp-buffer (insert (org-babel-trim body
))
935 (copy-region-as-kill (point-min) (point-max)))
937 (unless (fboundp prep-cmd
)
938 (error "No org-babel-prep-session function for %s!" lang
))
939 (funcall prep-cmd session params
))
940 (funcall init-cmd session params
)))
943 (defun org-babel-switch-to-session (&optional arg info
)
944 "Switch to the session of the current code block.
945 Uses `org-babel-initiate-session' to start the session. If called
946 with a prefix argument then this is passed on to
947 `org-babel-initiate-session'."
949 (pop-to-buffer (org-babel-initiate-session arg info
))
952 (defalias 'org-babel-pop-to-session
'org-babel-switch-to-session
)
954 (defvar org-src-window-setup
)
957 (defun org-babel-switch-to-session-with-code (&optional arg _info
)
958 "Switch to code buffer and display session."
962 (let ((other-window-buffer (window-buffer (next-window))))
963 (set-window-buffer (next-window) (current-buffer))
964 (set-window-buffer (selected-window) other-window-buffer
))
966 (info (org-babel-get-src-block-info))
967 (org-src-window-setup 'reorganize-frame
))
969 (org-babel-switch-to-session arg info
))
971 (funcall swap-windows
)))
974 (defmacro org-babel-do-in-edit-buffer
(&rest body
)
975 "Evaluate BODY in edit buffer if there is a code block at point.
976 Return t if a code block was found at point, nil otherwise."
977 `(let ((org-src-window-setup 'switch-invisibly
))
978 (when (and (org-babel-where-is-src-block-head)
980 (unwind-protect (progn ,@body
)
983 (def-edebug-spec org-babel-do-in-edit-buffer
(body))
985 (defun org-babel-do-key-sequence-in-edit-buffer (key)
986 "Read key sequence and execute the command in edit buffer.
987 Enter a key sequence to be executed in the language major-mode
988 edit buffer. For example, TAB will alter the contents of the
989 Org-mode code block according to the effect of TAB in the
990 language major-mode buffer. For languages that support
991 interactive sessions, this can be used to send code from the Org
992 buffer to the session for evaluation using the native major-mode
993 evaluation mechanisms."
994 (interactive "kEnter key-sequence to execute in edit buffer: ")
995 (org-babel-do-in-edit-buffer
997 (key-binding (or key
(read-key-sequence nil
))))))
999 (defvar org-bracket-link-regexp
)
1001 (defun org-babel-active-location-p ()
1002 (memq (org-element-type (save-match-data (org-element-context)))
1003 '(babel-call inline-babel-call inline-src-block src-block
)))
1006 (defun org-babel-open-src-block-result (&optional re-run
)
1007 "If `point' is on a src block then open the results of the
1008 source code block, otherwise return nil. With optional prefix
1009 argument RE-RUN the source-code block is evaluated even if
1010 results already exist."
1012 (let ((info (org-babel-get-src-block-info 'light
)))
1015 ;; go to the results, if there aren't any then run the block
1016 (goto-char (or (and (not re-run
) (org-babel-where-is-src-block-result))
1017 (progn (org-babel-execute-src-block)
1018 (org-babel-where-is-src-block-result))))
1020 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
1022 (if (looking-at org-bracket-link-regexp
)
1025 (let ((r (org-babel-format-result
1026 (org-babel-read-result) (cdr (assoc :sep
(nth 2 info
))))))
1027 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
1028 (delete-region (point-min) (point-max))
1033 (defmacro org-babel-map-src-blocks
(file &rest body
)
1034 "Evaluate BODY forms on each source-block in FILE.
1035 If FILE is nil evaluate BODY forms on source blocks in current
1036 buffer. During evaluation of BODY the following local variables
1037 are set relative to the currently matched code block.
1039 full-block ------- string holding the entirety of the code block
1040 beg-block -------- point at the beginning of the code block
1041 end-block -------- point at the end of the matched code block
1042 lang ------------- string holding the language of the code block
1043 beg-lang --------- point at the beginning of the lang
1044 end-lang --------- point at the end of the lang
1045 switches --------- string holding the switches
1046 beg-switches ----- point at the beginning of the switches
1047 end-switches ----- point at the end of the switches
1048 header-args ------ string holding the header-args
1049 beg-header-args -- point at the beginning of the header-args
1050 end-header-args -- point at the end of the header-args
1051 body ------------- string holding the body of the code block
1052 beg-body --------- point at the beginning of the body
1053 end-body --------- point at the end of the body"
1054 (declare (indent 1))
1055 (let ((tempvar (make-symbol "file")))
1056 `(let* ((case-fold-search t
)
1058 (visited-p (or (null ,tempvar
)
1059 (get-file-buffer (expand-file-name ,tempvar
))))
1060 (point (point)) to-be-removed
)
1061 (save-window-excursion
1062 (when ,tempvar
(find-file ,tempvar
))
1063 (setq to-be-removed
(current-buffer))
1064 (goto-char (point-min))
1065 (while (re-search-forward org-babel-src-block-regexp nil t
)
1066 (when (org-babel-active-location-p)
1067 (goto-char (match-beginning 0))
1068 (let ((full-block (match-string 0))
1069 (beg-block (match-beginning 0))
1070 (end-block (match-end 0))
1071 (lang (match-string 2))
1072 (beg-lang (match-beginning 2))
1073 (end-lang (match-end 2))
1074 (switches (match-string 3))
1075 (beg-switches (match-beginning 3))
1076 (end-switches (match-end 3))
1077 (header-args (match-string 4))
1078 (beg-header-args (match-beginning 4))
1079 (end-header-args (match-end 4))
1080 (body (match-string 5))
1081 (beg-body (match-beginning 5))
1082 (end-body (match-end 5)))
1083 ;; Silence byte-compiler in case `body' doesn't use all
1085 (ignore full-block beg-block end-block lang
1086 beg-lang end-lang switches beg-switches
1087 end-switches header-args beg-header-args
1088 end-header-args body beg-body end-body
)
1090 (goto-char end-block
)))))
1091 (unless visited-p
(kill-buffer to-be-removed
))
1092 (goto-char point
))))
1093 (def-edebug-spec org-babel-map-src-blocks
(form body
))
1096 (defmacro org-babel-map-inline-src-blocks
(file &rest body
)
1097 "Evaluate BODY forms on each inline source block in FILE.
1098 If FILE is nil evaluate BODY forms on source blocks in current
1100 (declare (indent 1) (debug (form body
)))
1101 (org-with-gensyms (datum end point tempvar to-be-removed visitedp
)
1102 `(let* ((case-fold-search t
)
1104 (,visitedp
(or (null ,tempvar
)
1105 (get-file-buffer (expand-file-name ,tempvar
))))
1108 (save-window-excursion
1109 (when ,tempvar
(find-file ,tempvar
))
1110 (setq ,to-be-removed
(current-buffer))
1111 (goto-char (point-min))
1112 (while (re-search-forward "src_\\S-" nil t
)
1113 (let ((,datum
(save-match-data (org-element-context))))
1114 (when (eq (org-element-type ,datum
) 'inline-src-block
)
1115 (goto-char (match-beginning 0))
1116 (let ((,end
(copy-marker (org-element-property :end
,datum
))))
1119 (set-marker ,end nil
))))))
1120 (unless ,visitedp
(kill-buffer ,to-be-removed
))
1121 (goto-char ,point
))))
1124 (defmacro org-babel-map-call-lines
(file &rest body
)
1125 "Evaluate BODY forms on each call line in FILE.
1126 If FILE is nil evaluate BODY forms on source blocks in current
1128 (declare (indent 1) (debug (form body
)))
1129 (org-with-gensyms (datum end point tempvar to-be-removed visitedp
)
1130 `(let* ((case-fold-search t
)
1132 (,visitedp
(or (null ,tempvar
)
1133 (get-file-buffer (expand-file-name ,tempvar
))))
1136 (save-window-excursion
1137 (when ,tempvar
(find-file ,tempvar
))
1138 (setq ,to-be-removed
(current-buffer))
1139 (goto-char (point-min))
1140 (while (re-search-forward "call_\\S-\\|^[ \t]*#\\+CALL:" nil t
)
1141 (let ((,datum
(save-match-data (org-element-context))))
1142 (when (memq (org-element-type ,datum
)
1143 '(babel-call inline-babel-call
))
1144 (goto-char (match-beginning 0))
1145 (let ((,end
(copy-marker (org-element-property :end
,datum
))))
1148 (set-marker ,end nil
))))))
1149 (unless ,visitedp
(kill-buffer ,to-be-removed
))
1150 (goto-char ,point
))))
1153 (defmacro org-babel-map-executables
(file &rest body
)
1154 "Evaluate BODY forms on each active Babel code in FILE.
1155 If FILE is nil evaluate BODY forms on source blocks in current
1157 (declare (indent 1) (debug (form body
)))
1158 (org-with-gensyms (datum end point tempvar to-be-removed visitedp
)
1159 `(let* ((case-fold-search t
)
1161 (,visitedp
(or (null ,tempvar
)
1162 (get-file-buffer (expand-file-name ,tempvar
))))
1165 (save-window-excursion
1166 (when ,tempvar
(find-file ,tempvar
))
1167 (setq ,to-be-removed
(current-buffer))
1168 (goto-char (point-min))
1169 (while (re-search-forward
1170 "\\(call\\|src\\)_\\|^[ \t]*#\\+\\(BEGIN_SRC\\|CALL:\\)" nil t
)
1171 (let ((,datum
(save-match-data (org-element-context))))
1172 (when (memq (org-element-type ,datum
)
1173 '(babel-call inline-babel-call inline-src-block
1175 (goto-char (match-beginning 0))
1176 (let ((,end
(copy-marker (org-element-property :end
,datum
))))
1179 (set-marker ,end nil
))))))
1180 (unless ,visitedp
(kill-buffer ,to-be-removed
))
1181 (goto-char ,point
))))
1184 (defun org-babel-execute-buffer (&optional arg
)
1185 "Execute source code blocks in a buffer.
1186 Call `org-babel-execute-src-block' on every source block in
1187 the current buffer."
1189 (org-babel-eval-wipe-error-buffer)
1190 (org-save-outline-visibility t
1191 (org-babel-map-executables nil
1192 (if (memq (org-element-type (org-element-context))
1193 '(babel-call inline-babel-call
))
1194 (org-babel-lob-execute-maybe)
1195 (org-babel-execute-src-block arg
)))))
1198 (defun org-babel-execute-subtree (&optional arg
)
1199 "Execute source code blocks in a subtree.
1200 Call `org-babel-execute-src-block' on every source block in
1201 the current subtree."
1205 (org-narrow-to-subtree)
1206 (org-babel-execute-buffer arg
)
1210 (defun org-babel-sha1-hash (&optional info
)
1211 "Generate an sha1 hash based on the value of info."
1213 (let ((print-level nil
)
1214 (info (or info
(org-babel-get-src-block-info))))
1216 (sort (copy-sequence (nth 2 info
))
1217 (lambda (a b
) (string< (car a
) (car b
)))))
1218 (let* ((rm (lambda (lst)
1219 (dolist (p '("replace" "silent" "none"
1220 "append" "prepend"))
1221 (setq lst
(remove p lst
)))
1224 (let ((v (if (and (listp (cdr arg
)) (null (cddr arg
)))
1225 (copy-sequence (cdr arg
))
1227 (when (and v
(not (and (sequencep v
)
1231 ((and (listp v
) ; lists are sorted
1232 (member (car arg
) '(:result-params
)))
1233 (sort (funcall rm v
) #'string
<))
1234 ((and (stringp v
) ; strings are sorted
1235 (member (car arg
) '(:results
:exports
)))
1236 (mapconcat #'identity
(sort (funcall rm
(split-string v
))
1241 (params (nth 2 info
))
1242 (body (if (org-babel-noweb-p params
:eval
)
1243 (org-babel-expand-noweb-references info
) (nth 1 info
)))
1244 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
1245 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
1248 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
1249 (org-babel-expand-body:generic
1250 body params
(and (fboundp assignments-cmd
)
1251 (funcall assignments-cmd params
))))))
1252 (let* ((it (format "%s-%s"
1255 (delq nil
(mapcar (lambda (arg)
1256 (let ((normalized (funcall norm arg
)))
1258 (format "%S" normalized
))))
1262 (when (org-called-interactively-p 'interactive
) (message hash
))
1265 (defun org-babel-current-result-hash (&optional info
)
1266 "Return the current in-buffer hash."
1267 (let ((result (org-babel-where-is-src-block-result nil info
)))
1269 (org-with-wide-buffer
1271 (looking-at org-babel-result-regexp
)
1272 (match-string-no-properties 1)))))
1274 (defun org-babel-set-current-result-hash (hash info
)
1275 "Set the current in-buffer hash to HASH."
1276 (org-with-wide-buffer
1277 (goto-char (org-babel-where-is-src-block-result nil info
))
1278 (looking-at org-babel-result-regexp
)
1279 (goto-char (match-beginning 1))
1280 (mapc #'delete-overlay
(overlays-at (point)))
1281 (forward-char org-babel-hash-show
)
1282 (mapc #'delete-overlay
(overlays-at (point)))
1283 (replace-match hash nil nil nil
1)
1285 (org-babel-hide-hash)))
1287 (defun org-babel-hide-hash ()
1288 "Hide the hash in the current results line.
1289 Only the initial `org-babel-hash-show' characters of the hash
1290 will remain visible."
1291 (add-to-invisibility-spec '(org-babel-hide-hash . t
))
1293 (when (and (re-search-forward org-babel-result-regexp nil t
)
1295 (let* ((start (match-beginning 1))
1296 (hide-start (+ org-babel-hash-show start
))
1298 (hash (match-string 1))
1300 (setq ov1
(make-overlay start hide-start
))
1301 (setq ov2
(make-overlay hide-start end
))
1302 (overlay-put ov2
'invisible
'org-babel-hide-hash
)
1303 (overlay-put ov1
'babel-hash hash
)))))
1305 (defun org-babel-hide-all-hashes ()
1306 "Hide the hash in the current buffer.
1307 Only the initial `org-babel-hash-show' characters of each hash
1308 will remain visible. This function should be called as part of
1309 the `org-mode-hook'."
1311 (while (and (not org-babel-hash-show-time
)
1312 (re-search-forward org-babel-result-regexp nil t
))
1313 (goto-char (match-beginning 0))
1314 (org-babel-hide-hash)
1315 (goto-char (match-end 0)))))
1316 (add-hook 'org-mode-hook
'org-babel-hide-all-hashes
)
1318 (defun org-babel-hash-at-point (&optional point
)
1319 "Return the value of the hash at POINT.
1321 The hash is also added as the last element of the kill ring.
1322 This can be called with \\[org-ctrl-c-ctrl-c]."
1324 (let ((hash (car (delq nil
(mapcar
1325 (lambda (ol) (overlay-get ol
'babel-hash
))
1326 (overlays-at (or point
(point))))))))
1327 (when hash
(kill-new hash
) (message hash
))))
1328 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-hash-at-point
)
1330 (defun org-babel-result-hide-spec ()
1331 "Hide portions of results lines.
1332 Add `org-babel-hide-result' as an invisibility spec for hiding
1333 portions of results lines."
1334 (add-to-invisibility-spec '(org-babel-hide-result . t
)))
1335 (add-hook 'org-mode-hook
'org-babel-result-hide-spec
)
1337 (defvar org-babel-hide-result-overlays nil
1338 "Overlays hiding results.")
1340 (defun org-babel-result-hide-all ()
1341 "Fold all results in the current buffer."
1343 (org-babel-show-result-all)
1345 (while (re-search-forward org-babel-result-regexp nil t
)
1346 (save-excursion (goto-char (match-beginning 0))
1347 (org-babel-hide-result-toggle-maybe)))))
1349 (defun org-babel-show-result-all ()
1350 "Unfold all results in the current buffer."
1351 (mapc 'delete-overlay org-babel-hide-result-overlays
)
1352 (setq org-babel-hide-result-overlays nil
))
1355 (defun org-babel-hide-result-toggle-maybe ()
1356 "Toggle visibility of result at point."
1358 (let ((case-fold-search t
))
1360 (beginning-of-line 1)
1361 (looking-at org-babel-result-regexp
))
1362 (progn (org-babel-hide-result-toggle)
1363 t
) ;; to signal that we took action
1364 nil
))) ;; to signal that we did not
1366 (defun org-babel-hide-result-toggle (&optional force
)
1367 "Toggle the visibility of the current result."
1371 (if (re-search-forward org-babel-result-regexp nil t
)
1372 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
1374 (while (looking-at org-babel-multi-line-header-regexp
)
1376 (goto-char (- (org-babel-result-end) 1)) (point)))
1378 (if (memq t
(mapcar (lambda (overlay)
1379 (eq (overlay-get overlay
'invisible
)
1380 'org-babel-hide-result
))
1381 (overlays-at start
)))
1382 (if (or (not force
) (eq force
'off
))
1384 (when (member ov org-babel-hide-result-overlays
)
1385 (setq org-babel-hide-result-overlays
1386 (delq ov org-babel-hide-result-overlays
)))
1387 (when (eq (overlay-get ov
'invisible
)
1388 'org-babel-hide-result
)
1389 (delete-overlay ov
)))
1390 (overlays-at start
)))
1391 (setq ov
(make-overlay start end
))
1392 (overlay-put ov
'invisible
'org-babel-hide-result
)
1393 ;; make the block accessible to isearch
1395 ov
'isearch-open-invisible
1397 (when (member ov org-babel-hide-result-overlays
)
1398 (setq org-babel-hide-result-overlays
1399 (delq ov org-babel-hide-result-overlays
)))
1400 (when (eq (overlay-get ov
'invisible
)
1401 'org-babel-hide-result
)
1402 (delete-overlay ov
))))
1403 (push ov org-babel-hide-result-overlays
)))
1404 (error "Not looking at a result line"))))
1406 ;; org-tab-after-check-for-cycling-hook
1407 (add-hook 'org-tab-first-hook
'org-babel-hide-result-toggle-maybe
)
1408 ;; Remove overlays when changing major mode
1409 (add-hook 'org-mode-hook
1410 (lambda () (org-add-hook 'change-major-mode-hook
1411 'org-babel-show-result-all
'append
'local
)))
1413 (defvar org-file-properties
)
1414 (defun org-babel-params-from-properties (&optional lang
)
1415 "Retrieve parameters specified as properties.
1416 Return a list of association lists of source block params
1417 specified in the properties of the current outline entry."
1420 ;; DEPRECATED header arguments specified as separate property at
1421 ;; point of definition.
1422 (org-babel-parse-multiple-vars
1426 (let* ((arg (symbol-name (car header
)))
1427 (val (org-entry-get (point) arg t
)))
1429 (cons (intern (concat ":" arg
))
1430 (org-babel-read val
)))))
1431 (org-babel-combine-header-arg-lists
1432 org-babel-common-header-args-w-values
1433 (let ((sym (intern (concat "org-babel-header-args:" lang
))))
1434 (and (boundp sym
) (symbol-value sym
)))))))
1435 ;; header arguments specified with the header-args property at
1437 (org-babel-parse-header-arguments
1438 (org-entry-get org-babel-current-src-block-location
1441 (and lang
; language-specific header arguments at point of call
1442 (org-babel-parse-header-arguments
1443 (org-entry-get org-babel-current-src-block-location
1444 (concat "header-args:" lang
)
1447 (defun org-babel-balanced-split (string alts
)
1448 "Split STRING on instances of ALTS.
1449 ALTS is a cons of two character options where each option may be
1450 either the numeric code of a single character or a list of
1451 character alternatives. For example to split on balanced
1452 instances of \"[ \t]:\" set ALTS to ((32 9) . 58)."
1453 (let* ((matches (lambda (ch spec
) (if (listp spec
) (member ch spec
) (equal spec ch
))))
1454 (matched (lambda (ch last
)
1456 (and (funcall matches ch
(cdr alts
))
1457 (funcall matches last
(car alts
)))
1458 (funcall matches ch alts
))))
1459 (balance 0) (last 0)
1461 (mapc (lambda (ch) ; split on [], (), "" balanced instances of [ \t]:
1462 (setq balance
(+ balance
1463 (cond ((or (equal 91 ch
) (equal 40 ch
)) 1)
1464 ((or (equal 93 ch
) (equal 41 ch
)) -
1)
1466 (when (and (equal 34 ch
) (not (equal 92 last
)))
1467 (setq quote
(not quote
)))
1468 (setq partial
(cons ch partial
))
1469 (when (and (= balance
0) (not quote
) (funcall matched ch last
))
1470 (setq lst
(cons (apply #'string
(nreverse
1477 (string-to-list string
))
1478 (nreverse (cons (apply #'string
(nreverse partial
)) lst
))))
1480 (defun org-babel-join-splits-near-ch (ch list
)
1481 "Join splits where \"=\" is on either end of the split."
1482 (let ((last= (lambda (str) (= ch
(aref str
(1- (length str
))))))
1483 (first= (lambda (str) (= ch
(aref str
0)))))
1485 (cl-reduce (lambda (acc el
)
1486 (let ((head (car acc
)))
1487 (if (and head
(or (funcall last
= head
) (funcall first
= el
)))
1488 (cons (concat head el
) (cdr acc
))
1490 list
:initial-value nil
))))
1492 (defun org-babel-parse-header-arguments (arg-string)
1493 "Parse a string of header arguments returning an alist."
1494 (when (> (length arg-string
) 0)
1495 (org-babel-parse-multiple-vars
1500 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1502 (cons (intern (match-string 1 arg
))
1503 (org-babel-read (org-babel-chomp (match-string 2 arg
))))
1504 (cons (intern (org-babel-chomp arg
)) nil
)))
1505 (let ((raw (org-babel-balanced-split arg-string
'((32 9) .
58))))
1506 (cons (car raw
) (mapcar (lambda (r) (concat ":" r
)) (cdr raw
)))))))))
1508 (defun org-babel-parse-multiple-vars (header-arguments)
1509 "Expand multiple variable assignments behind a single :var keyword.
1511 This allows expression of multiple variables with one :var as
1514 #+PROPERTY: var foo=1, bar=2"
1516 (mapc (lambda (pair)
1517 (if (eq (car pair
) :var
)
1518 (mapcar (lambda (v) (push (cons :var
(org-babel-trim v
)) results
))
1519 (org-babel-join-splits-near-ch
1520 61 (org-babel-balanced-split (cdr pair
) 32)))
1521 (push pair results
)))
1523 (nreverse results
)))
1525 (defun org-babel-process-params (params)
1526 "Expand variables in PARAMS and add summary parameters."
1527 (let* ((processed-vars (mapcar (lambda (el)
1530 (org-babel-ref-parse el
)))
1531 (org-babel--get-vars params
)))
1532 (vars-and-names (if (and (assoc :colname-names params
)
1533 (assoc :rowname-names params
))
1534 (list processed-vars
)
1535 (org-babel-disassemble-tables
1537 (cdr (assoc :hlines params
))
1538 (cdr (assoc :colnames params
))
1539 (cdr (assoc :rownames params
)))))
1540 (raw-result (or (cdr (assoc :results params
)) ""))
1541 (result-params (append
1542 (split-string (if (stringp raw-result
)
1545 (cdr (assoc :result-params params
)))))
1547 (mapcar (lambda (var) (cons :var var
)) (car vars-and-names
))
1549 (cons :colname-names
(or (cdr (assoc :colname-names params
))
1550 (cadr vars-and-names
)))
1551 (cons :rowname-names
(or (cdr (assoc :rowname-names params
))
1552 (caddr vars-and-names
)))
1553 (cons :result-params result-params
)
1554 (cons :result-type
(cond ((member "output" result-params
) 'output
)
1555 ((member "value" result-params
) 'value
)
1558 (lambda (x) (memq (car x
) '(:colname-names
:rowname-names
:result-params
1559 :result-type
:var
)))
1562 ;; row and column names
1563 (defun org-babel-del-hlines (table)
1564 "Remove all `hline's from TABLE."
1565 (remq 'hline table
))
1567 (defun org-babel-get-colnames (table)
1568 "Return the column names of TABLE.
1569 Return a cons cell, the `car' of which contains the TABLE less
1570 colnames, and the `cdr' of which contains a list of the column
1572 (if (equal 'hline
(nth 1 table
))
1573 (cons (cddr table
) (car table
))
1574 (cons (cdr table
) (car table
))))
1576 (defun org-babel-get-rownames (table)
1577 "Return the row names of TABLE.
1578 Return a cons cell, the `car' of which contains the TABLE less
1579 rownames, and the `cdr' of which contains a list of the rownames.
1580 Note: this function removes any hlines in TABLE."
1581 (let* ((table (org-babel-del-hlines table
))
1582 (rownames (funcall (lambda ()
1588 (setq tp
(cdr tp
))))
1590 (cons table rownames
)))
1592 (defun org-babel-put-colnames (table colnames
)
1593 "Add COLNAMES to TABLE if they exist."
1594 (if colnames
(apply 'list colnames
'hline table
) table
))
1596 (defun org-babel-put-rownames (table rownames
)
1597 "Add ROWNAMES to TABLE if they exist."
1599 (mapcar (lambda (row)
1601 (cons (or (pop rownames
) "") row
)
1605 (defun org-babel-pick-name (names selector
)
1606 "Select one out of an alist of row or column names.
1607 SELECTOR can be either a list of names in which case those names
1608 will be returned directly, or an index into the list NAMES in
1609 which case the indexed names will be return."
1610 (if (listp selector
)
1613 (if (and selector
(symbolp selector
) (not (equal t selector
)))
1614 (cdr (assoc selector names
))
1615 (if (integerp selector
)
1616 (nth (- selector
1) names
)
1617 (cdr (car (last names
))))))))
1619 (defun org-babel-disassemble-tables (vars hlines colnames rownames
)
1620 "Parse tables for further processing.
1621 Process the variables in VARS according to the HLINES,
1622 ROWNAMES and COLNAMES header arguments. Return a list consisting
1623 of the vars, cnames and rnames."
1624 (let (cnames rnames
)
1628 (when (listp (cdr var
))
1629 (when (and (not (equal colnames
"no"))
1630 (or colnames
(and (equal (nth 1 (cdr var
)) 'hline
)
1631 (not (member 'hline
(cddr (cdr var
)))))))
1632 (let ((both (org-babel-get-colnames (cdr var
))))
1633 (setq cnames
(cons (cons (car var
) (cdr both
))
1635 (setq var
(cons (car var
) (car both
)))))
1636 (when (and rownames
(not (equal rownames
"no")))
1637 (let ((both (org-babel-get-rownames (cdr var
))))
1638 (setq rnames
(cons (cons (car var
) (cdr both
))
1640 (setq var
(cons (car var
) (car both
)))))
1641 (when (and hlines
(not (equal hlines
"yes")))
1642 (setq var
(cons (car var
) (org-babel-del-hlines (cdr var
))))))
1645 (reverse cnames
) (reverse rnames
))))
1647 (defun org-babel-reassemble-table (table colnames rownames
)
1648 "Add column and row names to a table.
1649 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1650 to the table for reinsertion to org-mode."
1652 (let ((table (if (and rownames
(= (length table
) (length rownames
)))
1653 (org-babel-put-rownames table rownames
) table
)))
1654 (if (and colnames
(listp (car table
)) (= (length (car table
))
1656 (org-babel-put-colnames table colnames
) table
))
1659 (defun org-babel-where-is-src-block-head (&optional src-block
)
1660 "Find where the current source block begins.
1662 If optional argument SRC-BLOCK is `src-block' type element, find
1663 its current beginning instead.
1665 Return the point at the beginning of the current source block.
1666 Specifically at the beginning of the #+BEGIN_SRC line. Also set
1667 match-data relatively to `org-babel-src-block-regexp', which see.
1668 If the point is not on a source block then return nil."
1669 (let ((element (or src-block
(org-element-at-point))))
1670 (when (eq (org-element-type element
) 'src-block
)
1671 (let ((end (org-element-property :end element
)))
1672 (org-with-wide-buffer
1673 ;; Ensure point is not on a blank line after the block.
1675 (skip-chars-forward " \r\t\n" end
)
1676 (when (< (point) end
)
1677 (prog1 (goto-char (org-element-property :post-affiliated element
))
1678 (looking-at org-babel-src-block-regexp
))))))))
1681 (defun org-babel-goto-src-block-head ()
1682 "Go to the beginning of the current code block."
1684 (let ((head (org-babel-where-is-src-block-head)))
1685 (if head
(goto-char head
) (error "Not currently in a code block"))))
1688 (defun org-babel-goto-named-src-block (name)
1689 "Go to a named source-code block."
1691 (let ((completion-ignore-case t
)
1692 (case-fold-search t
)
1693 (all-block-names (org-babel-src-block-names)))
1694 (list (completing-read
1695 "source-block name: " all-block-names nil t
1696 (let* ((context (org-element-context))
1697 (type (org-element-type context
)))
1699 ((and (memq type
'(inline-src-block src-block
)) ;<<noweb>>
1700 (org-in-regexp (org-babel-noweb-wrap))))
1701 ((memq type
'(babel-call inline-babel-call
)) ;#+CALL:
1702 (org-element-property :call context
))
1703 ((org-element-property :results context
)) ;#+RESULTS:
1704 ((let ((symbol (thing-at-point 'symbol
))) ;Symbol.
1705 (and (member-ignore-case symbol all-block-names
)
1708 (let ((point (org-babel-find-named-block name
)))
1710 ;; Taken from `org-open-at-point'.
1711 (progn (org-mark-ring-push) (goto-char point
) (org-show-context))
1712 (message "source-code block `%s' not found in this buffer" name
))))
1714 (defun org-babel-find-named-block (name)
1715 "Find a named source-code block.
1716 Return the location of the source block identified by source
1717 NAME, or nil if no such block exists. Set match data according
1718 to `org-babel-named-src-block-regexp'."
1720 (goto-char (point-min))
1722 (org-next-block 1 nil
(org-babel-named-src-block-regexp-for-name name
)))))
1724 (defun org-babel-src-block-names (&optional file
)
1725 "Returns the names of source blocks in FILE or the current buffer."
1726 (when file
(find-file file
))
1728 (goto-char (point-min))
1729 (let ((re (org-babel-named-src-block-regexp-for-name))
1731 (while (ignore-errors (org-next-block 1 nil re
))
1732 (push (org-match-string-no-properties 9) names
))
1736 (defun org-babel-goto-named-result (name)
1737 "Go to a named result."
1739 (let ((completion-ignore-case t
))
1740 (list (completing-read "Source-block name: "
1741 (org-babel-result-names) nil t
))))
1742 (let ((point (org-babel-find-named-result name
)))
1744 ;; taken from `org-open-at-point'
1745 (progn (goto-char point
) (org-show-context))
1746 (message "result `%s' not found in this buffer" name
))))
1748 (defun org-babel-find-named-result (name)
1749 "Find a named result.
1750 Return the location of the result named NAME in the current
1751 buffer or nil if no such result exists."
1753 (goto-char (point-min))
1754 (let ((case-fold-search t
)
1755 (re (format "^[ \t]*#\\+%s.*?:[ \t]*%s[ \t]*$"
1756 org-babel-results-keyword
1757 (regexp-quote name
))))
1759 (while (re-search-forward re nil t
)
1760 (let ((element (org-element-at-point)))
1761 (when (or (eq (org-element-type element
) 'keyword
)
1763 (org-element-property :post-affiliated element
)))
1764 (throw :found
(line-beginning-position)))))))))
1766 (defun org-babel-result-names (&optional file
)
1767 "Returns the names of results in FILE or the current buffer."
1769 (when file
(find-file file
)) (goto-char (point-min))
1770 (let ((case-fold-search t
) names
)
1771 (while (re-search-forward org-babel-result-w-name-regexp nil t
)
1772 (setq names
(cons (match-string-no-properties 9) names
)))
1776 (defun org-babel-next-src-block (&optional arg
)
1777 "Jump to the next source block.
1778 With optional prefix argument ARG, jump forward ARG many source blocks."
1780 (org-next-block arg nil org-babel-src-block-regexp
))
1783 (defun org-babel-previous-src-block (&optional arg
)
1784 "Jump to the previous source block.
1785 With optional prefix argument ARG, jump backward ARG many source blocks."
1787 (org-previous-block arg org-babel-src-block-regexp
))
1789 (defvar org-babel-load-languages
)
1792 (defun org-babel-mark-block ()
1793 "Mark current src block."
1795 (let ((head (org-babel-where-is-src-block-head)))
1799 (looking-at org-babel-src-block-regexp
))
1800 (push-mark (match-end 5) nil t
)
1801 (goto-char (match-beginning 5)))))
1803 (defun org-babel-demarcate-block (&optional arg
)
1804 "Wrap or split the code in the region or on the point.
1805 When called from inside of a code block the current block is
1806 split. When called from outside of a code block a new code block
1807 is created. In both cases if the region is demarcated and if the
1808 region is not active then the point is demarcated."
1810 (let* ((info (org-babel-get-src-block-info 'light
))
1811 (start (org-babel-where-is-src-block-head))
1812 (block (and start
(match-string 0)))
1813 (headers (and start
(match-string 4)))
1814 (stars (concat (make-string (or (org-current-level) 1) ?
*) " "))
1815 (lower-case-p (and block
1816 (let (case-fold-search)
1817 (org-string-match-p "#\\+begin_src" block
)))))
1823 (let ((lang (nth 0 info
))
1824 (indent (make-string (org-get-indentation) ?\s
)))
1825 (when (string-match "^[[:space:]]*$"
1826 (buffer-substring (point-at-bol)
1828 (delete-region (point-at-bol) (point-at-eol)))
1830 (if (looking-at "^") "" "\n")
1831 indent
(funcall (if lower-case-p
'downcase
'upcase
) "#+end_src\n")
1832 (if arg stars indent
) "\n"
1833 indent
(funcall (if lower-case-p
'downcase
'upcase
) "#+begin_src ")
1835 (if (> (length headers
) 1)
1836 (concat " " headers
) headers
)
1837 (if (looking-at "[\n\r]")
1839 (concat "\n" (make-string (current-column) ?
)))))))
1840 (move-end-of-line 2))
1841 (sort (if (org-region-active-p) (list (mark) (point)) (list (point))) #'>))
1842 (let ((start (point))
1843 (lang (completing-read
1845 (mapcar #'symbol-name
1847 (append (mapcar #'car org-babel-load-languages
)
1848 (mapcar (lambda (el) (intern (car el
)))
1849 org-src-lang-modes
))))))
1850 (body (delete-and-extract-region
1851 (if (org-region-active-p) (mark) (point)) (point))))
1852 (insert (concat (if (looking-at "^") "" "\n")
1853 (if arg
(concat stars
"\n") "")
1854 (funcall (if lower-case-p
'downcase
'upcase
) "#+begin_src ")
1857 (if (or (= (length body
) 0)
1858 (string-match "[\r\n]$" body
)) "" "\n")
1859 (funcall (if lower-case-p
'downcase
'upcase
) "#+end_src\n")))
1860 (goto-char start
) (move-end-of-line 1)))))
1862 (defun org-babel--insert-results-keyword (name hash
)
1863 "Insert RESULTS keyword with NAME value at point.
1864 If NAME is nil, results are anonymous. HASH is a string used as
1865 the results hash, or nil. Leave point before the keyword."
1866 (save-excursion (insert "\n")) ;open line to indent.
1869 (insert (concat "#+" org-babel-results-keyword
1870 (cond ((not hash
) nil
)
1871 (org-babel-hash-show-time
1873 (format-time-string "<%Y-%m-%d %H:%M:%S>")
1875 (t (format "[%s]" hash
)))
1877 (when name
(concat " " name
))
1879 (beginning-of-line -
1)
1880 (when hash
(org-babel-hide-hash)))
1882 (defun org-babel--clear-results-maybe (hash)
1883 "Clear results when hash doesn't match HASH.
1885 When results hash does not match HASH, remove RESULTS keyword at
1886 point, along with related contents. Do nothing if HASH is nil.
1888 Return a non-nil value if results were cleared. In this case,
1889 leave point where new results should be inserted."
1891 (looking-at org-babel-result-regexp
)
1892 (unless (string= (match-string 1) hash
)
1893 (let* ((e (org-element-at-point))
1894 (post (copy-marker (org-element-property :post-affiliated e
))))
1898 (goto-char (org-element-property :end e
))
1899 (skip-chars-backward " \t\n")
1900 (line-beginning-position 2)))
1901 ;; Delete RESULT keyword. However, if RESULTS keyword is
1902 ;; orphaned, ignore this part. The deletion above already
1904 (unless (= (point) post
)
1905 (delete-region (line-beginning-position)
1906 (line-beginning-position 2)))
1908 (set-marker post nil
)))
1911 (defun org-babel-where-is-src-block-result (&optional insert _info hash
)
1912 "Find where the current source block results begin.
1914 Return the point at the beginning of the result of the current
1915 source block, specifically at the beginning of the results line.
1917 If no result exists for this block return nil, unless optional
1918 argument INSERT is non-nil. In this case, create a results line
1919 following the source block and return the position at its
1920 beginning. In the case of inline code, remove the results part
1923 If optional argument HASH is a string, remove contents related to
1924 RESULTS keyword if its hash is different. Then update the latter
1926 (let ((context (org-element-context)))
1928 (org-with-wide-buffer
1929 (pcase (org-element-type context
)
1930 ((or `inline-babel-call
`inline-src-block
)
1931 ;; Results for inline objects are located right after them.
1932 ;; There is no RESULTS line to insert either.
1933 (let ((limit (org-element-property
1934 :contents-end
(org-element-property :parent context
))))
1935 (goto-char (org-element-property :end context
))
1936 (skip-chars-forward " \t\n" limit
)
1940 (let ((result (org-element-context)))
1941 (and (eq (org-element-type result
) 'macro
)
1942 (string= (org-element-property :key result
)
1944 (if (not insert
) (point)
1948 (goto-char (org-element-property :end result
))
1949 (skip-chars-backward " \t")
1952 ((or `babel-call
`src-block
)
1953 (let* ((name (org-element-property :name context
))
1954 (named-results (and name
(org-babel-find-named-result name
))))
1955 (goto-char (or named-results
(org-element-property :end context
)))
1957 ;; Existing results named after the current source.
1959 (when (org-babel--clear-results-maybe hash
)
1960 (org-babel--insert-results-keyword name hash
))
1961 (throw :found
(point)))
1962 ;; Named results expect but none to be found.
1964 ;; No possible anonymous results at the very end of
1965 ;; buffer or outside CONTEXT parent.
1967 (or (org-element-property
1968 :contents-end
(org-element-property :parent context
))
1970 ;; Check if next element is an anonymous result below
1971 ;; the current block.
1972 ((let* ((next (org-element-at-point))
1973 (end (save-excursion
1975 (org-element-property :post-affiliated next
))
1976 (line-end-position)))
1977 (empty-result-re (concat org-babel-result-regexp
"$"))
1978 (case-fold-search t
))
1979 (re-search-forward empty-result-re end t
))
1981 (when (org-babel--clear-results-maybe hash
)
1982 (org-babel--insert-results-keyword nil hash
))
1983 (throw :found
(point))))))
1984 ;; Ignore other elements.
1985 (_ (throw :found nil
))))
1986 ;; No result found. Insert a RESULTS keyword below element, if
1987 ;; appropriate. In this case, ensure there is an empty line
1988 ;; after the previous element.
1991 (goto-char (min (org-element-property :end context
) (point-max)))
1992 (skip-chars-backward " \t\n")
1994 (cond ((not (bolp)) (insert "\n\n"))
1996 (= (org-element-property :post-blank context
) 0))
1999 (org-babel--insert-results-keyword
2000 (org-element-property :name context
) hash
)
2003 (defun org-babel-read-element (element)
2004 "Read ELEMENT into emacs-lisp.
2005 Return nil if ELEMENT cannot be read."
2006 (org-with-wide-buffer
2007 (goto-char (org-element-property :post-affiliated element
))
2008 (pcase (org-element-type element
)
2010 (let ((v (org-babel-trim (org-element-property :value element
))))
2011 (or (org-babel-number-p v
) v
)))
2012 (`table
(org-babel-read-table))
2013 (`plain-list
(org-babel-read-list))
2015 (let ((v (org-element-property :value element
)))
2016 (if (or org-src-preserve-indentation
2017 (org-element-property :preserve-indent element
))
2019 (org-remove-indentation v
))))
2021 (org-remove-indentation (org-element-property :value element
)))
2023 ;; Treat paragraphs containing a single link specially.
2024 (skip-chars-forward " \t")
2025 (if (and (looking-at org-bracket-link-regexp
)
2027 (goto-char (match-end 0))
2028 (skip-chars-forward " \r\t\n")
2029 (<= (org-element-property :end element
)
2031 (org-babel-read-link)
2032 (buffer-substring-no-properties
2033 (org-element-property :contents-begin element
)
2034 (org-element-property :contents-end element
))))
2035 ((or `center-block
`quote-block
`verse-block
`special-block
)
2036 (org-remove-indentation
2037 (buffer-substring-no-properties
2038 (org-element-property :contents-begin element
)
2039 (org-element-property :contents-end element
))))
2042 (defun org-babel-read-result ()
2043 "Read the result at point into emacs-lisp."
2044 (and (not (save-excursion
2046 (looking-at-p "[ \t]*$")))
2047 (org-babel-read-element (org-element-at-point))))
2049 (defun org-babel-read-table ()
2050 "Read the table at point into emacs-lisp."
2051 (mapcar (lambda (row)
2052 (if (and (symbolp row
) (equal row
'hline
)) row
2053 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
)) row
)))
2054 (org-table-to-lisp)))
2056 (defun org-babel-read-list ()
2057 "Read the list at point into emacs-lisp."
2058 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
))
2059 (cdr (org-list-to-lisp))))
2061 (defvar org-link-types-re
)
2062 (defun org-babel-read-link ()
2063 "Read the link at point into emacs-lisp.
2064 If the path of the link is a file path it is expanded using
2065 `expand-file-name'."
2066 (let* ((case-fold-search t
)
2067 (raw (and (looking-at org-bracket-link-regexp
)
2068 (org-no-properties (match-string 1))))
2069 (type (and (string-match org-link-types-re raw
)
2070 (match-string 1 raw
))))
2072 ((not type
) (expand-file-name raw
))
2073 ((string= type
"file")
2074 (and (string-match "file\\(.*\\):\\(.+\\)" raw
)
2075 (expand-file-name (match-string 2 raw
))))
2078 (defun org-babel-format-result (result &optional sep
)
2079 "Format RESULT for writing to file."
2080 (let ((echo-res (lambda (r) (if (stringp r
) r
(format "%S" r
)))))
2084 result
(list :sep
(or sep
"\t") :fmt echo-res
))
2086 (funcall echo-res result
))))
2088 (defun org-babel-insert-result (result &optional result-params info hash lang
)
2089 "Insert RESULT into the current buffer.
2091 By default RESULT is inserted after the end of the current source
2092 block. The RESULT of an inline source block usually will be
2093 wrapped inside a `results' macro and placed on the same line as
2094 the inline source block. The macro is stripped upon export.
2095 Multiline and non-scalar RESULTS from inline source blocks are
2096 not allowed. With optional argument RESULT-PARAMS controls
2097 insertion of results in the Org mode file. RESULT-PARAMS can
2098 take the following values:
2100 replace - (default option) insert results after the source block
2101 or inline source block replacing any previously
2104 silent -- no results are inserted into the Org-mode buffer but
2105 the results are echoed to the minibuffer and are
2106 ingested by Emacs (a potentially time consuming
2109 file ---- the results are interpreted as a file path, and are
2110 inserted into the buffer using the Org-mode file syntax.
2112 list ---- the results are interpreted as an Org-mode list.
2114 raw ----- results are added directly to the Org-mode file. This
2115 is a good option if you code block will output org-mode
2118 drawer -- results are added directly to the Org-mode file as with
2119 \"raw\", but are wrapped in a RESULTS drawer or results
2120 macro, allowing them to later be replaced or removed
2123 org ----- results are added inside of a \"src_org{}\" or \"#+BEGIN_SRC
2124 org\" block depending on whether the current source block is
2125 inline or not. They are not comma-escaped when inserted,
2126 but Org syntax here will be discarded when exporting the
2129 html ---- results are added inside of a #+BEGIN_EXPORT HTML block
2130 or html export snippet depending on whether the current
2131 source block is inline or not. This is a good option
2132 if your code block will output html formatted text.
2134 latex --- results are added inside of a #+BEGIN_EXPORT LATEX
2135 block or latex export snippet depending on whether the
2136 current source block is inline or not. This is a good
2137 option if your code block will output latex formatted
2140 code ---- the results are extracted in the syntax of the source
2141 code of the language being evaluated and are added
2142 inside of a source block with the source-code language
2143 set appropriately. Also, source block inlining is
2144 preserved in this case. Note this relies on the
2145 optional LANG argument.
2147 list ---- the results are rendered as a list. This option not
2148 allowed for inline src blocks.
2150 table --- the results are rendered as a table. This option not
2151 allowed for inline src blocks.
2153 INFO may provide the values of these header arguments (in the
2154 `header-arguments-alist' see the docstring for
2155 `org-babel-get-src-block-info'):
2157 :file --- the name of the file to which output should be written.
2159 :wrap --- the effect is similar to `latex' in RESULT-PARAMS but
2160 using the argument supplied to specify the export block
2162 (cond ((stringp result
)
2163 (setq result
(org-no-properties result
))
2164 (when (member "file" result-params
)
2165 (setq result
(org-babel-result-to-file
2166 result
(when (assoc :file-desc
(nth 2 info
))
2167 (or (cdr (assoc :file-desc
(nth 2 info
)))
2170 (t (setq result
(format "%S" result
))))
2171 (if (and result-params
(member "silent" result-params
))
2172 (progn (message (replace-regexp-in-string "%" "%%" (format "%S" result
)))
2174 (let ((inline (let ((context (org-element-context)))
2175 (and (memq (org-element-type context
)
2176 '(inline-babel-call inline-src-block
))
2180 (or (and (member "table" result-params
) "`:results table'")
2181 (and (listp result
) "list result")
2182 (and (string-match-p "\n." result
) "multiline result")
2183 (and (member "list" result-params
) "`:results list'"))))
2185 (user-error "Inline error: %s cannot be used" warning
))))
2187 (let* ((visible-beg (point-min-marker))
2188 (visible-end (copy-marker (point-max) t
))
2189 (inline (let ((context (org-element-context)))
2190 (and (memq (org-element-type context
)
2191 '(inline-babel-call inline-src-block
))
2193 (existing-result (org-babel-where-is-src-block-result t nil hash
))
2194 (results-switches (cdr (assq :results_switches
(nth 2 info
))))
2195 ;; When results exist outside of the current visible
2196 ;; region of the buffer, be sure to widen buffer to
2198 (outside-scope (and existing-result
2200 (or (> visible-beg existing-result
)
2201 (<= visible-end existing-result
))))
2203 ;; Ensure non-inline results end in a newline.
2204 (when (and (org-string-nw-p result
)
2206 (not (string-equal (substring result -
1) "\n")))
2207 (setq result
(concat result
"\n")))
2210 (when outside-scope
(widen))
2211 (if existing-result
(goto-char existing-result
)
2212 (goto-char (org-element-property :end inline
))
2213 (skip-chars-backward " \t"))
2215 (setq indent
(org-get-indentation))
2220 ;; Make sure new results are separated from the
2221 ;; source code by one space.
2222 (unless existing-result
2224 (setq beg
(point))))
2225 ((member "replace" result-params
)
2226 (delete-region (point) (org-babel-result-end)))
2227 ((member "append" result-params
)
2228 (goto-char (org-babel-result-end)) (setq beg
(point-marker)))
2229 ((member "prepend" result-params
))) ; already there
2230 (setq results-switches
2231 (if results-switches
(concat " " results-switches
) ""))
2232 (let ((wrap (lambda (start finish
&optional no-escape no-newlines
2233 inline-start inline-finish
)
2235 (setq start inline-start
)
2236 (setq finish inline-finish
)
2237 (setq no-newlines t
))
2239 (insert (concat finish
(unless no-newlines
"\n")))
2241 (insert (concat start
(unless no-newlines
"\n")))
2243 (org-escape-code-in-region (min (point) end
) end
))
2245 (unless no-newlines
(goto-char (point-at-eol)))
2246 (setq end
(point-marker))))
2249 ;; Non-nil when result R can be turned into
2252 (null (cdr (last r
)))
2254 (lambda (e) (or (atom e
) (null (cdr (last e
)))))
2256 ;; insert results based on type
2258 ;; Do nothing for an empty result.
2260 ;; Insert a list if preferred.
2261 ((member "list" result-params
)
2264 (org-list-to-generic
2268 (list (if (stringp e
) e
(format "%S" e
))))
2269 (if (listp result
) result
2270 (split-string result
"\n" t
))))
2271 '(:splicep nil
:istart
"- " :iend
"\n")))
2273 ;; Try hard to print RESULT as a table. Give up if
2274 ;; it contains an improper list.
2275 ((funcall tabulablep result
)
2277 (insert (concat (orgtbl-to-orgtbl
2280 (or (eq e
'hline
) (listp e
)))
2287 (when (org-at-table-p) (org-table-align))
2288 (goto-char (org-table-end)))
2289 ;; Print verbatim a list that cannot be turned into
2291 ((listp result
) (insert (format "%s\n" result
)))
2292 ((member "file" result-params
)
2294 (setq result
(org-macro-escape-arguments result
)))
2296 ((and inline
(not (member "raw" result-params
)))
2297 (insert (org-macro-escape-arguments
2298 (org-babel-chomp result
"\n"))))
2299 (t (goto-char beg
) (insert result
)))
2300 (setq end
(point-marker))
2301 ;; possibly wrap result
2303 ((assoc :wrap
(nth 2 info
))
2304 (let ((name (or (cdr (assoc :wrap
(nth 2 info
))) "RESULTS")))
2305 (funcall wrap
(concat "#+BEGIN_" name
)
2306 (concat "#+END_" (car (org-split-string name
)))
2307 nil nil
(concat "{{{results(@@" name
":") "@@)}}}")))
2308 ((member "html" result-params
)
2309 (funcall wrap
"#+BEGIN_EXPORT html" "#+END_EXPORT" nil nil
2310 "{{{results(@@html:" "@@)}}}"))
2311 ((member "latex" result-params
)
2312 (funcall wrap
"#+BEGIN_EXPORT latex" "#+END_EXPORT" nil nil
2313 "{{{results(@@latex:" "@@)}}}"))
2314 ((member "org" result-params
)
2315 (goto-char beg
) (if (org-at-table-p) (org-cycle))
2316 (funcall wrap
"#+BEGIN_SRC org" "#+END_SRC" nil nil
2317 "{{{results(src_org{" "})}}}"))
2318 ((member "code" result-params
)
2319 (let ((lang (or lang
"none")))
2320 (funcall wrap
(format "#+BEGIN_SRC %s%s" lang results-switches
)
2322 (format "{{{results(src_%s[%s]{" lang results-switches
)
2324 ((member "raw" result-params
)
2325 (goto-char beg
) (if (org-at-table-p) (org-cycle)))
2326 ((or (member "drawer" result-params
)
2327 ;; Stay backward compatible with <7.9.2
2328 (member "wrap" result-params
))
2329 (goto-char beg
) (if (org-at-table-p) (org-cycle))
2330 (funcall wrap
":RESULTS:" ":END:" 'no-escape nil
2331 "{{{results(" ")}}}"))
2332 ((and inline
(member "file" result-params
))
2333 (funcall wrap nil nil nil nil
"{{{results(" ")}}}"))
2334 ((and (not (funcall tabulablep result
))
2335 (not (member "file" result-params
)))
2336 (let ((org-babel-inline-result-wrap
2337 ;; Hard code {{{results(...)}}} on top of customization.
2338 (format "{{{results(%s)}}}"
2339 org-babel-inline-result-wrap
)))
2340 (org-babel-examplify-region beg end results-switches inline
)
2341 (setq end
(point))))))
2342 ;; Possibly indent results in par with #+results line.
2343 (when (and (not inline
) (numberp indent
) (> indent
0)
2344 ;; In this case `table-align' does the work
2346 (not (and (listp result
)
2347 (member "append" result-params
))))
2348 (indent-rigidly beg end indent
))
2350 (if (member "value" result-params
)
2351 (message "Code block returned no value.")
2352 (message "Code block produced no output."))
2353 (message "Code block evaluation complete.")))
2354 (when outside-scope
(narrow-to-region visible-beg visible-end
))
2355 (set-marker visible-beg nil
)
2356 (set-marker visible-end nil
)))))))
2358 (defun org-babel-remove-result (&optional info keep-keyword
)
2359 "Remove the result of the current source block."
2361 (let ((location (org-babel-where-is-src-block-result nil info
)))
2364 (goto-char location
)
2365 (when (looking-at (concat org-babel-result-regexp
".*$"))
2367 (if keep-keyword
(1+ (match-end 0)) (1- (match-beginning 0)))
2368 (progn (forward-line 1) (org-babel-result-end))))))))
2370 (defun org-babel-remove-inline-result (&optional datum
)
2371 "Remove the result of the current inline-src-block or babel call.
2372 The result must be wrapped in a `results' macro to be removed.
2373 Leading white space is trimmed."
2375 (let* ((el (or datum
(org-element-context))))
2376 (when (memq (org-element-type el
) '(inline-src-block inline-babel-call
))
2377 (org-with-wide-buffer
2378 (goto-char (org-element-property :end el
))
2379 (skip-chars-backward " \t")
2380 (let ((result (save-excursion
2383 (org-element-property
2384 :contents-end
(org-element-property :parent el
)))
2385 (org-element-context))))
2386 (when (and (eq (org-element-type result
) 'macro
)
2387 (string= (org-element-property :key result
) "results"))
2388 (delete-region ; And leading whitespace.
2390 (progn (goto-char (org-element-property :end result
))
2391 (skip-chars-backward " \t\n")
2394 (defun org-babel-remove-result-one-or-many (x)
2395 "Remove the result of the current source block.
2396 If called with a prefix argument, remove all result blocks
2400 (org-babel-map-src-blocks nil
(org-babel-remove-result))
2401 (org-babel-remove-result)))
2403 (defun org-babel-result-end ()
2404 "Return the point at the end of the current set of results."
2407 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
2408 ((org-at-item-p) (let* ((struct (org-list-struct))
2409 (prvs (org-list-prevs-alist struct
)))
2410 (org-list-get-list-end (point-at-bol) struct prvs
)))
2411 ((let ((case-fold-search t
)) (looking-at "^\\([ \t]*\\):results:"))
2412 (progn (re-search-forward (concat "^" (match-string 1) ":END:"))
2413 (forward-char 1) (point)))
2415 (let ((case-fold-search t
))
2416 (if (looking-at (concat "[ \t]*#\\+begin_\\([^ \t\n\r]+\\)"))
2417 (progn (re-search-forward (concat "[ \t]*#\\+end_" (match-string 1))
2420 (while (looking-at "[ \t]*\\(: \\|:$\\|\\[\\[\\)")
2424 (defun org-babel-result-to-file (result &optional description
)
2425 "Convert RESULT into an `org-mode' link with optional DESCRIPTION.
2426 If the `default-directory' is different from the containing
2427 file's directory then expand relative links."
2428 (when (stringp result
)
2429 (format "[[file:%s]%s]"
2430 (if (and default-directory
2432 (not (string= (expand-file-name default-directory
)
2434 (file-name-directory buffer-file-name
)))))
2435 (expand-file-name result default-directory
)
2437 (if description
(concat "[" description
"]") ""))))
2439 (defvar org-babel-capitalize-example-region-markers nil
2440 "Make true to capitalize begin/end example markers inserted by code blocks.")
2442 (define-obsolete-function-alias
2443 'org-babel-examplize-region
2444 'org-babel-examplify-region
"25.1")
2446 (defun org-babel-examplify-region (beg end
&optional results-switches inline
)
2447 "Comment out region using the inline `==' or `: ' org example quote."
2451 (if org-babel-capitalize-example-region-markers
(upcase str
) str
))))
2455 (insert (format org-babel-inline-result-wrap
2456 (delete-and-extract-region beg end
))))
2457 (let ((size (count-lines beg end
)))
2459 (cond ((= size
0)) ; do nothing for an empty result
2460 ((< size org-babel-min-lines-for-block-output
)
2463 (beginning-of-line 1) (insert ": ") (forward-line 1)))
2466 (insert (if results-switches
2468 (funcall maybe-cap
"#+begin_example")
2470 (funcall maybe-cap
"#+begin_example\n")))
2471 (if (markerp end
) (goto-char end
) (forward-char (- end beg
)))
2472 (insert (funcall maybe-cap
"#+end_example\n")))))))))
2474 (defun org-babel-update-block-body (new-body)
2475 "Update the body of the current code block to NEW-BODY."
2476 (let ((element (org-element-at-point)))
2477 (unless (eq (org-element-type element
) 'src-block
)
2478 (error "Not in a source block"))
2479 (goto-char (org-babel-where-is-src-block-head element
))
2480 (let* ((ind (org-get-indentation))
2481 (body-start (line-beginning-position 2))
2482 (body (org-element-normalize-string
2483 (if (or org-src-preserve-indentation
2484 (org-element-property :preserve-indent element
))
2487 (insert (org-remove-indentation new-body
))
2491 (+ ind org-edit-src-content-indentation
))
2492 (buffer-string))))))
2493 (delete-region body-start
2494 (org-with-wide-buffer
2495 (goto-char (org-element-property :end element
))
2496 (skip-chars-backward " \t\n")
2497 (line-beginning-position)))
2498 (goto-char body-start
)
2501 (defun org-babel-merge-params (&rest plists
)
2502 "Combine all parameter association lists in PLISTS.
2503 Later elements of PLISTS override the values of previous elements.
2504 This takes into account some special considerations for certain
2505 parameters when merging lists."
2506 (let* ((results-exclusive-groups
2507 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2508 (cdr (assoc 'results org-babel-common-header-args-w-values
))))
2509 (exports-exclusive-groups
2510 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2511 (cdr (assoc 'exports org-babel-common-header-args-w-values
))))
2513 (e-merge (lambda (exclusive-groups &rest result-params
)
2514 ;; maintain exclusivity of mutually exclusive parameters
2516 (mapc (lambda (new-params)
2517 (mapc (lambda (new-param)
2518 (mapc (lambda (exclusive-group)
2519 (when (member new-param exclusive-group
)
2520 (mapcar (lambda (excluded-param)
2527 (setq output
(org-uniquify
2528 (cons new-param output
))))
2532 params results exports tangle noweb cache vars shebang comments padline
2541 (let ((name (if (listp (cdr pair
))
2543 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
2545 (intern (match-string 1 (cdr pair
)))))))
2549 (if (member name
(mapcar #'car vars
))
2551 (push name clearnames
)
2555 (unless (equal (car p
) name
) p
))
2558 (list (cons name pair
))))
2559 ;; if no name is given and we already have named variables
2560 ;; then assign to named variables in order
2561 (if (and vars
(nth variable-index vars
))
2562 (let ((name (car (nth variable-index vars
))))
2563 (push name clearnames
) ; clear out colnames
2566 (prog1 (setf (cddr (nth variable-index vars
))
2567 (concat (symbol-name name
) "=" (cdr pair
)))
2568 (incf variable-index
)))
2569 (error "Variable \"%s\" must be assigned a default value"
2572 (setq results
(funcall e-merge results-exclusive-groups
2575 (let ((r (cdr pair
)))
2576 (if (stringp r
) r
(eval r
)))))))
2579 (setq results
(funcall e-merge results-exclusive-groups
2581 (unless (or (member "both" exports
)
2582 (member "none" exports
)
2583 (member "code" exports
))
2584 (setq exports
(funcall e-merge exports-exclusive-groups
2585 exports
'("results"))))
2586 (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))
2589 (setq results
(funcall e-merge results-exclusive-groups
2591 (unless (or (member "both" exports
)
2592 (member "none" exports
)
2593 (member "code" exports
))
2594 (setq exports
(funcall e-merge exports-exclusive-groups
2595 exports
'("results"))))
2596 (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))
2598 (setq exports
(funcall e-merge exports-exclusive-groups
2600 (split-string (or (cdr pair
) "")))))
2601 (:tangle
;; take the latest -- always overwrite
2602 (setq tangle
(or (list (cdr pair
)) tangle
)))
2604 (setq noweb
(funcall e-merge
2605 '(("yes" "no" "tangle" "no-export"
2606 "strip-export" "eval"))
2608 (split-string (or (cdr pair
) "")))))
2610 (setq cache
(funcall e-merge
'(("yes" "no")) cache
2611 (split-string (or (cdr pair
) "")))))
2613 (setq padline
(funcall e-merge
'(("yes" "no")) padline
2614 (split-string (or (cdr pair
) "")))))
2615 (:shebang
;; take the latest -- always overwrite
2616 (setq shebang
(or (list (cdr pair
)) shebang
)))
2618 (setq comments
(funcall e-merge
'(("yes" "no")) comments
2619 (split-string (or (cdr pair
) "")))))
2620 (t ;; replace: this covers e.g. :session
2621 (setq params
(cons pair
(assq-delete-all (car pair
) params
))))))
2624 (setq vars
(reverse vars
))
2625 (while vars
(setq params
(cons (cons :var
(cddr (pop vars
))) params
)))
2626 ;; clear out col-names and row-names for replaced variables
2631 (when (assoc param params
)
2632 (setf (cdr (assoc param params
))
2633 (cl-remove-if (lambda (pair) (equal (car pair
) name
))
2634 (cdr (assoc param params
))))
2635 (setf params
(cl-remove-if (lambda (pair) (and (equal (car pair
) param
)
2638 (list :colname-names
:rowname-names
)))
2642 (let ((key (intern (concat ":" (symbol-name hd
))))
2644 (setf params
(cons (cons key
(mapconcat 'identity val
" ")) params
))))
2645 '(results exports tangle noweb padline cache shebang comments
))
2648 (defvar org-babel-use-quick-and-dirty-noweb-expansion nil
2649 "Set to true to use regular expressions to expand noweb references.
2650 This results in much faster noweb reference expansion but does
2651 not properly allow code blocks to inherit the \":noweb-ref\"
2652 header argument from buffer or subtree wide properties.")
2654 (defun org-babel-noweb-p (params context
)
2655 "Check if PARAMS require expansion in CONTEXT.
2656 CONTEXT may be one of :tangle, :export or :eval."
2658 (intersect (lambda (as bs
)
2660 (if (member (car as
) bs
)
2662 (funcall intersect
(cdr as
) bs
))))))
2663 (funcall intersect
(case context
2664 (:tangle
'("yes" "tangle" "no-export" "strip-export"))
2665 (:eval
'("yes" "no-export" "strip-export" "eval"))
2667 (split-string (or (cdr (assoc :noweb params
)) "")))))
2669 (defun org-babel-expand-noweb-references (&optional info parent-buffer
)
2670 "Expand Noweb references in the body of the current source code block.
2672 For example the following reference would be replaced with the
2673 body of the source-code block named `example-block'.
2677 Note that any text preceding the <<foo>> construct on a line will
2678 be interposed between the lines of the replacement text. So for
2679 example if <<foo>> is placed behind a comment, then the entire
2680 replacement text will also be commented.
2682 This function must be called from inside of the buffer containing
2683 the source-code block which holds BODY.
2685 In addition the following syntax can be used to insert the
2686 results of evaluating the source-code block named `example-block'.
2690 Any optional arguments can be passed to example-block by placing
2691 the arguments inside the parenthesis following the convention
2692 defined by `org-babel-lob'. For example
2694 <<example-block(a=9)>>
2696 would set the value of argument \"a\" equal to \"9\". Note that
2697 these arguments are not evaluated in the current source-code
2698 block but are passed literally to the \"example-block\"."
2699 (let* ((parent-buffer (or parent-buffer
(current-buffer)))
2700 (info (or info
(org-babel-get-src-block-info 'light
)))
2703 (ob-nww-start org-babel-noweb-wrap-start
)
2704 (ob-nww-end org-babel-noweb-wrap-end
)
2705 (comment (string= "noweb" (cdr (assoc :comments
(nth 2 info
)))))
2706 (rx-prefix (concat "\\(" org-babel-src-name-regexp
"\\|"
2707 ":noweb-ref[ \t]+" "\\)"))
2709 (nb-add (lambda (text) (setq new-body
(concat new-body text
))))
2710 (c-wrap (lambda (text)
2712 (funcall (intern (concat lang
"-mode")))
2713 (comment-region (point) (progn (insert text
) (point)))
2714 (org-babel-trim (buffer-string)))))
2715 index source-name evaluate prefix
)
2717 (setq-local org-babel-noweb-wrap-start ob-nww-start
)
2718 (setq-local org-babel-noweb-wrap-end ob-nww-end
)
2719 (insert body
) (goto-char (point-min))
2720 (setq index
(point))
2721 (while (and (re-search-forward (org-babel-noweb-wrap) nil t
))
2722 (save-match-data (setf source-name
(match-string 1)))
2723 (save-match-data (setq evaluate
(string-match "(.*)" source-name
)))
2726 (buffer-substring (match-beginning 0)
2728 (beginning-of-line 1) (point)))))
2729 ;; add interval to new-body (removing noweb reference)
2730 (goto-char (match-beginning 0))
2731 (funcall nb-add
(buffer-substring index
(point)))
2732 (goto-char (match-end 0))
2733 (setq index
(point))
2736 (with-current-buffer parent-buffer
2739 (mapconcat ;; Interpose PREFIX between every line.
2743 (let ((raw (org-babel-ref-resolve source-name
)))
2744 (if (stringp raw
) raw
(format "%S" raw
)))
2746 ;; Retrieve from the library of babel.
2747 (nth 2 (assoc (intern source-name
)
2748 org-babel-library-of-babel
))
2749 ;; Return the contents of headlines literally.
2751 (when (org-babel-ref-goto-headline-id source-name
)
2752 (org-babel-ref-headline-body)))
2753 ;; Find the expansion of reference in this buffer.
2754 (let ((rx (concat rx-prefix source-name
"[ \t\n]"))
2757 (goto-char (point-min))
2758 (if org-babel-use-quick-and-dirty-noweb-expansion
2759 (while (re-search-forward rx nil t
)
2760 (let* ((i (org-babel-get-src-block-info 'light
))
2761 (body (org-babel-expand-noweb-references i
))
2762 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2765 (let ((cs (org-babel-tangle-comment-links i
)))
2766 (concat (funcall c-wrap
(car cs
)) "\n"
2768 (funcall c-wrap
(cadr cs
))))
2770 (setq expansion
(cons sep
(cons full expansion
)))))
2771 (org-babel-map-src-blocks nil
2772 (let ((i (org-babel-get-src-block-info 'light
)))
2773 (when (equal (or (cdr (assoc :noweb-ref
(nth 2 i
)))
2776 (let* ((body (org-babel-expand-noweb-references i
))
2777 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2780 (let ((cs (org-babel-tangle-comment-links i
)))
2781 (concat (funcall c-wrap
(car cs
)) "\n"
2783 (funcall c-wrap
(cadr cs
))))
2786 (cons sep
(cons full expansion
)))))))))
2788 (mapconcat #'identity
(nreverse (cdr expansion
)) "")))
2789 ;; Possibly raise an error if named block doesn't exist.
2790 (if (or org-babel-noweb-error-all-langs
2791 (member lang org-babel-noweb-error-langs
))
2793 (org-babel-noweb-wrap source-name
)
2794 "could not be resolved (see "
2795 "`org-babel-noweb-error-langs')"))
2797 "[\n\r]") (concat "\n" prefix
))))))
2798 (funcall nb-add
(buffer-substring index
(point-max))))
2801 (defun org-babel--script-escape-inner (str)
2802 (let (in-single in-double backslash out
)
2809 (setq backslash nil
)
2811 ((and in-single
(eq ch ?
'))
2812 ;; Escaped single quote inside single quoted string:
2813 ;; emit just a single quote, since we've changed the
2814 ;; outer quotes to double.
2817 ;; Escaped double quote
2819 ;; This should be interpreted as backslash+quote,
2820 ;; not an escape. Emit a three backslashes
2821 ;; followed by a quote (because one layer of
2822 ;; quoting will be stripped by `org-babel-read').
2823 (append (list ch ?
\\ ?
\\ ?
\\) out
)
2824 ;; Otherwise we are in a double-quoted string. Emit
2825 ;; a single escaped quote
2826 (append (list ch ?
\\) out
)))
2828 ;; Escaped backslash: emit a single escaped backslash
2829 (append (list ?
\\ ?
\\) out
))
2830 ;; Other: emit a quoted backslash followed by whatever
2831 ;; the character was (because one layer of quoting will
2832 ;; be stripped by `org-babel-read').
2833 (t (append (list ch ?
\\ ?
\\) out
))))
2835 (?\
[ (if (or in-double in-single
)
2838 (?\
] (if (or in-double in-single
)
2841 (?\
{ (if (or in-double in-single
)
2844 (?\
} (if (or in-double in-single
)
2847 (?
, (if (or in-double in-single
)
2848 (cons ?
, out
) (cons ?\s out
)))
2851 (setq in-single
(not in-single
)) (cons ?
\" out
)))
2853 (append (list ?
\" ?
\\) out
)
2854 (setq in-double
(not in-double
)) (cons ?
\" out
)))
2855 (?
\\ (unless (or in-single in-double
)
2856 (error "Can't handle backslash outside string in `org-babel-script-escape'"))
2859 (t (cons ch out
))))))
2860 (string-to-list str
))
2861 (when (or in-single in-double
)
2862 (error "Unterminated string in `org-babel-script-escape'"))
2863 (apply #'string
(reverse out
))))
2865 (defun org-babel-script-escape (str &optional force
)
2866 "Safely convert tables into elisp lists."
2867 (unless (stringp str
)
2868 (error "`org-babel-script-escape' expects a string"))
2871 ((and (> (length str
) 2)
2872 (or (and (string-equal "[" (substring str
0 1))
2873 (string-equal "]" (substring str -
1)))
2874 (and (string-equal "{" (substring str
0 1))
2875 (string-equal "}" (substring str -
1)))
2876 (and (string-equal "(" (substring str
0 1))
2877 (string-equal ")" (substring str -
1)))))
2879 (concat "'" (org-babel--script-escape-inner str
)))
2881 (and (> (length str
) 2)
2882 (or (and (string-equal "'" (substring str
0 1))
2883 (string-equal "'" (substring str -
1)))
2884 ;; We need to pass double-quoted strings
2885 ;; through the backslash-twiddling bits, even
2886 ;; though we don't need to change their
2888 (and (string-equal "\"" (substring str
0 1))
2889 (string-equal "\"" (substring str -
1))))))
2890 (org-babel--script-escape-inner str
))
2892 (condition-case nil
(org-babel-read escaped
) (error escaped
))))
2894 (defun org-babel-read (cell &optional inhibit-lisp-eval
)
2895 "Convert the string value of CELL to a number if appropriate.
2896 Otherwise if CELL looks like lisp (meaning it starts with a
2897 \"(\", \"\\='\", \"\\=`\" or a \"[\") then read and evaluate it as
2898 lisp, otherwise return it unmodified as a string. Optional
2899 argument INHIBIT-LISP-EVAL inhibits lisp evaluation for
2900 situations in which is it not appropriate."
2901 (if (and (stringp cell
) (not (equal cell
"")))
2902 (or (org-babel-number-p cell
)
2903 (if (and (not inhibit-lisp-eval
)
2904 (or (member (substring cell
0 1) '("(" "'" "`" "["))
2905 (string= cell
"*this*")))
2907 (if (string= (substring cell
0 1) "\"")
2909 (progn (set-text-properties 0 (length cell
) nil cell
) cell
))))
2912 (defun org-babel-number-p (string)
2913 "If STRING represents a number return its value."
2914 (if (and (string-match "[0-9]+" string
)
2915 (string-match "^-?[0-9]*\\.?[0-9]*$" string
)
2916 (= (length (substring string
(match-beginning 0)
2919 (string-to-number string
)))
2921 (defun org-babel-import-elisp-from-file (file-name &optional separator
)
2922 "Read the results located at FILE-NAME into an elisp table.
2923 If the table is trivial, then return it as a scalar."
2925 (save-window-excursion
2929 (org-table-import file-name separator
)
2930 (delete-file file-name
)
2931 (setq result
(mapcar (lambda (row)
2932 (mapcar #'org-babel-string-read row
))
2933 (org-table-to-lisp))))
2934 (error (message "Error reading results: %s" err
) nil
)))
2935 (if (null (cdr result
)) ;; if result is trivial vector, then scalarize it
2936 (if (consp (car result
))
2937 (if (null (cdr (car result
)))
2943 (defun org-babel-string-read (cell)
2944 "Strip nested \"s from around strings."
2945 (org-babel-read (or (and (stringp cell
)
2946 (string-match "\\\"\\(.+\\)\\\"" cell
)
2947 (match-string 1 cell
))
2950 (defun org-babel-chomp (string &optional regexp
)
2951 "Strip a trailing space or carriage return from STRING.
2952 The default regexp used is \"[ \\f\\t\\n\\r\\v]\" but another one
2953 can be specified as the REGEXP argument."
2954 (let ((regexp (or regexp
"[ \f\t\n\r\v]")))
2955 (while (and (> (length string
) 0)
2956 (string-match regexp
(substring string -
1)))
2957 (setq string
(substring string
0 -
1)))
2960 (defun org-babel-trim (string &optional regexp
)
2961 "Strip a leading and trailing space or carriage return from STRING.
2962 Like `org-babel-chomp', but run on both the first and last
2963 character of the string."
2966 (org-babel-chomp (org-reverse-string string
) regexp
)) regexp
))
2968 (defun org-babel-local-file-name (file)
2969 "Return the local name component of FILE."
2970 (or (file-remote-p file
'localname
) file
))
2972 (defun org-babel-process-file-name (name &optional no-quote-p
)
2973 "Prepare NAME to be used in an external process.
2974 If NAME specifies a remote location, the remote portion of the
2975 name is removed, since in that case the process will be executing
2976 remotely. The file name is then processed by `expand-file-name'.
2977 Unless second argument NO-QUOTE-P is non-nil, the file name is
2978 additionally processed by `shell-quote-argument'"
2979 (let ((f (org-babel-local-file-name (expand-file-name name
))))
2980 (if no-quote-p f
(shell-quote-argument f
))))
2982 (defvar org-babel-temporary-directory
)
2983 (unless (or noninteractive
(boundp 'org-babel-temporary-directory
))
2984 (defvar org-babel-temporary-directory
2985 (or (and (boundp 'org-babel-temporary-directory
)
2986 (file-exists-p org-babel-temporary-directory
)
2987 org-babel-temporary-directory
)
2988 (make-temp-file "babel-" t
))
2989 "Directory to hold temporary files created to execute code blocks.
2990 Used by `org-babel-temp-file'. This directory will be removed on
2993 (defcustom org-babel-remote-temporary-directory
"/tmp/"
2994 "Directory to hold temporary files on remote hosts."
2998 (defmacro org-babel-result-cond
(result-params scalar-form
&rest table-forms
)
2999 "Call the code to parse raw string results according to RESULT-PARAMS."
3001 (debug (form form
&rest form
)))
3002 (org-with-gensyms (params)
3003 `(let ((,params
,result-params
))
3004 (unless (member "none" ,params
)
3005 (if (or (member "scalar" ,params
)
3006 (member "verbatim" ,params
)
3007 (member "html" ,params
)
3008 (member "code" ,params
)
3009 (member "pp" ,params
)
3010 (member "file" ,params
)
3011 (and (or (member "output" ,params
)
3012 (member "raw" ,params
)
3013 (member "org" ,params
)
3014 (member "drawer" ,params
))
3015 (not (member "table" ,params
))))
3018 (def-edebug-spec org-babel-result-cond
(form form body
))
3020 (defun org-babel-temp-file (prefix &optional suffix
)
3021 "Create a temporary file in the `org-babel-temporary-directory'.
3022 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
3023 value of `temporary-file-directory' temporarily set to the value
3024 of `org-babel-temporary-directory'."
3025 (if (file-remote-p default-directory
)
3027 (concat (file-remote-p default-directory
)
3029 prefix org-babel-remote-temporary-directory
))))
3030 (make-temp-file prefix nil suffix
))
3031 (let ((temporary-file-directory
3032 (or (and (boundp 'org-babel-temporary-directory
)
3033 (file-exists-p org-babel-temporary-directory
)
3034 org-babel-temporary-directory
)
3035 temporary-file-directory
)))
3036 (make-temp-file prefix nil suffix
))))
3038 (defun org-babel-remove-temporary-directory ()
3039 "Remove `org-babel-temporary-directory' on Emacs shutdown."
3040 (when (and (boundp 'org-babel-temporary-directory
)
3041 (file-exists-p org-babel-temporary-directory
))
3042 ;; taken from `delete-directory' in files.el
3045 (mapc (lambda (file)
3046 ;; This test is equivalent to
3047 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
3048 ;; but more efficient
3049 (if (eq t
(car (file-attributes file
)))
3050 (delete-directory file
)
3051 (delete-file file
)))
3052 ;; We do not want to delete "." and "..".
3053 (directory-files org-babel-temporary-directory
'full
3054 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
3055 (delete-directory org-babel-temporary-directory
))
3057 (message "Failed to remove temporary Org-babel directory %s"
3058 (if (boundp 'org-babel-temporary-directory
)
3059 org-babel-temporary-directory
3060 "[directory not defined]"))))))
3062 (add-hook 'kill-emacs-hook
'org-babel-remove-temporary-directory
)
3064 (defun org-babel-one-header-arg-safe-p (pair safe-list
)
3065 "Determine if the PAIR is a safe babel header arg according to SAFE-LIST.
3067 For the format of SAFE-LIST, see `org-babel-safe-header-args'."
3069 (keywordp (car pair
))
3070 (stringp (cdr pair
))
3072 (memq (car pair
) safe-list
)
3073 (let ((entry (assq (car pair
) safe-list
)))
3076 (cond ((functionp (cdr entry
))
3077 (funcall (cdr entry
) (cdr pair
)))
3078 ((listp (cdr entry
))
3079 (member (cdr pair
) (cdr entry
)))
3082 (defun org-babel-generate-file-param (src-name params
)
3083 "Calculate the filename for source block results.
3085 The directory is calculated from the :output-dir property of the
3086 source block; if not specified, use the current directory.
3088 If the source block has a #+NAME and the :file parameter does not
3089 contain any period characters, then the :file parameter is
3090 treated as an extension, and the output file name is the
3091 concatenation of the directory (as calculated above), the block
3092 name, a period, and the parameter value as a file extension.
3093 Otherwise, the :file parameter is treated as a full file name,
3094 and the output file name is the directory (as calculated above)
3095 plus the parameter value."
3096 (let* ((file-cons (assq :file params
))
3097 (file-ext-cons (assq :file-ext params
))
3098 (file-ext (cdr-safe file-ext-cons
))
3099 (dir (cdr-safe (assq :output-dir params
)))
3101 ;; create the output-dir if it does not exist
3103 (make-directory dir t
))
3105 ;; :file given; add :output-dir if given
3107 (setcdr file-cons
(concat (file-name-as-directory dir
) (cdr file-cons
))))
3108 ;; :file not given; compute from name and :file-ext if possible
3109 (when (and src-name file-ext
)
3111 (setq fname
(concat (file-name-as-directory (or dir
""))
3112 src-name
"." file-ext
))
3113 (setq fname
(concat src-name
"." file-ext
)))
3114 (setq params
(cons (cons :file fname
) params
))))
3117 ;;; Used by backends: R, Maxima, Octave.
3118 (defun org-babel-graphical-output-file (params)
3119 "File where a babel block should send graphical output, per PARAMS."
3120 (unless (assq :file params
)
3121 (if (assq :file-ext params
)
3122 (user-error ":file-ext given but no :file generated; did you forget to give a block a #+NAME?")
3123 (user-error "No :file header argument given; cannot create graphical result.")))
3124 (and (member "graphics" (cdr (assq :result-params params
)))
3125 (cdr (assq :file params
))))
3127 (defun org-babel-make-language-alias (new old
)
3128 "Make source blocks of type NEW aliases for those of type OLD.
3130 NEW and OLD should be strings. This function should be called
3131 after the babel API for OLD-type source blocks is fully defined.
3133 Callers of this function will probably want to add an entry to
3134 `org-src-lang-modes' as well."
3135 (dolist (fn '("execute" "expand-body" "prep-session"
3136 "variable-assignments" "load-session"))
3137 (let ((sym (intern-soft (concat "org-babel-" fn
":" old
))))
3138 (when (and sym
(fboundp sym
))
3139 (defalias (intern (concat "org-babel-" fn
":" new
)) sym
))))
3140 ;; Technically we don't need a `dolist' for just one variable, but
3141 ;; we keep it for symmetry/ease of future expansion.
3142 (dolist (var '("default-header-args"))
3143 (let ((sym (intern-soft (concat "org-babel-" var
":" old
))))
3144 (when (and sym
(boundp sym
))
3145 (defvaralias (intern (concat "org-babel-" var
":" new
)) sym
)))))
3150 ;; generated-autoload-file: "org-loaddefs.el"
3153 ;;; ob-core.el ends here