1 ;;; ob-core.el --- working with code blocks in org-mode
3 ;; Copyright (C) 2009-2015 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
))
37 ;; dynamically scoped for tramp
38 (defvar org-babel-call-process-region-original nil
)
39 (defvar org-src-lang-modes
)
40 (defvar org-babel-library-of-babel
)
41 (declare-function outline-show-all
"outline" ())
42 (declare-function org-remove-indentation
"org" (code &optional n
))
43 (declare-function org-mark-ring-push
"org" (&optional pos buffer
))
44 (declare-function tramp-compat-make-temp-file
"tramp-compat"
45 (filename &optional dir-flag
))
46 (declare-function tramp-dissect-file-name
"tramp" (name &optional nodefault
))
47 (declare-function tramp-file-name-user
"tramp" (vec))
48 (declare-function tramp-file-name-host
"tramp" (vec))
49 (declare-function with-parsed-tramp-file-name
"tramp" (filename var
&rest body
))
50 (declare-function org-icompleting-read
"org" (&rest args
))
51 (declare-function org-edit-src-code
"org-src" (&optional code edit-buffer-name
))
52 (declare-function org-edit-src-exit
"org-src" ())
53 (declare-function org-open-at-point
"org" (&optional in-emacs reference-buffer
))
54 (declare-function org-save-outline-visibility
"org-macs" (use-markers &rest body
))
55 (declare-function org-outline-overlay-data
"org" (&optional use-markers
))
56 (declare-function org-set-outline-overlay-data
"org" (data))
57 (declare-function org-narrow-to-subtree
"org" ())
58 (declare-function org-split-string
"org" (string &optional separators
))
59 (declare-function org-entry-get
"org"
60 (pom property
&optional inherit literal-nil
))
61 (declare-function org-make-options-regexp
"org" (kwds &optional extra
))
62 (declare-function org-do-remove-indentation
"org" (&optional n
))
63 (declare-function org-next-block
"org" (arg &optional backward block-regexp
))
64 (declare-function org-previous-block
"org" (arg &optional block-regexp
))
65 (declare-function org-show-context
"org" (&optional key
))
66 (declare-function org-at-table-p
"org" (&optional table-type
))
67 (declare-function org-cycle
"org" (&optional arg
))
68 (declare-function org-uniquify
"org" (list))
69 (declare-function org-current-level
"org" ())
70 (declare-function org-table-import
"org-table" (file arg
))
71 (declare-function org-add-hook
"org-compat"
72 (hook function
&optional append local
))
73 (declare-function org-table-align
"org-table" ())
74 (declare-function org-table-end
"org-table" (&optional table-type
))
75 (declare-function orgtbl-to-generic
"org-table" (table params
))
76 (declare-function orgtbl-to-orgtbl
"org-table" (table params
))
77 (declare-function org-babel-tangle-comment-links
"ob-tangle" (&optional info
))
78 (declare-function org-babel-lob-get-info
"ob-lob" nil
)
79 (declare-function org-babel-ref-split-args
"ob-ref" (arg-string))
80 (declare-function org-babel-ref-parse
"ob-ref" (assignment))
81 (declare-function org-babel-ref-resolve
"ob-ref" (ref))
82 (declare-function org-babel-ref-goto-headline-id
"ob-ref" (id))
83 (declare-function org-babel-ref-headline-body
"ob-ref" ())
84 (declare-function org-babel-lob-execute-maybe
"ob-lob" ())
85 (declare-function org-number-sequence
"org-compat" (from &optional to inc
))
86 (declare-function org-at-item-p
"org-list" ())
87 (declare-function org-list-parse-list
"org-list" (&optional delete
))
88 (declare-function org-list-to-generic
"org-list" (LIST PARAMS
))
89 (declare-function org-list-struct
"org-list" ())
90 (declare-function org-list-prevs-alist
"org-list" (struct))
91 (declare-function org-list-get-list-end
"org-list" (item struct prevs
))
92 (declare-function org-completing-read
"org" (&rest args
))
93 (declare-function org-escape-code-in-region
"org-src" (beg end
))
94 (declare-function org-unescape-code-in-string
"org-src" (s))
95 (declare-function org-table-to-lisp
"org-table" (&optional txt
))
96 (declare-function org-reverse-string
"org" (string))
97 (declare-function org-element-context
"org-element" (&optional element
))
98 (declare-function org-element-type
"org-element" (element))
99 (declare-function org-element-at-point
"org-element" ())
100 (declare-function org-element-property
"org-element" (property element
))
101 (declare-function org-macro-escape-arguments
"org-macro" (&rest args
))
103 (defgroup org-babel nil
104 "Code block evaluation and management in `org-mode' documents."
108 (defcustom org-confirm-babel-evaluate t
109 "Confirm before evaluation.
111 Require confirmation before interactively evaluating code
112 blocks in Org-mode buffers. The default value of this variable
113 is t, meaning confirmation is required for any code block
114 evaluation. This variable can be set to nil to inhibit any
115 future confirmation requests. This variable can also be set to a
116 function which takes two arguments the language of the code block
117 and the body of the code block. Such a function should then
118 return a non-nil value if the user should be prompted for
119 execution or nil if no prompt is required.
121 Warning: Disabling confirmation may result in accidental
122 evaluation of potentially harmful code. It may be advisable
123 remove code block execution from \\[org-ctrl-c-ctrl-c] \
124 as further protection
125 against accidental code block evaluation. The
126 `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
127 remove code block execution from the \\[org-ctrl-c-ctrl-c] keybinding."
130 :type
'(choice boolean function
))
131 ;; don't allow this variable to be changed through file settings
132 (put 'org-confirm-babel-evaluate
'safe-local-variable
(lambda (x) (eq x t
)))
134 (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
136 Remove code block evaluation from the \\[org-ctrl-c-ctrl-c] key binding."
141 (defcustom org-babel-results-keyword
"RESULTS"
142 "Keyword used to name results generated by code blocks.
143 It should be \"RESULTS\". However any capitalization may be
147 :package-version
'(Org .
"8.0")
151 (eq (compare-strings "RESULTS" nil nil v nil nil t
)
154 (defcustom org-babel-noweb-wrap-start
"<<"
155 "String used to begin a noweb reference in a code block.
156 See also `org-babel-noweb-wrap-end'."
160 (defcustom org-babel-noweb-wrap-end
">>"
161 "String used to end a noweb reference in a code block.
162 See also `org-babel-noweb-wrap-start'."
166 (defcustom org-babel-inline-result-wrap
"=%s="
167 "Format string used to wrap inline results.
168 This string must include a \"%s\" which will be replaced by the results."
171 (put 'org-babel-inline-result-wrap
175 (string-match-p "%s" value
))))
177 (defun org-babel-noweb-wrap (&optional regexp
)
178 (concat org-babel-noweb-wrap-start
179 (or regexp
"\\([^ \t\n].+?[^ \t]\\|[^ \t\n]\\)")
180 org-babel-noweb-wrap-end
))
182 (defvar org-babel-src-name-regexp
183 "^[ \t]*#\\+name:[ \t]*"
184 "Regular expression used to match a source name line.")
186 (defvar org-babel-multi-line-header-regexp
187 "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
188 "Regular expression used to match multi-line header arguments.")
190 (defvar org-babel-src-block-regexp
192 ;; (1) indentation (2) lang
193 "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
195 "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
196 ;; (4) header arguments
199 "\\([^\000]*?\n\\)??[ \t]*#\\+end_src")
200 "Regexp used to identify code blocks.")
202 (defvar org-babel-inline-src-block-regexp
204 ;; (1) replacement target (2) lang
205 "\\(?:^\\|[^-[:alnum:]]?\\)\\(src_\\([^ \f\t\n\r\v[]+\\)"
206 ;; (3,4) (unused, headers)
207 "\\(\\|\\[[ \t]*\\(.*?\\)\\]\\)"
209 "{\\([^\f\n\r\v]+?\\)}\\)")
210 "Regexp used to identify inline src-blocks.")
212 (defun org-babel--get-vars (params)
213 "Return the babel variable assignments in PARAMS.
215 PARAMS is a quasi-alist of header args, whcih may contain
216 multiple entries for the key `:var'. This function returns a
217 list of the cdr of all the `:var' entries."
219 (cl-remove-if-not (lambda (x) (eq (car x
) :var
)) params
)))
221 (defun org-babel-get-inline-src-block-matches ()
222 "Set match data if within body of an inline source block.
223 Returns non-nil if match-data set"
225 (let ((datum (org-element-context)))
226 (when (eq (org-element-type datum
) 'inline-src-block
)
227 (goto-char (org-element-property :begin datum
))
228 (when (looking-at org-babel-inline-src-block-regexp
)
231 (defvar org-babel-inline-lob-one-liner-regexp
)
232 (defun org-babel-get-lob-one-liner-matches ()
233 "Set match data if on line of an lob one liner.
234 Returns non-nil if match-data set"
236 (let ((datum (org-element-context)))
237 (when (eq (org-element-type datum
) 'inline-babel-call
)
238 (goto-char (org-element-property :begin datum
))))
239 (if (looking-at org-babel-inline-lob-one-liner-regexp
)
243 (defun org-babel-get-src-block-info (&optional light
)
244 "Get information on the current source block.
246 Optional argument LIGHT does not resolve remote variable
247 references; a process which could likely result in the execution
248 of other code blocks.
251 (language body header-arguments-alist switches name indent block-head)."
252 (let ((case-fold-search t
) head info name indent
)
254 (if (setq head
(org-babel-where-is-src-block-head))
257 (setq info
(org-babel-parse-src-block-match))
258 (setq indent
(car (last info
)))
259 (setq info
(butlast info
))
260 (while (and (forward-line -
1)
261 (looking-at org-babel-multi-line-header-regexp
))
263 (org-babel-merge-params
265 (org-babel-parse-header-arguments (match-string 1)))))
266 (when (looking-at (org-babel-named-src-block-regexp-for-name))
267 (setq name
(org-match-string-no-properties 9))))
268 ;; inline source block
269 (when (org-babel-get-inline-src-block-matches)
270 (setq head
(match-beginning 0))
271 (setq info
(org-babel-parse-inline-src-block-match))))
272 ;; resolve variable references and add summary parameters
273 (when (and info
(not light
))
274 (setf (nth 2 info
) (org-babel-process-params (nth 2 info
))))
276 (setf (nth 2 info
) (org-babel-generate-file-param name
(nth 2 info
))))
277 (when info
(append info
(list name indent head
)))))
279 (defvar org-babel-exp-reference-buffer nil
280 "Buffer containing original contents of the exported buffer.
281 This is used by Babel to resolve references in source blocks.
282 Its value is dynamically bound during export.")
284 (defun org-babel-check-confirm-evaluate (info)
285 "Check whether INFO allows code block evaluation.
287 Returns nil if evaluation is disallowed, t if it is
288 unconditionally allowed, and the symbol `query' if the user
289 should be asked whether to allow evaluation."
290 (let* ((headers (nth 2 info
))
291 (eval (or (cdr (assq :eval headers
))
292 (when (assq :noeval headers
) "no")))
293 (eval-no (member eval
'("no" "never")))
294 (export org-babel-exp-reference-buffer
)
295 (eval-no-export (and export
(member eval
'("no-export" "never-export"))))
296 (noeval (or eval-no eval-no-export
))
297 (query (or (equal eval
"query")
298 (and export
(equal eval
"query-export"))
299 (if (functionp org-confirm-babel-evaluate
)
301 (goto-char (nth 6 info
))
302 (funcall org-confirm-babel-evaluate
303 ;; language, code block body
304 (nth 0 info
) (nth 1 info
)))
305 org-confirm-babel-evaluate
))))
311 (defun org-babel-check-evaluate (info)
312 "Check if code block INFO should be evaluated.
314 Do not query the user, but do display an informative message if
315 evaluation is blocked. Returns non-nil if evaluation is not blocked."
316 (let ((evalp (org-babel-check-confirm-evaluate info
)))
318 (message "Evaluation of this %s code-block%sis disabled."
320 (let ((name (nth 4 info
))) (if name
(format " (%s) " name
) ""))))
323 ;; Dynamically scoped for asynchronous export.
324 (defvar org-babel-confirm-evaluate-answer-no
)
326 (defun org-babel-confirm-evaluate (info)
327 "Confirm evaluation of the code block INFO.
329 This query can also be suppressed by setting the value of
330 `org-confirm-babel-evaluate' to nil, in which case all future
331 interactive code block evaluations will proceed without any
332 confirmation from the user.
334 Note disabling confirmation may result in accidental evaluation
335 of potentially harmful code.
337 The variable `org-babel-confirm-evaluate-answer-no' is used by
338 the async export process, which requires a non-interactive
339 environment, to override this check."
340 (let* ((evalp (org-babel-check-confirm-evaluate info
))
343 (name-string (if name
(format " (%s) " name
) " ")))
348 (and (not (org-bound-and-true-p
349 org-babel-confirm-evaluate-answer-no
))
351 (format "Evaluate this %s code block%son your system? "
354 (message "Evaluation of this %s code-block%sis aborted."
357 (x (error "Unexpected value `%s' from `org-babel-check-confirm-evaluate'" x
)))))
360 (defun org-babel-execute-safely-maybe ()
361 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
362 (org-babel-execute-maybe)))
364 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-execute-safely-maybe
)
367 (defun org-babel-execute-maybe ()
369 (or (org-babel-execute-src-block-maybe)
370 (org-babel-lob-execute-maybe)))
372 (defmacro org-babel-when-in-src-block
(&rest body
)
373 "Execute BODY if point is in a source block and return t.
375 Otherwise do nothing and return nil."
376 `(if (or (org-babel-where-is-src-block-head)
377 (org-babel-get-inline-src-block-matches))
383 (defun org-babel-execute-src-block-maybe ()
384 "Conditionally execute a source block.
385 Detect if this is context for a Babel src-block and if so
386 then run `org-babel-execute-src-block'."
388 (org-babel-when-in-src-block
389 (org-babel-eval-wipe-error-buffer)
390 (org-babel-execute-src-block current-prefix-arg
)))
393 (defun org-babel-view-src-block-info ()
394 "Display information on the current source block.
395 This includes header arguments, language and name, and is largely
396 a window into the `org-babel-get-src-block-info' function."
398 (let ((info (org-babel-get-src-block-info 'light
))
399 (full (lambda (it) (> (length it
) 0)))
400 (printf (lambda (fmt &rest args
) (princ (apply #'format fmt args
)))))
402 (with-help-window (help-buffer)
403 (let ((name (nth 4 info
))
405 (switches (nth 3 info
))
406 (header-args (nth 2 info
)))
407 (when name
(funcall printf
"Name: %s\n" name
))
408 (when lang
(funcall printf
"Lang: %s\n" lang
))
409 (funcall printf
"Properties:\n")
410 (funcall printf
"\t:header-args \t%s\n" (org-entry-get (point) "header-args" t
))
411 (funcall printf
"\t:header-args:%s \t%s\n" lang
(org-entry-get (point) (concat "header-args:" lang
) t
))
413 (when (funcall full switches
) (funcall printf
"Switches: %s\n" switches
))
414 (funcall printf
"Header Arguments:\n")
415 (dolist (pair (sort header-args
416 (lambda (a b
) (string< (symbol-name (car a
))
417 (symbol-name (car b
))))))
418 (when (funcall full
(format "%s" (cdr pair
)))
419 (funcall printf
"\t%S%s\t%s\n"
421 (if (> (length (format "%S" (car pair
))) 7) "" "\t")
425 (defun org-babel-expand-src-block-maybe ()
426 "Conditionally expand a source block.
427 Detect if this is context for a org-babel src-block and if so
428 then run `org-babel-expand-src-block'."
430 (org-babel-when-in-src-block
431 (org-babel-expand-src-block current-prefix-arg
)))
434 (defun org-babel-load-in-session-maybe ()
435 "Conditionally load a source block in a session.
436 Detect if this is context for a org-babel src-block and if so
437 then run `org-babel-load-in-session'."
439 (org-babel-when-in-src-block
440 (org-babel-load-in-session current-prefix-arg
)))
442 (add-hook 'org-metaup-hook
'org-babel-load-in-session-maybe
)
445 (defun org-babel-pop-to-session-maybe ()
446 "Conditionally pop to a session.
447 Detect if this is context for a org-babel src-block and if so
448 then run `org-babel-switch-to-session'."
450 (org-babel-when-in-src-block
451 (org-babel-switch-to-session current-prefix-arg
)))
453 (add-hook 'org-metadown-hook
'org-babel-pop-to-session-maybe
)
455 (defconst org-babel-common-header-args-w-values
456 '((cache .
((no yes
)))
458 (colnames .
((nil no yes
)))
459 (comments .
((no link yes org both noweb
)))
461 (eval .
((yes no no-export strip-export never-export eval never
463 (exports .
((code results both none
)))
468 (hlines .
((no yes
)))
469 (mkdirp .
((yes no
)))
472 (noweb .
((yes no tangle no-export strip-export
)))
476 (padline .
((yes no
)))
479 (results .
((file list vector table scalar verbatim
)
480 (raw html latex org code pp drawer
)
481 (replace silent none append prepend
)
483 (rownames .
((no yes
)))
487 (tangle .
((tangle yes no
:any
)))
488 (tangle-mode .
((#o755
#o555
#o444
:any
)))
492 (defconst org-babel-header-arg-names
493 (mapcar #'car org-babel-common-header-args-w-values
)
494 "Common header arguments used by org-babel.
495 Note that individual languages may define their own language
496 specific header arguments as well.")
498 (defconst org-babel-safe-header-args
499 '(:cache
:colnames
:comments
:exports
:epilogue
:hlines
:noeval
500 :noweb
:noweb-ref
:noweb-sep
:padline
:prologue
:rownames
501 :sep
:session
:tangle
:wrap
502 (:eval .
("never" "query"))
503 (:results .
(lambda (str) (not (string-match "file" str
)))))
504 "A list of safe header arguments for babel source blocks.
506 The list can have entries of the following forms:
507 - :ARG -> :ARG is always a safe header arg
508 - (:ARG . (VAL1 VAL2 ...)) -> :ARG is safe as a header arg if it is
509 `equal' to one of the VALs.
510 - (:ARG . FN) -> :ARG is safe as a header arg if the function FN
511 returns non-nil. FN is passed one
512 argument, the value of the header arg
515 (defmacro org-babel-header-args-safe-fn
(safe-list)
516 "Return a function that determines whether a list of header args are safe.
519 \(put \\='org-babel-default-header-args \\='safe-local-variable
520 (org-babel-header-args-safe-p org-babel-safe-header-args)
522 This allows org-babel languages to extend the list of safe values for
523 their `org-babel-default-header-args:foo' variable.
525 For the format of SAFE-LIST, see `org-babel-safe-header-args'."
531 (org-babel-one-header-arg-safe-p pair
,safe-list
)))
534 (defvar org-babel-default-header-args
535 '((:session .
"none") (:results .
"replace") (:exports .
"code")
536 (:cache .
"no") (:noweb .
"no") (:hlines .
"no") (:tangle .
"no"))
537 "Default arguments to use when evaluating a source block.")
538 (put 'org-babel-default-header-args
'safe-local-variable
539 (org-babel-header-args-safe-fn org-babel-safe-header-args
))
541 (defvar org-babel-default-inline-header-args
542 '((:session .
"none") (:results .
"replace")
543 (:exports .
"results") (:hlines .
"yes"))
544 "Default arguments to use when evaluating an inline source block.")
545 (put 'org-babel-default-inline-header-args
'safe-local-variable
546 (org-babel-header-args-safe-fn org-babel-safe-header-args
))
548 (defvar org-babel-data-names
'("tblname" "results" "name"))
550 (defvar org-babel-result-regexp
551 (concat "^[ \t]*#\\+"
552 (regexp-opt org-babel-data-names t
)
554 ;; FIXME The string below is `org-ts-regexp'
555 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
556 " \\)?\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*")
557 "Regular expression used to match result lines.
558 If the results are associated with a hash key then the hash will
559 be saved in the second match data.")
561 (defvar org-babel-result-w-name-regexp
562 (concat org-babel-result-regexp
563 "\\([^ ()\f\t\n\r\v]+\\)\\((\\(.*\\))\\|\\)"))
565 (defvar org-babel-min-lines-for-block-output
10
566 "The minimum number of lines for block output.
567 If number of lines of output is equal to or exceeds this
568 value, the output is placed in a #+begin_example...#+end_example
569 block. Otherwise the output is marked as literal by inserting
570 colons at the starts of the lines. This variable only takes
571 effect if the :results output option is in effect.")
573 (defvar org-babel-noweb-error-all-langs nil
574 "Raise errors when noweb references don't resolve.
575 Also see `org-babel-noweb-error-langs' to control noweb errors on
576 a language by language bases.")
578 (defvar org-babel-noweb-error-langs nil
579 "Languages for which Babel will raise literate programming errors.
580 List of languages for which errors should be raised when the
581 source code block satisfying a noweb reference in this language
582 can not be resolved. Also see `org-babel-noweb-error-all-langs'
583 to raise errors for all languages.")
585 (defvar org-babel-hash-show
4
586 "Number of initial characters to show of a hidden results hash.")
588 (defvar org-babel-hash-show-time nil
589 "Non-nil means show the time the code block was evaluated in the result hash.")
591 (defvar org-babel-after-execute-hook nil
592 "Hook for functions to be called after `org-babel-execute-src-block'")
594 (defun org-babel-named-src-block-regexp-for-name (&optional name
)
595 "This generates a regexp used to match a src block named NAME.
596 If NAME is nil, match any name. Matched name is then put in
597 match group 9. Other match groups are defined in
598 `org-babel-src-block-regexp'."
599 (concat org-babel-src-name-regexp
600 (concat (if name
(regexp-quote name
) "\\(?9:.*?\\)") "[ \t]*" )
601 "\\(?:\n[ \t]*#\\+\\S-+:.*\\)*?"
603 (substring org-babel-src-block-regexp
1)))
605 (defun org-babel-named-data-regexp-for-name (name)
606 "This generates a regexp used to match data named NAME."
607 (concat org-babel-result-regexp
(regexp-quote name
) "\\([ \t]\\|$\\)"))
610 (defvar call-process-region
)
611 (defvar org-babel-current-src-block-location nil
612 "Marker pointing to the src block currently being executed.
613 This may also point to a call line or an inline code block. If
614 multiple blocks are being executed (e.g., in chained execution
615 through use of the :var header argument) this marker points to
616 the outer-most code block.")
619 (defun org-babel-execute-src-block (&optional arg info params
)
620 "Execute the current source code block.
621 Insert the results of execution into the buffer. Source code
622 execution and the collection and formatting of results can be
623 controlled through a variety of header arguments.
625 With prefix argument ARG, force re-execution even if an existing
626 result cached in the buffer would otherwise have been returned.
628 Optionally supply a value for INFO in the form returned by
629 `org-babel-get-src-block-info'.
631 Optionally supply a value for PARAMS which will be merged with
632 the header arguments specified at the front of the source code
635 (let* ((org-babel-current-src-block-location
636 (or org-babel-current-src-block-location
638 (org-babel-where-is-src-block-head)
640 (and (org-babel-get-inline-src-block-matches)
641 (match-beginning 0))))
644 (org-babel-get-src-block-info))))
645 (cl-callf org-babel-merge-params
(nth 2 info
) params
)
646 (when (org-babel-check-evaluate info
)
647 (cl-callf org-babel-process-params
(nth 2 info
))
648 (let* ((params (nth 2 info
))
649 (cachep (and (not arg
) (cdr (assoc :cache params
))
650 (string= "yes" (cdr (assoc :cache params
)))))
651 (new-hash (when cachep
(org-babel-sha1-hash info
)))
652 (old-hash (when cachep
(org-babel-current-result-hash)))
653 (cache-current-p (and (not arg
) new-hash
654 (equal new-hash old-hash
))))
657 (save-excursion ;; return cached result
658 (goto-char (org-babel-where-is-src-block-result nil info
))
660 (skip-chars-forward " \t")
661 (let ((result (org-babel-read-result)))
662 (message (replace-regexp-in-string
663 "%" "%%" (format "%S" result
))) result
)))
664 ((org-babel-confirm-evaluate info
)
665 (let* ((lang (nth 0 info
))
666 (result-params (cdr (assoc :result-params params
)))
667 (body (setf (nth 1 info
)
668 (if (org-babel-noweb-p params
:eval
)
669 (org-babel-expand-noweb-references info
)
671 (dir (cdr (assoc :dir params
)))
673 (or (and dir
(file-name-as-directory (expand-file-name dir
)))
675 (org-babel-call-process-region-original ;; for tramp handler
676 (or (org-bound-and-true-p
677 org-babel-call-process-region-original
)
678 (symbol-function 'call-process-region
)))
679 (indent (nth 5 info
))
682 (let ((call-process-region
684 (apply 'org-babel-tramp-handle-call-process-region
688 (let ((f (intern (concat "org-babel-execute:" f
))))
689 (when (fboundp f
) f
)))))
691 (or (funcall lang-check lang
)
694 (cdr (assoc lang org-src-lang-modes
))))
695 (error "No org-babel-execute function for %s!"
697 (message "executing %s code block%s..."
699 (if (nth 4 info
) (format " (%s)" (nth 4 info
)) ""))
700 (if (member "none" result-params
)
702 (funcall cmd body params
)
703 (message "result silenced")
706 (let ((result (funcall cmd body params
)))
707 (if (and (eq (cdr (assoc :result-type params
))
709 (or (member "vector" result-params
)
710 (member "table" result-params
))
711 (not (listp result
)))
712 (list (list result
)) result
)))
713 ;; If non-empty result and :file then write to :file.
714 (when (cdr (assoc :file params
))
716 (with-temp-file (cdr (assoc :file params
))
718 (org-babel-format-result
719 result
(cdr (assoc :sep
(nth 2 info
)))))))
720 (setq result
(cdr (assoc :file params
))))
721 ;; Possibly perform post process provided its appropriate.
722 (when (cdr (assoc :post params
))
723 (let ((*this
* (if (cdr (assoc :file params
))
724 (org-babel-result-to-file
725 (cdr (assoc :file params
))
726 (when (assoc :file-desc params
)
727 (or (cdr (assoc :file-desc params
))
730 (setq result
(org-babel-ref-resolve
731 (cdr (assoc :post params
))))
732 (when (cdr (assoc :file params
))
734 (remove "file" result-params
)))))
735 (org-babel-insert-result
736 result result-params info new-hash indent lang
))
737 (run-hooks 'org-babel-after-execute-hook
)
739 (setq call-process-region
740 'org-babel-call-process-region-original
)))))))))
742 (defun org-babel-expand-body:generic
(body params
&optional var-lines
)
743 "Expand BODY with PARAMS.
744 Expand a block of code with org-babel according to its header
745 arguments. This generic implementation of body expansion is
746 called for languages which have not defined their own specific
747 org-babel-expand-body:lang function."
748 (let ((pro (cdr (assoc :prologue params
)))
749 (epi (cdr (assoc :epilogue params
))))
750 (mapconcat #'identity
751 (append (when pro
(list pro
))
754 (when epi
(list epi
)))
758 (defun org-babel-expand-src-block (&optional arg info params
)
759 "Expand the current source code block.
760 Expand according to the source code block's header
761 arguments and pop open the results in a preview buffer."
763 (let* ((info (or info
(org-babel-get-src-block-info)))
765 (params (setf (nth 2 info
)
766 (sort (org-babel-merge-params (nth 2 info
) params
)
767 (lambda (el1 el2
) (string< (symbol-name (car el1
))
768 (symbol-name (car el2
)))))))
769 (body (setf (nth 1 info
)
770 (if (org-babel-noweb-p params
:eval
)
771 (org-babel-expand-noweb-references info
) (nth 1 info
))))
772 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
773 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
776 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
777 (org-babel-expand-body:generic
778 body params
(and (fboundp assignments-cmd
)
779 (funcall assignments-cmd params
))))))
780 (if (org-called-interactively-p 'any
)
782 expanded
(concat "*Org-Babel Preview " (buffer-name) "[ " lang
" ]*"))
785 (defun org-babel-edit-distance (s1 s2
)
786 "Return the edit (levenshtein) distance between strings S1 S2."
787 (let* ((l1 (length s1
))
789 (dist (vconcat (mapcar (lambda (_) (make-vector (1+ l2
) nil
))
790 (number-sequence 1 (1+ l1
)))))
791 (in (lambda (i j
) (aref (aref dist i
) j
))))
792 (setf (aref (aref dist
0) 0) 0)
793 (dolist (j (number-sequence 1 l2
))
794 (setf (aref (aref dist
0) j
) j
))
795 (dolist (i (number-sequence 1 l1
))
796 (setf (aref (aref dist i
) 0) i
)
797 (dolist (j (number-sequence 1 l2
))
798 (setf (aref (aref dist i
) j
)
800 (1+ (funcall in
(1- i
) j
))
801 (1+ (funcall in i
(1- j
)))
802 (+ (if (equal (aref s1
(1- i
)) (aref s2
(1- j
))) 0 1)
803 (funcall in
(1- i
) (1- j
)))))))
806 (defun org-babel-combine-header-arg-lists (original &rest others
)
807 "Combine a number of lists of header argument names and arguments."
808 (let ((results (copy-sequence original
)))
809 (dolist (new-list others
)
810 (dolist (arg-pair new-list
)
811 (let ((header (car arg-pair
))
812 (args (cdr arg-pair
)))
814 (cons arg-pair
(cl-remove-if
815 (lambda (pair) (equal header
(car pair
)))
820 (defun org-babel-check-src-block ()
821 "Check for misspelled header arguments in the current code block."
823 ;; TODO: report malformed code block
824 ;; TODO: report incompatible combinations of header arguments
825 ;; TODO: report uninitialized variables
826 (let ((too-close 2) ;; <- control closeness to report potential match
827 (names (mapcar #'symbol-name org-babel-header-arg-names
)))
828 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg
)) 1))
829 (and (org-babel-where-is-src-block-head)
830 (org-babel-parse-header-arguments
832 (match-string 4))))))
834 (when (and (not (string= header name
))
835 (<= (org-babel-edit-distance header name
) too-close
)
836 (not (member header names
)))
837 (error "Supplied header \"%S\" is suspiciously close to \"%S\""
839 (message "No suspicious header arguments found.")))
842 (defun org-babel-insert-header-arg (&optional header-arg value
)
843 "Insert a header argument selecting from lists of common args and values."
845 (let* ((info (org-babel-get-src-block-info 'light
))
848 (lang-headers (intern (concat "org-babel-header-args:" lang
)))
849 (headers (org-babel-combine-header-arg-lists
850 org-babel-common-header-args-w-values
851 (when (boundp lang-headers
) (eval lang-headers
))))
852 (header-arg (or header-arg
853 (org-icompleting-read
856 (lambda (header-spec) (symbol-name (car header-spec
)))
858 (vals (cdr (assoc (intern header-arg
) headers
)))
862 (read-from-minibuffer "value: "))
866 (let ((arg (org-icompleting-read
869 (mapcar #'symbol-name group
)))))
870 (if (and arg
(not (string= "default" arg
)))
876 (goto-char (point-at-eol))
877 (unless (= (char-before (point)) ?\
) (insert " "))
878 (insert ":" header-arg
) (when value
(insert " " value
)))))
880 ;; Add support for completing-read insertion of header arguments after ":"
881 (defun org-babel-header-arg-expand ()
882 "Call `org-babel-enter-header-arg-w-completion' in appropriate contexts."
883 (when (and (equal (char-before) ?\
:) (org-babel-where-is-src-block-head))
884 (org-babel-enter-header-arg-w-completion (match-string 2))))
886 (defun org-babel-enter-header-arg-w-completion (&optional lang
)
887 "Insert header argument appropriate for LANG with completion."
888 (let* ((lang-headers-var (intern (concat "org-babel-header-args:" lang
)))
889 (lang-headers (when (boundp lang-headers-var
) (eval lang-headers-var
)))
890 (headers-w-values (org-babel-combine-header-arg-lists
891 org-babel-common-header-args-w-values lang-headers
))
892 (headers (mapcar #'symbol-name
(mapcar #'car headers-w-values
)))
893 (header (org-completing-read "Header Arg: " headers
))
894 (args (cdr (assoc (intern header
) headers-w-values
)))
895 (arg (when (and args
(listp args
))
897 (format "%s: " header
)
898 (mapcar #'symbol-name
(apply #'append args
))))))
899 (insert (concat header
" " (or arg
"")))
902 (add-hook 'org-tab-first-hook
'org-babel-header-arg-expand
)
905 (defun org-babel-load-in-session (&optional arg info
)
906 "Load the body of the current source-code block.
907 Evaluate the header arguments for the source block before
908 entering the session. After loading the body this pops open the
911 (let* ((info (or info
(org-babel-get-src-block-info)))
913 (params (nth 2 info
))
915 (user-error "No src code block at point")
917 (if (org-babel-noweb-p params
:eval
)
918 (org-babel-expand-noweb-references info
)
920 (session (cdr (assoc :session params
)))
921 (dir (cdr (assoc :dir params
)))
923 (or (and dir
(file-name-as-directory dir
)) default-directory
))
924 (cmd (intern (concat "org-babel-load-session:" lang
))))
925 (unless (fboundp cmd
)
926 (error "No org-babel-load-session function for %s!" lang
))
927 (pop-to-buffer (funcall cmd session body params
))
931 (defun org-babel-initiate-session (&optional arg info
)
932 "Initiate session for current code block.
933 If called with a prefix argument then resolve any variable
934 references in the header arguments and assign these variables in
935 the session. Copy the body of the code block to the kill ring."
937 (let* ((info (or info
(org-babel-get-src-block-info (not arg
))))
940 (params (nth 2 info
))
941 (session (cdr (assoc :session params
)))
942 (dir (cdr (assoc :dir params
)))
944 (or (and dir
(file-name-as-directory dir
)) default-directory
))
945 (init-cmd (intern (format "org-babel-%s-initiate-session" lang
)))
946 (prep-cmd (intern (concat "org-babel-prep-session:" lang
))))
947 (if (and (stringp session
) (string= session
"none"))
948 (error "This block is not using a session!"))
949 (unless (fboundp init-cmd
)
950 (error "No org-babel-initiate-session function for %s!" lang
))
951 (with-temp-buffer (insert (org-babel-trim body
))
952 (copy-region-as-kill (point-min) (point-max)))
954 (unless (fboundp prep-cmd
)
955 (error "No org-babel-prep-session function for %s!" lang
))
956 (funcall prep-cmd session params
))
957 (funcall init-cmd session params
)))
960 (defun org-babel-switch-to-session (&optional arg info
)
961 "Switch to the session of the current code block.
962 Uses `org-babel-initiate-session' to start the session. If called
963 with a prefix argument then this is passed on to
964 `org-babel-initiate-session'."
966 (pop-to-buffer (org-babel-initiate-session arg info
))
969 (defalias 'org-babel-pop-to-session
'org-babel-switch-to-session
)
971 (defvar org-src-window-setup
)
974 (defun org-babel-switch-to-session-with-code (&optional arg info
)
975 "Switch to code buffer and display session."
979 (let ((other-window-buffer (window-buffer (next-window))))
980 (set-window-buffer (next-window) (current-buffer))
981 (set-window-buffer (selected-window) other-window-buffer
))
983 (info (org-babel-get-src-block-info))
984 (org-src-window-setup 'reorganize-frame
))
986 (org-babel-switch-to-session arg info
))
988 (funcall swap-windows
)))
991 (defmacro org-babel-do-in-edit-buffer
(&rest body
)
992 "Evaluate BODY in edit buffer if there is a code block at point.
993 Return t if a code block was found at point, nil otherwise."
994 `(let ((org-src-window-setup 'switch-invisibly
))
995 (when (and (org-babel-where-is-src-block-head)
997 (unwind-protect (progn ,@body
)
1000 (def-edebug-spec org-babel-do-in-edit-buffer
(body))
1002 (defun org-babel-do-key-sequence-in-edit-buffer (key)
1003 "Read key sequence and execute the command in edit buffer.
1004 Enter a key sequence to be executed in the language major-mode
1005 edit buffer. For example, TAB will alter the contents of the
1006 Org-mode code block according to the effect of TAB in the
1007 language major-mode buffer. For languages that support
1008 interactive sessions, this can be used to send code from the Org
1009 buffer to the session for evaluation using the native major-mode
1010 evaluation mechanisms."
1011 (interactive "kEnter key-sequence to execute in edit buffer: ")
1012 (org-babel-do-in-edit-buffer
1014 (key-binding (or key
(read-key-sequence nil
))))))
1016 (defvar org-bracket-link-regexp
)
1018 (defun org-babel-active-location-p ()
1019 (memq (org-element-type (save-match-data (org-element-context)))
1020 '(babel-call inline-babel-call inline-src-block src-block
)))
1023 (defun org-babel-open-src-block-result (&optional re-run
)
1024 "If `point' is on a src block then open the results of the
1025 source code block, otherwise return nil. With optional prefix
1026 argument RE-RUN the source-code block is evaluated even if
1027 results already exist."
1029 (let ((info (org-babel-get-src-block-info 'light
)))
1032 ;; go to the results, if there aren't any then run the block
1033 (goto-char (or (and (not re-run
) (org-babel-where-is-src-block-result))
1034 (progn (org-babel-execute-src-block)
1035 (org-babel-where-is-src-block-result))))
1037 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
1039 (if (looking-at org-bracket-link-regexp
)
1042 (let ((r (org-babel-format-result
1043 (org-babel-read-result) (cdr (assoc :sep
(nth 2 info
))))))
1044 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
1045 (delete-region (point-min) (point-max))
1050 (defmacro org-babel-map-src-blocks
(file &rest body
)
1051 "Evaluate BODY forms on each source-block in FILE.
1052 If FILE is nil evaluate BODY forms on source blocks in current
1053 buffer. During evaluation of BODY the following local variables
1054 are set relative to the currently matched code block.
1056 full-block ------- string holding the entirety of the code block
1057 beg-block -------- point at the beginning of the code block
1058 end-block -------- point at the end of the matched code block
1059 lang ------------- string holding the language of the code block
1060 beg-lang --------- point at the beginning of the lang
1061 end-lang --------- point at the end of the lang
1062 switches --------- string holding the switches
1063 beg-switches ----- point at the beginning of the switches
1064 end-switches ----- point at the end of the switches
1065 header-args ------ string holding the header-args
1066 beg-header-args -- point at the beginning of the header-args
1067 end-header-args -- point at the end of the header-args
1068 body ------------- string holding the body of the code block
1069 beg-body --------- point at the beginning of the body
1070 end-body --------- point at the end of the body"
1071 (declare (indent 1))
1072 (let ((tempvar (make-symbol "file")))
1073 `(let* ((case-fold-search t
)
1075 (visited-p (or (null ,tempvar
)
1076 (get-file-buffer (expand-file-name ,tempvar
))))
1077 (point (point)) to-be-removed
)
1078 (save-window-excursion
1079 (when ,tempvar
(find-file ,tempvar
))
1080 (setq to-be-removed
(current-buffer))
1081 (goto-char (point-min))
1082 (while (re-search-forward org-babel-src-block-regexp nil t
)
1083 (when (org-babel-active-location-p)
1084 (goto-char (match-beginning 0))
1085 (let ((full-block (match-string 0))
1086 (beg-block (match-beginning 0))
1087 (end-block (match-end 0))
1088 (lang (match-string 2))
1089 (beg-lang (match-beginning 2))
1090 (end-lang (match-end 2))
1091 (switches (match-string 3))
1092 (beg-switches (match-beginning 3))
1093 (end-switches (match-end 3))
1094 (header-args (match-string 4))
1095 (beg-header-args (match-beginning 4))
1096 (end-header-args (match-end 4))
1097 (body (match-string 5))
1098 (beg-body (match-beginning 5))
1099 (end-body (match-end 5)))
1101 (goto-char end-block
)))))
1102 (unless visited-p
(kill-buffer to-be-removed
))
1103 (goto-char point
))))
1104 (def-edebug-spec org-babel-map-src-blocks
(form body
))
1107 (defmacro org-babel-map-inline-src-blocks
(file &rest body
)
1108 "Evaluate BODY forms on each inline source-block in FILE.
1109 If FILE is nil evaluate BODY forms on source blocks in current
1111 (declare (indent 1))
1112 (let ((tempvar (make-symbol "file")))
1113 `(let* ((case-fold-search t
)
1115 (visited-p (or (null ,tempvar
)
1116 (get-file-buffer (expand-file-name ,tempvar
))))
1117 (point (point)) to-be-removed
)
1118 (save-window-excursion
1119 (when ,tempvar
(find-file ,tempvar
))
1120 (setq to-be-removed
(current-buffer))
1121 (goto-char (point-min))
1122 (while (re-search-forward org-babel-inline-src-block-regexp nil t
)
1123 (when (org-babel-active-location-p)
1124 (goto-char (match-beginning 1))
1125 (save-match-data ,@body
))
1126 (goto-char (match-end 0))))
1127 (unless visited-p
(kill-buffer to-be-removed
))
1128 (goto-char point
))))
1129 (def-edebug-spec org-babel-map-inline-src-blocks
(form body
))
1131 (defvar org-babel-lob-one-liner-regexp
)
1134 (defmacro org-babel-map-call-lines
(file &rest body
)
1135 "Evaluate BODY forms on each call line in FILE.
1136 If FILE is nil evaluate BODY forms on source blocks in current
1138 (declare (indent 1))
1139 (let ((tempvar (make-symbol "file")))
1140 `(let* ((,tempvar
,file
)
1141 (visited-p (or (null ,tempvar
)
1142 (get-file-buffer (expand-file-name ,tempvar
))))
1143 (point (point)) to-be-removed
)
1144 (save-window-excursion
1145 (when ,tempvar
(find-file ,tempvar
))
1146 (setq to-be-removed
(current-buffer))
1147 (goto-char (point-min))
1148 (while (re-search-forward org-babel-lob-one-liner-regexp nil t
)
1149 (when (org-babel-active-location-p)
1150 (goto-char (match-beginning 1))
1151 (save-match-data ,@body
))
1152 (goto-char (match-end 0))))
1153 (unless visited-p
(kill-buffer to-be-removed
))
1154 (goto-char point
))))
1155 (def-edebug-spec org-babel-map-call-lines
(form body
))
1158 (defmacro org-babel-map-executables
(file &rest body
)
1159 (declare (indent 1))
1160 (let ((tempvar (make-symbol "file"))
1161 (rx (make-symbol "rx")))
1162 `(let* ((,tempvar
,file
)
1163 (,rx
(concat "\\(" org-babel-src-block-regexp
1164 "\\|" org-babel-inline-src-block-regexp
1165 "\\|" org-babel-lob-one-liner-regexp
"\\)"))
1166 (visited-p (or (null ,tempvar
)
1167 (get-file-buffer (expand-file-name ,tempvar
))))
1168 (point (point)) to-be-removed
)
1169 (save-window-excursion
1170 (when ,tempvar
(find-file ,tempvar
))
1171 (setq to-be-removed
(current-buffer))
1172 (goto-char (point-min))
1173 (while (re-search-forward ,rx nil t
)
1174 (when (org-babel-active-location-p)
1175 (goto-char (match-beginning 1))
1176 (when (looking-at org-babel-inline-src-block-regexp
)
1178 (save-match-data ,@body
))
1179 (goto-char (match-end 0))))
1180 (unless visited-p
(kill-buffer to-be-removed
))
1181 (goto-char point
))))
1182 (def-edebug-spec org-babel-map-executables
(form body
))
1185 (defun org-babel-execute-buffer (&optional arg
)
1186 "Execute source code blocks in a buffer.
1187 Call `org-babel-execute-src-block' on every source block in
1188 the current buffer."
1190 (org-babel-eval-wipe-error-buffer)
1191 (org-save-outline-visibility t
1192 (org-babel-map-executables nil
1193 (if (looking-at org-babel-lob-one-liner-regexp
)
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 (org-babel-where-is-src-block-result nil info
)
1268 (org-no-properties (match-string 5)))
1270 (defun org-babel-set-current-result-hash (hash info
)
1271 "Set the current in-buffer hash to HASH."
1272 (org-babel-where-is-src-block-result nil info
)
1273 (save-excursion (goto-char (match-beginning 5))
1274 (mapc #'delete-overlay
(overlays-at (point)))
1275 (forward-char org-babel-hash-show
)
1276 (mapc #'delete-overlay
(overlays-at (point)))
1277 (replace-match hash nil nil nil
5)
1278 (goto-char (point-at-bol))
1279 (org-babel-hide-hash)))
1281 (defun org-babel-hide-hash ()
1282 "Hide the hash in the current results line.
1283 Only the initial `org-babel-hash-show' characters of the hash
1284 will remain visible."
1285 (add-to-invisibility-spec '(org-babel-hide-hash . t
))
1287 (when (and (re-search-forward org-babel-result-regexp nil t
)
1289 (let* ((start (match-beginning 5))
1290 (hide-start (+ org-babel-hash-show start
))
1292 (hash (match-string 5))
1294 (setq ov1
(make-overlay start hide-start
))
1295 (setq ov2
(make-overlay hide-start end
))
1296 (overlay-put ov2
'invisible
'org-babel-hide-hash
)
1297 (overlay-put ov1
'babel-hash hash
)))))
1299 (defun org-babel-hide-all-hashes ()
1300 "Hide the hash in the current buffer.
1301 Only the initial `org-babel-hash-show' characters of each hash
1302 will remain visible. This function should be called as part of
1303 the `org-mode-hook'."
1305 (while (and (not org-babel-hash-show-time
)
1306 (re-search-forward org-babel-result-regexp nil t
))
1307 (goto-char (match-beginning 0))
1308 (org-babel-hide-hash)
1309 (goto-char (match-end 0)))))
1310 (add-hook 'org-mode-hook
'org-babel-hide-all-hashes
)
1312 (defun org-babel-hash-at-point (&optional point
)
1313 "Return the value of the hash at POINT.
1315 The hash is also added as the last element of the kill ring.
1316 This can be called with \\[org-ctrl-c-ctrl-c]."
1318 (let ((hash (car (delq nil
(mapcar
1319 (lambda (ol) (overlay-get ol
'babel-hash
))
1320 (overlays-at (or point
(point))))))))
1321 (when hash
(kill-new hash
) (message hash
))))
1322 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-hash-at-point
)
1324 (defun org-babel-result-hide-spec ()
1325 "Hide portions of results lines.
1326 Add `org-babel-hide-result' as an invisibility spec for hiding
1327 portions of results lines."
1328 (add-to-invisibility-spec '(org-babel-hide-result . t
)))
1329 (add-hook 'org-mode-hook
'org-babel-result-hide-spec
)
1331 (defvar org-babel-hide-result-overlays nil
1332 "Overlays hiding results.")
1334 (defun org-babel-result-hide-all ()
1335 "Fold all results in the current buffer."
1337 (org-babel-show-result-all)
1339 (while (re-search-forward org-babel-result-regexp nil t
)
1340 (save-excursion (goto-char (match-beginning 0))
1341 (org-babel-hide-result-toggle-maybe)))))
1343 (defun org-babel-show-result-all ()
1344 "Unfold all results in the current buffer."
1345 (mapc 'delete-overlay org-babel-hide-result-overlays
)
1346 (setq org-babel-hide-result-overlays nil
))
1349 (defun org-babel-hide-result-toggle-maybe ()
1350 "Toggle visibility of result at point."
1352 (let ((case-fold-search t
))
1354 (beginning-of-line 1)
1355 (looking-at org-babel-result-regexp
))
1356 (progn (org-babel-hide-result-toggle)
1357 t
) ;; to signal that we took action
1358 nil
))) ;; to signal that we did not
1360 (defun org-babel-hide-result-toggle (&optional force
)
1361 "Toggle the visibility of the current result."
1365 (if (re-search-forward org-babel-result-regexp nil t
)
1366 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
1368 (while (looking-at org-babel-multi-line-header-regexp
)
1370 (goto-char (- (org-babel-result-end) 1)) (point)))
1372 (if (memq t
(mapcar (lambda (overlay)
1373 (eq (overlay-get overlay
'invisible
)
1374 'org-babel-hide-result
))
1375 (overlays-at start
)))
1376 (if (or (not force
) (eq force
'off
))
1378 (when (member ov org-babel-hide-result-overlays
)
1379 (setq org-babel-hide-result-overlays
1380 (delq ov org-babel-hide-result-overlays
)))
1381 (when (eq (overlay-get ov
'invisible
)
1382 'org-babel-hide-result
)
1383 (delete-overlay ov
)))
1384 (overlays-at start
)))
1385 (setq ov
(make-overlay start end
))
1386 (overlay-put ov
'invisible
'org-babel-hide-result
)
1387 ;; make the block accessible to isearch
1389 ov
'isearch-open-invisible
1391 (when (member ov org-babel-hide-result-overlays
)
1392 (setq org-babel-hide-result-overlays
1393 (delq ov org-babel-hide-result-overlays
)))
1394 (when (eq (overlay-get ov
'invisible
)
1395 'org-babel-hide-result
)
1396 (delete-overlay ov
))))
1397 (push ov org-babel-hide-result-overlays
)))
1398 (error "Not looking at a result line"))))
1400 ;; org-tab-after-check-for-cycling-hook
1401 (add-hook 'org-tab-first-hook
'org-babel-hide-result-toggle-maybe
)
1402 ;; Remove overlays when changing major mode
1403 (add-hook 'org-mode-hook
1404 (lambda () (org-add-hook 'change-major-mode-hook
1405 'org-babel-show-result-all
'append
'local
)))
1407 (defvar org-file-properties
)
1408 (defun org-babel-params-from-properties (&optional lang
)
1409 "Retrieve parameters specified as properties.
1410 Return a list of association lists of source block params
1411 specified in the properties of the current outline entry."
1414 ;; DEPRECATED header arguments specified as separate property at
1415 ;; point of definition.
1416 (org-babel-parse-multiple-vars
1420 (let* ((arg (symbol-name (car header
)))
1421 (val (org-entry-get (point) arg t
)))
1423 (cons (intern (concat ":" arg
))
1424 (org-babel-read val
)))))
1425 (org-babel-combine-header-arg-lists
1426 org-babel-common-header-args-w-values
1427 (let ((sym (intern (concat "org-babel-header-args:" lang
))))
1428 (and (boundp sym
) (symbol-value sym
)))))))
1429 ;; header arguments specified with the header-args property at
1431 (org-babel-parse-header-arguments
1432 (org-entry-get org-babel-current-src-block-location
1435 (and lang
; language-specific header arguments at point of call
1436 (org-babel-parse-header-arguments
1437 (org-entry-get org-babel-current-src-block-location
1438 (concat "header-args:" lang
)
1441 (defvar org-src-preserve-indentation
) ;; declare defcustom from org-src
1442 (defun org-babel-parse-src-block-match ()
1443 "Parse the results from a match of the `org-babel-src-block-regexp'."
1444 (let* ((block-indentation (string-width (match-string 1)))
1445 (lang (org-match-string-no-properties 2))
1446 (lang-headers (intern (concat "org-babel-default-header-args:" lang
)))
1447 (switches (match-string 3))
1448 (body (let* ((body (org-match-string-no-properties 5))
1449 (sub-length (- (length body
) 1)))
1450 (if (and (> sub-length
0)
1451 (string= "\n" (substring body sub-length
)))
1452 (substring body
0 sub-length
)
1454 (preserve-indentation (or org-src-preserve-indentation
1456 (string-match "-i\\>" switches
)))))
1458 ;; get block body less properties, protective commas, and indentation
1461 (insert (org-unescape-code-in-string body
))
1462 (unless preserve-indentation
(org-do-remove-indentation))
1464 (apply #'org-babel-merge-params
1465 org-babel-default-header-args
1466 (when (boundp lang-headers
) (eval lang-headers
))
1468 (org-babel-params-from-properties lang
)
1469 (list (org-babel-parse-header-arguments
1470 (org-no-properties (or (match-string 4) ""))))))
1472 block-indentation
)))
1474 (defun org-babel-parse-inline-src-block-match ()
1475 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
1476 (let* ((lang (org-no-properties (match-string 2)))
1477 (lang-headers (intern (concat "org-babel-default-header-args:" lang
))))
1479 (org-unescape-code-in-string (org-no-properties (match-string 5)))
1480 (apply #'org-babel-merge-params
1481 org-babel-default-inline-header-args
1482 (if (boundp lang-headers
) (eval lang-headers
) nil
)
1484 (org-babel-params-from-properties lang
)
1485 (list (org-babel-parse-header-arguments
1486 (org-no-properties (or (match-string 4) ""))))))
1489 (defun org-babel-balanced-split (string alts
)
1490 "Split STRING on instances of ALTS.
1491 ALTS is a cons of two character options where each option may be
1492 either the numeric code of a single character or a list of
1493 character alternatives. For example to split on balanced
1494 instances of \"[ \t]:\" set ALTS to '((32 9) . 58)."
1495 (let* ((matches (lambda (ch spec
) (if (listp spec
) (member ch spec
) (equal spec ch
))))
1496 (matched (lambda (ch last
)
1498 (and (funcall matches ch
(cdr alts
))
1499 (funcall matches last
(car alts
)))
1500 (funcall matches ch alts
))))
1501 (balance 0) (last 0)
1503 (mapc (lambda (ch) ; split on [], (), "" balanced instances of [ \t]:
1504 (setq balance
(+ balance
1505 (cond ((or (equal 91 ch
) (equal 40 ch
)) 1)
1506 ((or (equal 93 ch
) (equal 41 ch
)) -
1)
1508 (when (and (equal 34 ch
) (not (equal 92 last
)))
1509 (setq quote
(not quote
)))
1510 (setq partial
(cons ch partial
))
1511 (when (and (= balance
0) (not quote
) (funcall matched ch last
))
1512 (setq lst
(cons (apply #'string
(nreverse
1519 (string-to-list string
))
1520 (nreverse (cons (apply #'string
(nreverse partial
)) lst
))))
1522 (defun org-babel-join-splits-near-ch (ch list
)
1523 "Join splits where \"=\" is on either end of the split."
1524 (let ((last= (lambda (str) (= ch
(aref str
(1- (length str
))))))
1525 (first= (lambda (str) (= ch
(aref str
0)))))
1527 (cl-reduce (lambda (acc el
)
1528 (let ((head (car acc
)))
1529 (if (and head
(or (funcall last
= head
) (funcall first
= el
)))
1530 (cons (concat head el
) (cdr acc
))
1532 list
:initial-value nil
))))
1534 (defun org-babel-parse-header-arguments (arg-string)
1535 "Parse a string of header arguments returning an alist."
1536 (when (> (length arg-string
) 0)
1537 (org-babel-parse-multiple-vars
1542 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1544 (cons (intern (match-string 1 arg
))
1545 (org-babel-read (org-babel-chomp (match-string 2 arg
))))
1546 (cons (intern (org-babel-chomp arg
)) nil
)))
1547 (let ((raw (org-babel-balanced-split arg-string
'((32 9) .
58))))
1548 (cons (car raw
) (mapcar (lambda (r) (concat ":" r
)) (cdr raw
)))))))))
1550 (defun org-babel-parse-multiple-vars (header-arguments)
1551 "Expand multiple variable assignments behind a single :var keyword.
1553 This allows expression of multiple variables with one :var as
1556 #+PROPERTY: var foo=1, bar=2"
1558 (mapc (lambda (pair)
1559 (if (eq (car pair
) :var
)
1560 (mapcar (lambda (v) (push (cons :var
(org-babel-trim v
)) results
))
1561 (org-babel-join-splits-near-ch
1562 61 (org-babel-balanced-split (cdr pair
) 32)))
1563 (push pair results
)))
1565 (nreverse results
)))
1567 (defun org-babel-process-params (params)
1568 "Expand variables in PARAMS and add summary parameters."
1569 (let* ((processed-vars (mapcar (lambda (el)
1572 (org-babel-ref-parse el
)))
1573 (org-babel--get-vars params
)))
1574 (vars-and-names (if (and (assoc :colname-names params
)
1575 (assoc :rowname-names params
))
1576 (list processed-vars
)
1577 (org-babel-disassemble-tables
1579 (cdr (assoc :hlines params
))
1580 (cdr (assoc :colnames params
))
1581 (cdr (assoc :rownames params
)))))
1582 (raw-result (or (cdr (assoc :results params
)) ""))
1583 (result-params (append
1584 (split-string (if (stringp raw-result
)
1587 (cdr (assoc :result-params params
)))))
1589 (mapcar (lambda (var) (cons :var var
)) (car vars-and-names
))
1591 (cons :colname-names
(or (cdr (assoc :colname-names params
))
1592 (cadr vars-and-names
)))
1593 (cons :rowname-names
(or (cdr (assoc :rowname-names params
))
1594 (caddr vars-and-names
)))
1595 (cons :result-params result-params
)
1596 (cons :result-type
(cond ((member "output" result-params
) 'output
)
1597 ((member "value" result-params
) 'value
)
1600 (lambda (x) (memq (car x
) '(:colname-names
:rowname-names
:result-params
1601 :result-type
:var
)))
1604 ;; row and column names
1605 (defun org-babel-del-hlines (table)
1606 "Remove all `hlines' from TABLE."
1607 (remq 'hline table
))
1609 (defun org-babel-get-colnames (table)
1610 "Return the column names of TABLE.
1611 Return a cons cell, the `car' of which contains the TABLE less
1612 colnames, and the `cdr' of which contains a list of the column
1614 (if (equal 'hline
(nth 1 table
))
1615 (cons (cddr table
) (car table
))
1616 (cons (cdr table
) (car table
))))
1618 (defun org-babel-get-rownames (table)
1619 "Return the row names of TABLE.
1620 Return a cons cell, the `car' of which contains the TABLE less
1621 rownames, and the `cdr' of which contains a list of the rownames.
1622 Note: this function removes any hlines in TABLE."
1623 (let* ((table (org-babel-del-hlines table
))
1624 (rownames (funcall (lambda ()
1630 (setq tp
(cdr tp
))))
1632 (cons table rownames
)))
1634 (defun org-babel-put-colnames (table colnames
)
1635 "Add COLNAMES to TABLE if they exist."
1636 (if colnames
(apply 'list colnames
'hline table
) table
))
1638 (defun org-babel-put-rownames (table rownames
)
1639 "Add ROWNAMES to TABLE if they exist."
1641 (mapcar (lambda (row)
1643 (cons (or (pop rownames
) "") row
)
1647 (defun org-babel-pick-name (names selector
)
1648 "Select one out of an alist of row or column names.
1649 SELECTOR can be either a list of names in which case those names
1650 will be returned directly, or an index into the list NAMES in
1651 which case the indexed names will be return."
1652 (if (listp selector
)
1655 (if (and selector
(symbolp selector
) (not (equal t selector
)))
1656 (cdr (assoc selector names
))
1657 (if (integerp selector
)
1658 (nth (- selector
1) names
)
1659 (cdr (car (last names
))))))))
1661 (defun org-babel-disassemble-tables (vars hlines colnames rownames
)
1662 "Parse tables for further processing.
1663 Process the variables in VARS according to the HLINES,
1664 ROWNAMES and COLNAMES header arguments. Return a list consisting
1665 of the vars, cnames and rnames."
1666 (let (cnames rnames
)
1670 (when (listp (cdr var
))
1671 (when (and (not (equal colnames
"no"))
1672 (or colnames
(and (equal (nth 1 (cdr var
)) 'hline
)
1673 (not (member 'hline
(cddr (cdr var
)))))))
1674 (let ((both (org-babel-get-colnames (cdr var
))))
1675 (setq cnames
(cons (cons (car var
) (cdr both
))
1677 (setq var
(cons (car var
) (car both
)))))
1678 (when (and rownames
(not (equal rownames
"no")))
1679 (let ((both (org-babel-get-rownames (cdr var
))))
1680 (setq rnames
(cons (cons (car var
) (cdr both
))
1682 (setq var
(cons (car var
) (car both
)))))
1683 (when (and hlines
(not (equal hlines
"yes")))
1684 (setq var
(cons (car var
) (org-babel-del-hlines (cdr var
))))))
1687 (reverse cnames
) (reverse rnames
))))
1689 (defun org-babel-reassemble-table (table colnames rownames
)
1690 "Add column and row names to a table.
1691 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1692 to the table for reinsertion to org-mode."
1694 (let ((table (if (and rownames
(= (length table
) (length rownames
)))
1695 (org-babel-put-rownames table rownames
) table
)))
1696 (if (and colnames
(listp (car table
)) (= (length (car table
))
1698 (org-babel-put-colnames table colnames
) table
))
1701 (defun org-babel-where-is-src-block-head ()
1702 "Find where the current source block begins.
1703 Return the point at the beginning of the current source block.
1704 Specifically at the beginning of the #+BEGIN_SRC line. Also set
1705 match-data relatively to `org-babel-src-block-regexp', which see.
1706 If the point is not on a source block then return nil."
1707 (let ((element (org-element-at-point)))
1708 (when (eq (org-element-type element
) 'src-block
)
1709 (let ((end (org-element-property :end element
)))
1710 (org-with-wide-buffer
1711 ;; Ensure point is not on a blank line after the block.
1713 (skip-chars-forward " \r\t\n" end
)
1714 (when (< (point) end
)
1715 (prog1 (goto-char (org-element-property :post-affiliated element
))
1716 (looking-at org-babel-src-block-regexp
))))))))
1719 (defun org-babel-goto-src-block-head ()
1720 "Go to the beginning of the current code block."
1722 (let ((head (org-babel-where-is-src-block-head)))
1723 (if head
(goto-char head
) (error "Not currently in a code block"))))
1726 (defun org-babel-goto-named-src-block (name)
1727 "Go to a named source-code block."
1729 (let ((completion-ignore-case t
)
1730 (case-fold-search t
)
1731 (under-point (thing-at-point 'line
)))
1732 (list (org-icompleting-read
1733 "source-block name: " (org-babel-src-block-names) nil t
1736 ((string-match (org-babel-noweb-wrap) under-point
)
1737 (let ((block-name (match-string 1 under-point
)))
1738 (string-match "[^(]*" block-name
)
1739 (match-string 0 block-name
)))
1741 ((string-match org-babel-lob-one-liner-regexp under-point
)
1742 (let ((source-info (car (org-babel-lob-get-info))))
1743 (if (string-match "^\\([^\\[]+?\\)\\(\\[.*\\]\\)?(" source-info
)
1744 (let ((source-name (match-string 1 source-info
)))
1747 ((string-match (concat "#\\+" org-babel-results-keyword
1748 "\\:\s+\\([^\\(]*\\)") under-point
)
1749 (match-string 1 under-point
))
1751 ((and (thing-at-point 'symbol
))
1752 (org-babel-find-named-block (thing-at-point 'symbol
))
1753 (thing-at-point 'symbol
))
1755 (let ((point (org-babel-find-named-block name
)))
1757 ;; taken from `org-open-at-point'
1758 (progn (org-mark-ring-push) (goto-char point
) (org-show-context))
1759 (message "source-code block `%s' not found in this buffer" name
))))
1761 (defun org-babel-find-named-block (name)
1762 "Find a named source-code block.
1763 Return the location of the source block identified by source
1764 NAME, or nil if no such block exists. Set match data according
1765 to `org-babel-named-src-block-regexp'."
1767 (goto-char (point-min))
1769 (org-next-block 1 nil
(org-babel-named-src-block-regexp-for-name name
)))))
1771 (defun org-babel-src-block-names (&optional file
)
1772 "Returns the names of source blocks in FILE or the current buffer."
1773 (when file
(find-file file
))
1775 (goto-char (point-min))
1776 (let ((re (org-babel-named-src-block-regexp-for-name))
1778 (while (ignore-errors (org-next-block 1 nil re
))
1779 (push (org-match-string-no-properties 9) names
))
1783 (defun org-babel-goto-named-result (name)
1784 "Go to a named result."
1786 (let ((completion-ignore-case t
))
1787 (list (org-icompleting-read "source-block name: "
1788 (org-babel-result-names) nil t
))))
1789 (let ((point (org-babel-find-named-result name
)))
1791 ;; taken from `org-open-at-point'
1792 (progn (goto-char point
) (org-show-context))
1793 (message "result `%s' not found in this buffer" name
))))
1795 (defun org-babel-find-named-result (name &optional point
)
1796 "Find a named result.
1797 Return the location of the result named NAME in the current
1798 buffer or nil if no such result exists."
1800 (let ((case-fold-search t
))
1801 (goto-char (or point
(point-min)))
1802 (catch 'is-a-code-block
1803 (when (re-search-forward
1804 (concat org-babel-result-regexp
1805 "[ \t]" (regexp-quote name
) "[ \t]*[\n\f\v\r]") nil t
)
1806 (when (and (string= "name" (downcase (match-string 1)))
1807 (or (beginning-of-line 1)
1808 (looking-at org-babel-src-block-regexp
)
1809 (looking-at org-babel-multi-line-header-regexp
)
1810 (looking-at org-babel-lob-one-liner-regexp
)))
1811 (throw 'is-a-code-block
(org-babel-find-named-result name
(point))))
1812 (beginning-of-line 0) (point))))))
1814 (defun org-babel-result-names (&optional file
)
1815 "Returns the names of results in FILE or the current buffer."
1817 (when file
(find-file file
)) (goto-char (point-min))
1818 (let ((case-fold-search t
) names
)
1819 (while (re-search-forward org-babel-result-w-name-regexp nil t
)
1820 (setq names
(cons (match-string 4) names
)))
1824 (defun org-babel-next-src-block (&optional arg
)
1825 "Jump to the next source block.
1826 With optional prefix argument ARG, jump forward ARG many source blocks."
1828 (org-next-block arg nil org-babel-src-block-regexp
))
1831 (defun org-babel-previous-src-block (&optional arg
)
1832 "Jump to the previous source block.
1833 With optional prefix argument ARG, jump backward ARG many source blocks."
1835 (org-previous-block arg org-babel-src-block-regexp
))
1837 (defvar org-babel-load-languages
)
1840 (defun org-babel-mark-block ()
1841 "Mark current src block."
1843 (let ((head (org-babel-where-is-src-block-head)))
1847 (looking-at org-babel-src-block-regexp
))
1848 (push-mark (match-end 5) nil t
)
1849 (goto-char (match-beginning 5)))))
1851 (defun org-babel-demarcate-block (&optional arg
)
1852 "Wrap or split the code in the region or on the point.
1853 When called from inside of a code block the current block is
1854 split. When called from outside of a code block a new code block
1855 is created. In both cases if the region is demarcated and if the
1856 region is not active then the point is demarcated."
1858 (let* ((info (org-babel-get-src-block-info 'light
))
1859 (start (org-babel-where-is-src-block-head))
1860 (block (and start
(match-string 0)))
1861 (headers (and start
(match-string 4)))
1862 (stars (concat (make-string (or (org-current-level) 1) ?
*) " "))
1863 (lower-case-p (and block
1864 (let (case-fold-search)
1865 (org-string-match-p "#\\+begin_src" block
)))))
1871 (let ((lang (nth 0 info
))
1872 (indent (make-string (nth 5 info
) ?
)))
1873 (when (string-match "^[[:space:]]*$"
1874 (buffer-substring (point-at-bol)
1876 (delete-region (point-at-bol) (point-at-eol)))
1878 (if (looking-at "^") "" "\n")
1879 indent
(funcall (if lower-case-p
'downcase
'upcase
) "#+end_src\n")
1880 (if arg stars indent
) "\n"
1881 indent
(funcall (if lower-case-p
'downcase
'upcase
) "#+begin_src ")
1883 (if (> (length headers
) 1)
1884 (concat " " headers
) headers
)
1885 (if (looking-at "[\n\r]")
1887 (concat "\n" (make-string (current-column) ?
)))))))
1888 (move-end-of-line 2))
1889 (sort (if (org-region-active-p) (list (mark) (point)) (list (point))) #'>))
1890 (let ((start (point))
1891 (lang (org-icompleting-read
1893 (mapcar #'symbol-name
1895 (append (mapcar #'car org-babel-load-languages
)
1896 (mapcar (lambda (el) (intern (car el
)))
1897 org-src-lang-modes
))))))
1898 (body (delete-and-extract-region
1899 (if (org-region-active-p) (mark) (point)) (point))))
1900 (insert (concat (if (looking-at "^") "" "\n")
1901 (if arg
(concat stars
"\n") "")
1902 (funcall (if lower-case-p
'downcase
'upcase
) "#+begin_src ")
1905 (if (or (= (length body
) 0)
1906 (string-match "[\r\n]$" body
)) "" "\n")
1907 (funcall (if lower-case-p
'downcase
'upcase
) "#+end_src\n")))
1908 (goto-char start
) (move-end-of-line 1)))))
1910 (defvar org-babel-lob-one-liner-regexp
)
1911 (defun org-babel-where-is-src-block-result (&optional insert info hash indent
)
1912 "Find where the current source block results begin.
1913 Return the point at the beginning of the result of the current
1914 source block. Specifically at the beginning of the results line.
1915 If no result exists for this block then create a results line
1916 following the source block."
1918 (let* ((case-fold-search t
)
1919 (on-lob-line (save-excursion
1920 (beginning-of-line 1)
1921 (looking-at org-babel-lob-one-liner-regexp
)))
1922 (inlinep (when (org-babel-get-inline-src-block-matches)
1924 (name (nth 4 (or info
(org-babel-get-src-block-info 'light
))))
1925 (head (unless on-lob-line
(org-babel-where-is-src-block-head)))
1927 (when head
(goto-char head
))
1928 (org-with-wide-buffer
1930 found
;; was there a result (before we potentially insert one)
1935 ;; - return t if it is found, else return nil
1936 ;; - if it does not need to be rebuilt, then don't set end
1937 ;; - if it does need to be rebuilt then do set end
1938 name
(setq beg
(org-babel-find-named-result name
))
1940 (when (and hash
(not (string= hash
(match-string 5))))
1941 (goto-char beg
) (setq end beg
) ;; beginning of result
1943 (delete-region end
(org-babel-result-end)) nil
)))
1946 ;; - return t if it is found, else return nil
1947 ;; - if it is found, and the hash doesn't match, delete and set end
1948 (or on-lob-line
(re-search-forward "^[ \t]*#\\+end_src" nil t
))
1949 (progn (end-of-line 1)
1950 (if (eobp) (insert "\n") (forward-char 1))
1954 (progn ;; unnamed results line already exists
1956 (while (re-search-forward "[^ \f\t\n\r\v]" nil t
)
1957 (beginning-of-line 1)
1959 ((looking-at (concat org-babel-result-regexp
"\n"))
1960 (throw 'non-comment t
))
1961 ((and (looking-at "^[ \t]*#")
1963 org-babel-lob-one-liner-regexp
)))
1965 (t (throw 'non-comment nil
))))))
1966 (let ((this-hash (match-string 5)))
1968 ;; must remove and rebuild if hash!=old-hash
1969 (if (and hash
(not (string= hash this-hash
)))
1971 (setq end
(point-at-bol))
1973 (delete-region end
(org-babel-result-end))
1975 (setq end nil
))))))))))
1976 (if (not (and insert end
)) found
1979 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1980 (when (wholenump indent
) (indent-to indent
))
1982 "#+" org-babel-results-keyword
1984 (if org-babel-hash-show-time
1986 "["(format-time-string "<%Y-%m-%d %H:%M:%S>")" "hash
"]")
1987 (concat "["hash
"]")))
1989 (when name
(concat " " name
)) "\n"))
1990 (unless beg
(insert "\n") (backward-char))
1991 (beginning-of-line 0)
1992 (when hash
(org-babel-hide-hash))
1995 (defun org-babel-read-element (element)
1996 "Read ELEMENT into emacs-lisp.
1997 Return nil if ELEMENT cannot be read."
1998 (org-with-wide-buffer
1999 (goto-char (org-element-property :post-affiliated element
))
2000 (pcase (org-element-type element
)
2002 (let ((v (org-babel-trim (org-element-property :value element
))))
2003 (or (org-babel-number-p v
) v
)))
2004 (`table
(org-babel-read-table))
2005 (`plain-list
(org-babel-read-list))
2006 ((or `example-block
`export-block
)
2007 (org-remove-indentation (org-element-property :value element
)))
2009 ;; Treat paragraphs containing a single link specially.
2010 (skip-chars-forward " \t")
2011 (if (and (looking-at org-bracket-link-regexp
)
2013 (goto-char (match-end 0))
2014 (skip-chars-forward " \r\t\n")
2015 (<= (org-element-property :end element
)
2017 (org-babel-read-link)
2018 (buffer-substring-no-properties
2019 (org-element-property :contents-begin element
)
2020 (org-element-property :contents-end element
))))
2021 ((or `center-block
`quote-block
`verse-block
`special-block
)
2022 (org-remove-indentation
2023 (buffer-substring-no-properties
2024 (org-element-property :contents-begin element
)
2025 (org-element-property :contents-end element
))))
2028 (defvar org-block-regexp
)
2029 (defun org-babel-read-result ()
2030 "Read the result at `point' into emacs-lisp."
2031 (let ((case-fold-search t
) result-string
)
2033 ((org-at-table-p) (org-babel-read-table))
2034 ((org-at-item-p) (org-babel-read-list))
2035 ((looking-at org-bracket-link-regexp
) (org-babel-read-link))
2036 ((looking-at org-block-regexp
) (org-remove-indentation (match-string 4)))
2037 ((or (looking-at "^[ \t]*: ") (looking-at "^[ \t]*:$"))
2040 (mapconcat (lambda (line)
2041 (or (and (> (length line
) 1)
2042 (string-match "^[ \t]*: ?\\(.+\\)" line
)
2043 (match-string 1 line
))
2047 (point) (org-babel-result-end)) "[\r\n]+")
2049 (or (org-babel-number-p result-string
) result-string
))
2050 ((looking-at org-babel-result-regexp
)
2051 (save-excursion (forward-line 1) (org-babel-read-result))))))
2053 (defun org-babel-read-table ()
2054 "Read the table at `point' into emacs-lisp."
2055 (mapcar (lambda (row)
2056 (if (and (symbolp row
) (equal row
'hline
)) row
2057 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
)) row
)))
2058 (org-table-to-lisp)))
2060 (defun org-babel-read-list ()
2061 "Read the list at `point' into emacs-lisp."
2062 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
))
2063 (mapcar #'cadr
(cdr (org-list-parse-list)))))
2065 (defvar org-link-types-re
)
2066 (defun org-babel-read-link ()
2067 "Read the link at `point' into emacs-lisp.
2068 If the path of the link is a file path it is expanded using
2069 `expand-file-name'."
2070 (let* ((case-fold-search t
)
2071 (raw (and (looking-at org-bracket-link-regexp
)
2072 (org-no-properties (match-string 1))))
2073 (type (and (string-match org-link-types-re raw
)
2074 (match-string 1 raw
))))
2076 ((not type
) (expand-file-name raw
))
2077 ((string= type
"file")
2078 (and (string-match "file\\(.*\\):\\(.+\\)" raw
)
2079 (expand-file-name (match-string 2 raw
))))
2082 (defun org-babel-format-result (result &optional sep
)
2083 "Format RESULT for writing to file."
2084 (let ((echo-res (lambda (r) (if (stringp r
) r
(format "%S" r
)))))
2088 result
(list :sep
(or sep
"\t") :fmt echo-res
))
2090 (funcall echo-res result
))))
2092 (defun org-babel-insert-result
2093 (result &optional result-params info hash indent lang
)
2094 "Insert RESULT into the current buffer.
2096 By default RESULT is inserted after the end of the current source
2097 block. The RESULT of an inline source block usually will be
2098 wrapped inside a `results' macro and placed on the same line as
2099 the inline source block. The macro is stripped upon export.
2100 Multiline and non-scalar RESULTS from inline source blocks are
2101 not allowed. With optional argument RESULT-PARAMS controls
2102 insertion of results in the Org mode file. RESULT-PARAMS can
2103 take the following values:
2105 replace - (default option) insert results after the source block
2106 or inline source block replacing any previously
2109 silent -- no results are inserted into the Org-mode buffer but
2110 the results are echoed to the minibuffer and are
2111 ingested by Emacs (a potentially time consuming
2114 file ---- the results are interpreted as a file path, and are
2115 inserted into the buffer using the Org-mode file syntax.
2117 list ---- the results are interpreted as an Org-mode list.
2119 raw ----- results are added directly to the Org-mode file. This
2120 is a good option if you code block will output org-mode
2123 drawer -- results are added directly to the Org-mode file as with
2124 \"raw\", but are wrapped in a RESULTS drawer or results
2125 macro, allowing them to later be replaced or removed
2128 org ----- results are added inside of a \"src_org{}\" or \"#+BEGIN_SRC
2129 org\" block depending on whether the current source block is
2130 inline or not. They are not comma-escaped when inserted,
2131 but Org syntax here will be discarded when exporting the
2134 html ---- results are added inside of a #+BEGIN_HTML block or
2135 html export snippet depending on whether the current
2136 source block is inline or not. This is a good option
2137 if your code block will output html formatted text.
2139 latex --- results are added inside of a #+BEGIN_LATEX block or
2140 latex export snippet depending on whether the current
2141 source block is inline or not. This is a good option
2142 if your code block will output latex formatted text.
2144 code ---- the results are extracted in the syntax of the source
2145 code of the language being evaluated and are added
2146 inside of a source block with the source-code language
2147 set appropriately. Also, source block inlining is
2148 preserved in this case. Note this relies on the
2149 optional LANG argument.
2151 list ---- the results are rendered as a list. This option not
2152 allowed for inline src blocks.
2154 table --- the results are rendered as a table. This option not
2155 allowed for inline src blocks.
2157 INFO may provide the values of these header arguments (in the
2158 `header-arguments-alist' see the docstring for
2159 `org-babel-get-src-block-info'):
2161 :file --- the name of the file to which output should be written.
2163 :wrap --- the effect is similar to `latex' in RESULT-PARAMS but
2164 using the argument supplied to specify the export block
2167 (if (stringp result
)
2169 (setq result
(org-no-properties result
))
2170 (when (member "file" result-params
)
2171 (setq result
(org-babel-result-to-file
2172 result
(when (assoc :file-desc
(nth 2 info
))
2173 (or (cdr (assoc :file-desc
(nth 2 info
)))
2175 (unless (listp result
) (setq result
(format "%S" result
))))
2176 (if (and result-params
(member "silent" result-params
))
2178 (message (replace-regexp-in-string "%" "%%" (format "%S" result
)))
2183 (when (or (org-babel-get-inline-src-block-matches)
2184 (org-babel-get-lob-one-liner-matches))
2185 (goto-char (match-end 0))
2186 (org-babel-remove-inline-result)
2191 (org-babel-where-is-src-block-result t info hash indent
)))
2195 (and (member "table" result-params
) "`:results table'")
2196 (and (listp result
) "list result")
2197 (and (org-string-match-p "\n." result
) "multiline result")
2198 (and (member "list" result-params
) "`:results list'"))))
2200 (cdr (assoc :results_switches
(nth 2 info
))))
2201 (visible-beg (point-min-marker))
2202 (visible-end (point-max-marker))
2203 ;; When results exist outside of the current visible
2204 ;; region of the buffer, be sure to widen buffer to
2206 (outside-scope-p (and existing-result
2207 (or (> visible-beg existing-result
)
2208 (<= visible-end existing-result
))))
2210 (when (and (stringp result
) ; ensure results end in a newline
2212 (> (length result
) 0)
2213 (not (or (string-equal (substring result -
1) "\n")
2214 (string-equal (substring result -
1) "\r"))))
2215 (setq result
(concat result
"\n")))
2218 (when outside-scope-p
(widen))
2219 (if (not existing-result
)
2220 (setq beg
(or inlinep
(point)))
2221 (goto-char existing-result
)
2223 (re-search-forward "#" nil t
)
2224 (setq indent
(- (current-column) 1)))
2228 ((member "replace" result-params
)
2229 (delete-region (point) (org-babel-result-end)))
2230 ((member "append" result-params
)
2231 (goto-char (org-babel-result-end)) (setq beg
(point-marker)))
2232 ((member "prepend" result-params
)))) ; already there
2233 (setq results-switches
2234 (if results-switches
(concat " " results-switches
) ""))
2235 (let ((wrap (lambda (start finish
&optional no-escape no-newlines
2236 inline-start inline-finish
)
2238 (setq start inline-start
)
2239 (setq finish inline-finish
)
2240 (setq no-newlines t
))
2242 (insert (concat finish
(unless no-newlines
"\n")))
2244 (insert (concat start
(unless no-newlines
"\n")))
2246 (org-escape-code-in-region (min (point) end
) end
))
2248 (unless no-newlines
(goto-char (point-at-eol)))
2249 (setq end
(point-marker))))
2252 ;; Non-nil when result R can be turned into
2255 (null (cdr (last r
)))
2257 (lambda (e) (or (atom e
) (null (cdr (last e
)))))
2259 ;; insert results based on type
2261 ;; Do nothing for an empty result.
2263 ;; Illegal inline result or params.
2265 (error "Inline error: %s cannot be used" bad-inline-p
))
2266 ;; insert a list if preferred
2267 ((member "list" result-params
)
2270 (org-list-to-generic
2273 (lambda (el) (list nil
(if (stringp el
) el
(format "%S" el
))))
2274 (if (listp result
) result
(split-string result
"\n" t
))))
2275 '(:splicep nil
:istart
"- " :iend
"\n")))
2277 ;; Try hard to print RESULT as a table. Give up if
2278 ;; it contains an improper list.
2279 ((funcall tabulablep result
)
2281 (insert (concat (orgtbl-to-orgtbl
2284 (or (eq e
'hline
) (listp e
)))
2291 (when (org-at-table-p) (org-table-align))
2292 (goto-char (org-table-end)))
2293 ;; Print verbatim a list that cannot be turned into
2295 ((listp result
) (insert (format "%s\n" result
)))
2296 ((member "file" result-params
)
2299 (setq result
(org-macro-escape-arguments result
)))
2302 (not (member "raw" result-params
)))
2304 (insert (org-macro-escape-arguments
2305 (org-babel-chomp result
"\n"))))
2306 (t (goto-char beg
) (insert result
)))
2307 (setq end
(point-marker))
2308 ;; possibly wrap result
2310 (bad-inline-p) ; Do nothing.
2311 ((assoc :wrap
(nth 2 info
))
2312 (let ((name (or (cdr (assoc :wrap
(nth 2 info
))) "RESULTS")))
2313 (funcall wrap
(concat "#+BEGIN_" name
)
2314 (concat "#+END_" (car (org-split-string name
)))
2315 nil nil
(concat "{{{results(@@" name
":") "@@)}}}")))
2316 ((member "html" result-params
)
2317 (funcall wrap
"#+BEGIN_HTML" "#+END_HTML" nil nil
2318 "{{{results(@@html:" "@@)}}}"))
2319 ((member "latex" result-params
)
2320 (funcall wrap
"#+BEGIN_LaTeX" "#+END_LaTeX" nil nil
2321 "{{{results(@@latex:" "@@)}}}"))
2322 ((member "org" result-params
)
2323 (goto-char beg
) (if (org-at-table-p) (org-cycle))
2324 (funcall wrap
"#+BEGIN_SRC org" "#+END_SRC" nil nil
2325 "{{{results(src_org{" "})}}}"))
2326 ((member "code" result-params
)
2327 (let ((lang (or lang
"none")))
2328 (funcall wrap
(format "#+BEGIN_SRC %s%s" lang results-switches
)
2330 (format "{{{results(src_%s[%s]{" lang results-switches
)
2332 ((member "raw" result-params
)
2333 (goto-char beg
) (if (org-at-table-p) (org-cycle)))
2334 ((or (member "drawer" result-params
)
2335 ;; Stay backward compatible with <7.9.2
2336 (member "wrap" result-params
))
2337 (goto-char beg
) (if (org-at-table-p) (org-cycle))
2338 (funcall wrap
":RESULTS:" ":END:" 'no-escape nil
2339 "{{{results(" ")}}}"))
2340 ((and inlinep
(member "file" result-params
))
2341 (funcall wrap nil nil nil nil
"{{{results(" ")}}}"))
2342 ((and (not (funcall tabulablep result
))
2343 (not (member "file" result-params
)))
2344 (let ((org-babel-inline-result-wrap
2345 ;; Hard code {{{results(...)}}} on top of customization.
2346 (format "{{{results(%s)}}}" org-babel-inline-result-wrap
)))
2347 (org-babel-examplify-region beg end results-switches
)
2348 (setq end
(point))))))
2349 ;; possibly indent the results to match the #+results line
2350 (when (and (not inlinep
) (numberp indent
) indent
(> indent
0)
2351 ;; in this case `table-align' does the work for us
2352 (not (and (listp result
)
2353 (member "append" result-params
))))
2354 (indent-rigidly beg end indent
))
2356 (if (member "value" result-params
)
2357 (message "Code block returned no value.")
2358 (message "Code block produced no output."))
2359 (message "Code block evaluation complete.")))
2360 (when outside-scope-p
(narrow-to-region visible-beg visible-end
))
2361 (set-marker visible-beg nil
)
2362 (set-marker visible-end nil
))))))
2364 (defun org-babel-remove-result (&optional info keep-keyword
)
2365 "Remove the result of the current source block."
2367 (let ((location (org-babel-where-is-src-block-result nil info
)))
2370 (goto-char location
)
2371 (when (looking-at (concat org-babel-result-regexp
".*$"))
2373 (if keep-keyword
(1+ (match-end 0)) (1- (match-beginning 0)))
2374 (progn (forward-line 1) (org-babel-result-end))))))))
2376 (defun org-babel-remove-inline-result ()
2377 "Remove the result of the current inline-src-block or babel call.
2378 The result must be wrapped in a `results' macro to be removed.
2379 Leading whitespace is trimmed."
2381 (let* ((el (org-element-context))
2382 (post-blank (org-element-property :post-blank el
)))
2383 (when (memq (org-element-type el
) '(inline-src-block inline-babel-call
))
2384 (org-with-wide-buffer
2385 (goto-char (org-element-property :end el
))
2386 (let ((el (org-element-context)))
2387 (when (and (eq (org-element-type el
) 'macro
)
2388 (string= (org-element-property :key el
) "results"))
2389 (delete-region ; And leading whitespace.
2390 (- (org-element-property :begin el
) post-blank
)
2391 (- (org-element-property :end el
)
2392 (org-element-property :post-blank el
)))))))))
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
)
2447 "Comment out region using the inline `==' or `: ' org example quote."
2449 (let ((chars-between (lambda (b e
)
2450 (not (string-match "^[\\s]*$"
2451 (buffer-substring b e
)))))
2452 (maybe-cap (lambda (str) (if org-babel-capitalize-example-region-markers
2454 (beg-bol (save-excursion (goto-char beg
) (point-at-bol)))
2455 (end-bol (save-excursion (goto-char end
) (point-at-bol)))
2456 (end-eol (save-excursion (goto-char end
) (point-at-eol))))
2457 (if (and (not (= end end-bol
))
2458 (or (funcall chars-between beg-bol beg
)
2459 (funcall chars-between end end-eol
)))
2462 (insert (format org-babel-inline-result-wrap
2463 (prog1 (buffer-substring beg end
)
2464 (delete-region beg end
)))))
2465 (let ((size (count-lines beg end
)))
2467 (cond ((= size
0)) ; do nothing for an empty result
2468 ((< size org-babel-min-lines-for-block-output
)
2471 (beginning-of-line 1) (insert ": ") (forward-line 1)))
2474 (insert (if results-switches
2476 (funcall maybe-cap
"#+begin_example")
2478 (funcall maybe-cap
"#+begin_example\n")))
2479 (if (markerp end
) (goto-char end
) (forward-char (- end beg
)))
2480 (insert (funcall maybe-cap
"#+end_example\n")))))))))
2482 (defun org-babel-update-block-body (new-body)
2483 "Update the body of the current code block to NEW-BODY."
2484 (if (not (org-babel-where-is-src-block-head))
2485 (error "Not in a source block")
2487 (replace-match (concat (org-babel-trim (org-remove-indentation new-body
))
2489 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
2491 (defun org-babel-merge-params (&rest plists
)
2492 "Combine all parameter association lists in PLISTS.
2493 Later elements of PLISTS override the values of previous elements.
2494 This takes into account some special considerations for certain
2495 parameters when merging lists."
2496 (let* ((results-exclusive-groups
2497 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2498 (cdr (assoc 'results org-babel-common-header-args-w-values
))))
2499 (exports-exclusive-groups
2500 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2501 (cdr (assoc 'exports org-babel-common-header-args-w-values
))))
2503 (e-merge (lambda (exclusive-groups &rest result-params
)
2504 ;; maintain exclusivity of mutually exclusive parameters
2506 (mapc (lambda (new-params)
2507 (mapc (lambda (new-param)
2508 (mapc (lambda (exclusive-group)
2509 (when (member new-param exclusive-group
)
2510 (mapcar (lambda (excluded-param)
2517 (setq output
(org-uniquify
2518 (cons new-param output
))))
2522 params results exports tangle noweb cache vars shebang comments padline
2531 (let ((name (if (listp (cdr pair
))
2533 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
2535 (intern (match-string 1 (cdr pair
)))))))
2539 (if (member name
(mapcar #'car vars
))
2541 (push name clearnames
)
2545 (unless (equal (car p
) name
) p
))
2548 (list (cons name pair
))))
2549 ;; if no name is given and we already have named variables
2550 ;; then assign to named variables in order
2551 (if (and vars
(nth variable-index vars
))
2552 (let ((name (car (nth variable-index vars
))))
2553 (push name clearnames
) ; clear out colnames
2556 (prog1 (setf (cddr (nth variable-index vars
))
2557 (concat (symbol-name name
) "=" (cdr pair
)))
2558 (incf variable-index
)))
2559 (error "Variable \"%s\" must be assigned a default value"
2562 (setq results
(funcall e-merge results-exclusive-groups
2565 (let ((r (cdr pair
)))
2566 (if (stringp r
) r
(eval r
)))))))
2569 (setq results
(funcall e-merge results-exclusive-groups
2571 (unless (or (member "both" exports
)
2572 (member "none" exports
)
2573 (member "code" exports
))
2574 (setq exports
(funcall e-merge exports-exclusive-groups
2575 exports
'("results"))))
2576 (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))
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
)))))
2588 (setq exports
(funcall e-merge exports-exclusive-groups
2590 (split-string (or (cdr pair
) "")))))
2591 (:tangle
;; take the latest -- always overwrite
2592 (setq tangle
(or (list (cdr pair
)) tangle
)))
2594 (setq noweb
(funcall e-merge
2595 '(("yes" "no" "tangle" "no-export"
2596 "strip-export" "eval"))
2598 (split-string (or (cdr pair
) "")))))
2600 (setq cache
(funcall e-merge
'(("yes" "no")) cache
2601 (split-string (or (cdr pair
) "")))))
2603 (setq padline
(funcall e-merge
'(("yes" "no")) padline
2604 (split-string (or (cdr pair
) "")))))
2605 (:shebang
;; take the latest -- always overwrite
2606 (setq shebang
(or (list (cdr pair
)) shebang
)))
2608 (setq comments
(funcall e-merge
'(("yes" "no")) comments
2609 (split-string (or (cdr pair
) "")))))
2610 (t ;; replace: this covers e.g. :session
2611 (setq params
(cons pair
(assq-delete-all (car pair
) params
))))))
2614 (setq vars
(reverse vars
))
2615 (while vars
(setq params
(cons (cons :var
(cddr (pop vars
))) params
)))
2616 ;; clear out col-names and row-names for replaced variables
2621 (when (assoc param params
)
2622 (setf (cdr (assoc param params
))
2623 (cl-remove-if (lambda (pair) (equal (car pair
) name
))
2624 (cdr (assoc param params
))))
2625 (setf params
(cl-remove-if (lambda (pair) (and (equal (car pair
) param
)
2628 (list :colname-names
:rowname-names
)))
2632 (let ((key (intern (concat ":" (symbol-name hd
))))
2634 (setf params
(cons (cons key
(mapconcat 'identity val
" ")) params
))))
2635 '(results exports tangle noweb padline cache shebang comments
))
2638 (defvar org-babel-use-quick-and-dirty-noweb-expansion nil
2639 "Set to true to use regular expressions to expand noweb references.
2640 This results in much faster noweb reference expansion but does
2641 not properly allow code blocks to inherit the \":noweb-ref\"
2642 header argument from buffer or subtree wide properties.")
2644 (defun org-babel-noweb-p (params context
)
2645 "Check if PARAMS require expansion in CONTEXT.
2646 CONTEXT may be one of :tangle, :export or :eval."
2648 (intersect (lambda (as bs
)
2650 (if (member (car as
) bs
)
2652 (funcall intersect
(cdr as
) bs
))))))
2653 (funcall intersect
(case context
2654 (:tangle
'("yes" "tangle" "no-export" "strip-export"))
2655 (:eval
'("yes" "no-export" "strip-export" "eval"))
2657 (split-string (or (cdr (assoc :noweb params
)) "")))))
2659 (defun org-babel-expand-noweb-references (&optional info parent-buffer
)
2660 "Expand Noweb references in the body of the current source code block.
2662 For example the following reference would be replaced with the
2663 body of the source-code block named `example-block'.
2667 Note that any text preceding the <<foo>> construct on a line will
2668 be interposed between the lines of the replacement text. So for
2669 example if <<foo>> is placed behind a comment, then the entire
2670 replacement text will also be commented.
2672 This function must be called from inside of the buffer containing
2673 the source-code block which holds BODY.
2675 In addition the following syntax can be used to insert the
2676 results of evaluating the source-code block named `example-block'.
2680 Any optional arguments can be passed to example-block by placing
2681 the arguments inside the parenthesis following the convention
2682 defined by `org-babel-lob'. For example
2684 <<example-block(a=9)>>
2686 would set the value of argument \"a\" equal to \"9\". Note that
2687 these arguments are not evaluated in the current source-code
2688 block but are passed literally to the \"example-block\"."
2689 (let* ((parent-buffer (or parent-buffer
(current-buffer)))
2690 (info (or info
(org-babel-get-src-block-info 'light
)))
2693 (ob-nww-start org-babel-noweb-wrap-start
)
2694 (ob-nww-end org-babel-noweb-wrap-end
)
2695 (comment (string= "noweb" (cdr (assoc :comments
(nth 2 info
)))))
2696 (rx-prefix (concat "\\(" org-babel-src-name-regexp
"\\|"
2697 ":noweb-ref[ \t]+" "\\)"))
2699 (nb-add (lambda (text) (setq new-body
(concat new-body text
))))
2700 (c-wrap (lambda (text)
2702 (funcall (intern (concat lang
"-mode")))
2703 (comment-region (point) (progn (insert text
) (point)))
2704 (org-babel-trim (buffer-string)))))
2705 index source-name evaluate prefix
)
2707 (setq-local org-babel-noweb-wrap-start ob-nww-start
)
2708 (setq-local org-babel-noweb-wrap-end ob-nww-end
)
2709 (insert body
) (goto-char (point-min))
2710 (setq index
(point))
2711 (while (and (re-search-forward (org-babel-noweb-wrap) nil t
))
2712 (save-match-data (setf source-name
(match-string 1)))
2713 (save-match-data (setq evaluate
(string-match "(.*)" source-name
)))
2716 (buffer-substring (match-beginning 0)
2718 (beginning-of-line 1) (point)))))
2719 ;; add interval to new-body (removing noweb reference)
2720 (goto-char (match-beginning 0))
2721 (funcall nb-add
(buffer-substring index
(point)))
2722 (goto-char (match-end 0))
2723 (setq index
(point))
2726 (with-current-buffer parent-buffer
2729 (mapconcat ;; Interpose PREFIX between every line.
2733 (let ((raw (org-babel-ref-resolve source-name
)))
2734 (if (stringp raw
) raw
(format "%S" raw
)))
2736 ;; Retrieve from the library of babel.
2737 (nth 2 (assoc (intern source-name
)
2738 org-babel-library-of-babel
))
2739 ;; Return the contents of headlines literally.
2741 (when (org-babel-ref-goto-headline-id source-name
)
2742 (org-babel-ref-headline-body)))
2743 ;; Find the expansion of reference in this buffer.
2744 (let ((rx (concat rx-prefix source-name
"[ \t\n]"))
2747 (goto-char (point-min))
2748 (if org-babel-use-quick-and-dirty-noweb-expansion
2749 (while (re-search-forward rx nil t
)
2750 (let* ((i (org-babel-get-src-block-info 'light
))
2751 (body (org-babel-expand-noweb-references i
))
2752 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2755 (let ((cs (org-babel-tangle-comment-links i
)))
2756 (concat (funcall c-wrap
(car cs
)) "\n"
2758 (funcall c-wrap
(cadr cs
))))
2760 (setq expansion
(cons sep
(cons full expansion
)))))
2761 (org-babel-map-src-blocks nil
2762 (let ((i (org-babel-get-src-block-info 'light
)))
2763 (when (equal (or (cdr (assoc :noweb-ref
(nth 2 i
)))
2766 (let* ((body (org-babel-expand-noweb-references i
))
2767 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2770 (let ((cs (org-babel-tangle-comment-links i
)))
2771 (concat (funcall c-wrap
(car cs
)) "\n"
2773 (funcall c-wrap
(cadr cs
))))
2776 (cons sep
(cons full expansion
)))))))))
2778 (mapconcat #'identity
(nreverse (cdr expansion
)) "")))
2779 ;; Possibly raise an error if named block doesn't exist.
2780 (if (or org-babel-noweb-error-all-langs
2781 (member lang org-babel-noweb-error-langs
))
2783 (org-babel-noweb-wrap source-name
)
2784 "could not be resolved (see "
2785 "`org-babel-noweb-error-langs')"))
2787 "[\n\r]") (concat "\n" prefix
))))))
2788 (funcall nb-add
(buffer-substring index
(point-max))))
2791 (defun org-babel--script-escape-inner (str)
2792 (let (in-single in-double backslash out
)
2799 (setq backslash nil
)
2801 ((and in-single
(eq ch ?
'))
2802 ;; Escaped single quote inside single quoted string:
2803 ;; emit just a single quote, since we've changed the
2804 ;; outer quotes to double.
2807 ;; Escaped double quote
2809 ;; This should be interpreted as backslash+quote,
2810 ;; not an escape. Emit a three backslashes
2811 ;; followed by a quote (because one layer of
2812 ;; quoting will be stripped by `org-babel-read').
2813 (append (list ch ?
\\ ?
\\ ?
\\) out
)
2814 ;; Otherwise we are in a double-quoted string. Emit
2815 ;; a single escaped quote
2816 (append (list ch ?
\\) out
)))
2818 ;; Escaped backslash: emit a single escaped backslash
2819 (append (list ?
\\ ?
\\) out
))
2820 ;; Other: emit a quoted backslash followed by whatever
2821 ;; the character was (because one layer of quoting will
2822 ;; be stripped by `org-babel-read').
2823 (t (append (list ch ?
\\ ?
\\) out
))))
2825 (?\
[ (if (or in-double in-single
)
2828 (?\
] (if (or in-double in-single
)
2831 (?\
{ (if (or in-double in-single
)
2834 (?\
} (if (or in-double in-single
)
2837 (?
, (if (or in-double in-single
)
2838 (cons ?
, out
) (cons ?\s out
)))
2841 (setq in-single
(not in-single
)) (cons ?
\" out
)))
2843 (append (list ?
\" ?
\\) out
)
2844 (setq in-double
(not in-double
)) (cons ?
\" out
)))
2845 (?
\\ (unless (or in-single in-double
)
2846 (error "Can't handle backslash outside string in `org-babel-script-escape'"))
2849 (t (cons ch out
))))))
2850 (string-to-list str
))
2851 (when (or in-single in-double
)
2852 (error "Unterminated string in `org-babel-script-escape'"))
2853 (apply #'string
(reverse out
))))
2855 (defun org-babel-script-escape (str &optional force
)
2856 "Safely convert tables into elisp lists."
2857 (unless (stringp str
)
2858 (error "`org-babel-script-escape' expects a string"))
2861 ((and (> (length str
) 2)
2862 (or (and (string-equal "[" (substring str
0 1))
2863 (string-equal "]" (substring str -
1)))
2864 (and (string-equal "{" (substring str
0 1))
2865 (string-equal "}" (substring str -
1)))
2866 (and (string-equal "(" (substring str
0 1))
2867 (string-equal ")" (substring str -
1)))))
2869 (concat "'" (org-babel--script-escape-inner str
)))
2871 (and (> (length str
) 2)
2872 (or (and (string-equal "'" (substring str
0 1))
2873 (string-equal "'" (substring str -
1)))
2874 ;; We need to pass double-quoted strings
2875 ;; through the backslash-twiddling bits, even
2876 ;; though we don't need to change their
2878 (and (string-equal "\"" (substring str
0 1))
2879 (string-equal "\"" (substring str -
1))))))
2880 (org-babel--script-escape-inner str
))
2882 (condition-case nil
(org-babel-read escaped
) (error escaped
))))
2884 (defun org-babel-read (cell &optional inhibit-lisp-eval
)
2885 "Convert the string value of CELL to a number if appropriate.
2886 Otherwise if CELL looks like lisp (meaning it starts with a
2887 \"(\", \"\\='\", \"\\=`\" or a \"[\") then read and evaluate it as
2888 lisp, otherwise return it unmodified as a string. Optional
2889 argument INHIBIT-LISP-EVAL inhibits lisp evaluation for
2890 situations in which is it not appropriate."
2891 (if (and (stringp cell
) (not (equal cell
"")))
2892 (or (org-babel-number-p cell
)
2893 (if (and (not inhibit-lisp-eval
)
2894 (or (member (substring cell
0 1) '("(" "'" "`" "["))
2895 (string= cell
"*this*")))
2897 (if (string= (substring cell
0 1) "\"")
2899 (progn (set-text-properties 0 (length cell
) nil cell
) cell
))))
2902 (defun org-babel-number-p (string)
2903 "If STRING represents a number return its value."
2904 (if (and (string-match "[0-9]+" string
)
2905 (string-match "^-?[0-9]*\\.?[0-9]*$" string
)
2906 (= (length (substring string
(match-beginning 0)
2909 (string-to-number string
)))
2911 (defun org-babel-import-elisp-from-file (file-name &optional separator
)
2912 "Read the results located at FILE-NAME into an elisp table.
2913 If the table is trivial, then return it as a scalar."
2915 (save-window-excursion
2919 (org-table-import file-name separator
)
2920 (delete-file file-name
)
2921 (setq result
(mapcar (lambda (row)
2922 (mapcar #'org-babel-string-read row
))
2923 (org-table-to-lisp))))
2924 (error (message "Error reading results: %s" err
) nil
)))
2925 (if (null (cdr result
)) ;; if result is trivial vector, then scalarize it
2926 (if (consp (car result
))
2927 (if (null (cdr (car result
)))
2933 (defun org-babel-string-read (cell)
2934 "Strip nested \"s from around strings."
2935 (org-babel-read (or (and (stringp cell
)
2936 (string-match "\\\"\\(.+\\)\\\"" cell
)
2937 (match-string 1 cell
))
2940 (defun org-babel-chomp (string &optional regexp
)
2941 "Strip a trailing space or carriage return from STRING.
2942 The default regexp used is \"[ \\f\\t\\n\\r\\v]\" but another one
2943 can be specified as the REGEXP argument."
2944 (let ((regexp (or regexp
"[ \f\t\n\r\v]")))
2945 (while (and (> (length string
) 0)
2946 (string-match regexp
(substring string -
1)))
2947 (setq string
(substring string
0 -
1)))
2950 (defun org-babel-trim (string &optional regexp
)
2951 "Strip a leading and trailing space or carriage return from STRING.
2952 Like `org-babel-chomp', but run on both the first and last
2953 character of the string."
2956 (org-babel-chomp (org-reverse-string string
) regexp
)) regexp
))
2958 (defun org-babel-tramp-handle-call-process-region
2959 (start end program
&optional delete buffer display
&rest args
)
2960 "Use Tramp to handle `call-process-region'.
2961 Fixes a bug in `tramp-handle-call-process-region'."
2962 (if (and (featurep 'tramp
) (file-remote-p default-directory
))
2963 (let ((tmpfile (tramp-compat-make-temp-file "")))
2964 (write-region start end tmpfile
)
2965 (when delete
(delete-region start end
))
2967 ;; (apply 'call-process program tmpfile buffer display args)
2969 (apply 'process-file program tmpfile buffer display args
)
2970 (delete-file tmpfile
)))
2971 ;; org-babel-call-process-region-original is the original emacs
2972 ;; definition. It is in scope from the let binding in
2973 ;; org-babel-execute-src-block
2974 (apply org-babel-call-process-region-original
2975 start end program delete buffer display args
)))
2977 (defun org-babel-local-file-name (file)
2978 "Return the local name component of FILE."
2979 (or (file-remote-p file
'localname
) file
))
2981 (defun org-babel-process-file-name (name &optional no-quote-p
)
2982 "Prepare NAME to be used in an external process.
2983 If NAME specifies a remote location, the remote portion of the
2984 name is removed, since in that case the process will be executing
2985 remotely. The file name is then processed by `expand-file-name'.
2986 Unless second argument NO-QUOTE-P is non-nil, the file name is
2987 additionally processed by `shell-quote-argument'"
2988 (let ((f (org-babel-local-file-name (expand-file-name name
))))
2989 (if no-quote-p f
(shell-quote-argument f
))))
2991 (defvar org-babel-temporary-directory
)
2992 (unless (or noninteractive
(boundp 'org-babel-temporary-directory
))
2993 (defvar org-babel-temporary-directory
2994 (or (and (boundp 'org-babel-temporary-directory
)
2995 (file-exists-p org-babel-temporary-directory
)
2996 org-babel-temporary-directory
)
2997 (make-temp-file "babel-" t
))
2998 "Directory to hold temporary files created to execute code blocks.
2999 Used by `org-babel-temp-file'. This directory will be removed on
3002 (defcustom org-babel-remote-temporary-directory
"/tmp/"
3003 "Directory to hold temporary files on remote hosts."
3007 (defmacro org-babel-result-cond
(result-params scalar-form
&rest table-forms
)
3008 "Call the code to parse raw string results according to RESULT-PARAMS."
3010 (debug (form form
&rest form
)))
3011 (org-with-gensyms (params)
3012 `(let ((,params
,result-params
))
3013 (unless (member "none" ,params
)
3014 (if (or (member "scalar" ,params
)
3015 (member "verbatim" ,params
)
3016 (member "html" ,params
)
3017 (member "code" ,params
)
3018 (member "pp" ,params
)
3019 (member "file" ,params
)
3020 (and (or (member "output" ,params
)
3021 (member "raw" ,params
)
3022 (member "org" ,params
)
3023 (member "drawer" ,params
))
3024 (not (member "table" ,params
))))
3027 (def-edebug-spec org-babel-result-cond
(form form body
))
3029 (defun org-babel-temp-file (prefix &optional suffix
)
3030 "Create a temporary file in the `org-babel-temporary-directory'.
3031 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
3032 value of `temporary-file-directory' temporarily set to the value
3033 of `org-babel-temporary-directory'."
3034 (if (file-remote-p default-directory
)
3036 (concat (file-remote-p default-directory
)
3038 prefix org-babel-remote-temporary-directory
))))
3039 (make-temp-file prefix nil suffix
))
3040 (let ((temporary-file-directory
3041 (or (and (boundp 'org-babel-temporary-directory
)
3042 (file-exists-p org-babel-temporary-directory
)
3043 org-babel-temporary-directory
)
3044 temporary-file-directory
)))
3045 (make-temp-file prefix nil suffix
))))
3047 (defun org-babel-remove-temporary-directory ()
3048 "Remove `org-babel-temporary-directory' on Emacs shutdown."
3049 (when (and (boundp 'org-babel-temporary-directory
)
3050 (file-exists-p org-babel-temporary-directory
))
3051 ;; taken from `delete-directory' in files.el
3054 (mapc (lambda (file)
3055 ;; This test is equivalent to
3056 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
3057 ;; but more efficient
3058 (if (eq t
(car (file-attributes file
)))
3059 (delete-directory file
)
3060 (delete-file file
)))
3061 ;; We do not want to delete "." and "..".
3062 (directory-files org-babel-temporary-directory
'full
3063 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
3064 (delete-directory org-babel-temporary-directory
))
3066 (message "Failed to remove temporary Org-babel directory %s"
3067 (if (boundp 'org-babel-temporary-directory
)
3068 org-babel-temporary-directory
3069 "[directory not defined]"))))))
3071 (add-hook 'kill-emacs-hook
'org-babel-remove-temporary-directory
)
3073 (defun org-babel-one-header-arg-safe-p (pair safe-list
)
3074 "Determine if the PAIR is a safe babel header arg according to SAFE-LIST.
3076 For the format of SAFE-LIST, see `org-babel-safe-header-args'."
3078 (keywordp (car pair
))
3079 (stringp (cdr pair
))
3081 (memq (car pair
) safe-list
)
3082 (let ((entry (assq (car pair
) safe-list
)))
3085 (cond ((functionp (cdr entry
))
3086 (funcall (cdr entry
) (cdr pair
)))
3087 ((listp (cdr entry
))
3088 (member (cdr pair
) (cdr entry
)))
3091 (defun org-babel-generate-file-param (src-name params
)
3092 "Calculate the filename for source block results.
3094 The directory is calculated from the :output-dir property of the
3095 source block; if not specified, use the current directory.
3097 If the source block has a #+NAME and the :file parameter does not
3098 contain any period characters, then the :file parameter is
3099 treated as an extension, and the output file name is the
3100 concatenation of the directory (as calculated above), the block
3101 name, a period, and the parameter value as a file extension.
3102 Otherwise, the :file parameter is treated as a full file name,
3103 and the output file name is the directory (as calculated above)
3104 plus the parameter value."
3105 (let* ((file-cons (assq :file params
))
3106 (file-ext-cons (assq :file-ext params
))
3107 (file-ext (cdr-safe file-ext-cons
))
3108 (dir (cdr-safe (assq :output-dir params
)))
3110 ;; create the output-dir if it does not exist
3112 (make-directory dir t
))
3114 ;; :file given; add :output-dir if given
3116 (setcdr file-cons
(concat (file-name-as-directory dir
) (cdr file-cons
))))
3117 ;; :file not given; compute from name and :file-ext if possible
3118 (when (and src-name file-ext
)
3120 (setq fname
(concat (file-name-as-directory (or dir
""))
3121 src-name
"." file-ext
))
3122 (setq fname
(concat src-name
"." file-ext
)))
3123 (setq params
(cons (cons :file fname
) params
))))
3126 ;;; Used by backends: R, Maxima, Octave.
3127 (defun org-babel-graphical-output-file (params)
3128 "File where a babel block should send graphical output, per PARAMS."
3129 (unless (assq :file params
)
3130 (if (assq :file-ext params
)
3131 (user-error ":file-ext given but no :file generated; did you forget to give a block a #+NAME?")
3132 (user-error "No :file header argument given; cannot create graphical result.")))
3133 (and (member "graphics" (cdr (assq :result-params params
)))
3134 (cdr (assq :file params
))))
3139 ;; generated-autoload-file: "org-loaddefs.el"
3142 ;;; ob-core.el ends here