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/>.
32 (defconst org-babel-exeext
33 (if (memq system-type
'(windows-nt cygwin
))
36 ;; dynamically scoped for tramp
37 (defvar org-babel-call-process-region-original nil
)
38 (defvar org-src-lang-modes
)
39 (defvar org-babel-library-of-babel
)
40 (declare-function show-all
"outline" ())
41 (declare-function org-every
"org" (pred seq
))
42 (declare-function org-remove-indentation
"org" (code &optional n
))
43 (declare-function org-reduce
"org" (CL-FUNC CL-SEQ
&rest CL-KEYS
))
44 (declare-function org-mark-ring-push
"org" (&optional pos buffer
))
45 (declare-function tramp-compat-make-temp-file
"tramp-compat"
46 (filename &optional dir-flag
))
47 (declare-function tramp-dissect-file-name
"tramp" (name &optional nodefault
))
48 (declare-function tramp-file-name-user
"tramp" (vec))
49 (declare-function tramp-file-name-host
"tramp" (vec))
50 (declare-function with-parsed-tramp-file-name
"tramp" (filename var
&rest body
))
51 (declare-function org-icompleting-read
"org" (&rest args
))
52 (declare-function org-edit-src-code
"org-src" (&optional code edit-buffer-name
))
53 (declare-function org-edit-src-exit
"org-src" ())
54 (declare-function org-open-at-point
"org" (&optional in-emacs reference-buffer
))
55 (declare-function org-save-outline-visibility
"org-macs" (use-markers &rest body
))
56 (declare-function org-outline-overlay-data
"org" (&optional use-markers
))
57 (declare-function org-set-outline-overlay-data
"org" (data))
58 (declare-function org-narrow-to-subtree
"org" ())
59 (declare-function org-split-string
"org" (string &optional separators
))
60 (declare-function org-entry-get
"org"
61 (pom property
&optional inherit literal-nil
))
62 (declare-function org-make-options-regexp
"org" (kwds &optional extra
))
63 (declare-function org-do-remove-indentation
"org" (&optional n
))
64 (declare-function org-next-block
"org" (arg &optional backward block-regexp
))
65 (declare-function org-previous-block
"org" (arg &optional block-regexp
))
66 (declare-function org-show-context
"org" (&optional key
))
67 (declare-function org-at-table-p
"org" (&optional table-type
))
68 (declare-function org-cycle
"org" (&optional arg
))
69 (declare-function org-uniquify
"org" (list))
70 (declare-function org-current-level
"org" ())
71 (declare-function org-table-import
"org-table" (file arg
))
72 (declare-function org-add-hook
"org-compat"
73 (hook function
&optional append local
))
74 (declare-function org-table-align
"org-table" ())
75 (declare-function org-table-end
"org-table" (&optional table-type
))
76 (declare-function orgtbl-to-generic
"org-table" (table params
))
77 (declare-function orgtbl-to-orgtbl
"org-table" (table params
))
78 (declare-function org-babel-tangle-comment-links
"ob-tangle" (&optional info
))
79 (declare-function org-babel-lob-get-info
"ob-lob" nil
)
80 (declare-function org-babel-ref-split-args
"ob-ref" (arg-string))
81 (declare-function org-babel-ref-parse
"ob-ref" (assignment))
82 (declare-function org-babel-ref-resolve
"ob-ref" (ref))
83 (declare-function org-babel-ref-goto-headline-id
"ob-ref" (id))
84 (declare-function org-babel-ref-headline-body
"ob-ref" ())
85 (declare-function org-babel-lob-execute-maybe
"ob-lob" ())
86 (declare-function org-number-sequence
"org-compat" (from &optional to inc
))
87 (declare-function org-at-item-p
"org-list" ())
88 (declare-function org-list-parse-list
"org-list" (&optional delete
))
89 (declare-function org-list-to-generic
"org-list" (LIST PARAMS
))
90 (declare-function org-list-struct
"org-list" ())
91 (declare-function org-list-prevs-alist
"org-list" (struct))
92 (declare-function org-list-get-list-end
"org-list" (item struct prevs
))
93 (declare-function org-remove-if
"org" (predicate seq
))
94 (declare-function org-completing-read
"org" (&rest args
))
95 (declare-function org-escape-code-in-region
"org-src" (beg end
))
96 (declare-function org-unescape-code-in-string
"org-src" (s))
97 (declare-function org-table-to-lisp
"org-table" (&optional txt
))
98 (declare-function org-reverse-string
"org" (string))
99 (declare-function org-element-context
"org-element" (&optional element
))
100 (declare-function org-element-type
"org-element" (element))
101 (declare-function org-element-at-point
"org-element" ())
102 (declare-function org-element-property
"org-element" (property element
))
103 (declare-function org-every
"org" (pred seq
))
104 (declare-function org-macro-escape-arguments
"org-macro" (&rest args
))
106 (defgroup org-babel nil
107 "Code block evaluation and management in `org-mode' documents."
111 (defcustom org-confirm-babel-evaluate t
112 "Confirm before evaluation.
113 Require confirmation before interactively evaluating code
114 blocks in Org-mode buffers. The default value of this variable
115 is t, meaning confirmation is required for any code block
116 evaluation. This variable can be set to nil to inhibit any
117 future confirmation requests. This variable can also be set to a
118 function which takes two arguments the language of the code block
119 and the body of the code block. Such a function should then
120 return a non-nil value if the user should be prompted for
121 execution or nil if no prompt is required.
123 Warning: Disabling confirmation may result in accidental
124 evaluation of potentially harmful code. It may be advisable
125 remove code block execution from C-c C-c as further protection
126 against accidental code block evaluation. The
127 `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
128 remove code block execution from the C-c C-c keybinding."
131 :type
'(choice boolean function
))
132 ;; don't allow this variable to be changed through file settings
133 (put 'org-confirm-babel-evaluate
'safe-local-variable
(lambda (x) (eq x t
)))
135 (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
136 "Remove code block evaluation from the C-c C-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-header (params key
&optional others
)
213 "Select only header argument of type KEY from a list.
214 Optional argument OTHERS indicates that only the header that do
215 not match KEY should be returned."
218 (lambda (p) (when (funcall (if others
#'not
#'identity
) (eq (car p
) key
)) p
))
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 (defmacro org-babel-check-confirm-evaluate
(info &rest body
)
285 "Evaluate BODY with special execution confirmation variables set.
287 Specifically; NOEVAL will indicate if evaluation is allowed,
288 QUERY will indicate if a user query is required, CODE-BLOCK will
289 hold the language of the code block, and BLOCK-NAME will hold the
290 name of the code block."
291 (declare (indent defun
))
293 (lang block-body headers name head eval eval-no export eval-no-export
)
294 `(let* ((,lang
(nth 0 ,info
))
295 (,block-body
(nth 1 ,info
))
296 (,headers
(nth 2 ,info
))
297 (,name
(nth 4 ,info
))
298 (,head
(nth 6 ,info
))
299 (,eval
(or (cdr (assoc :eval
,headers
))
300 (when (assoc :noeval
,headers
) "no")))
301 (,eval-no
(or (equal ,eval
"no")
302 (equal ,eval
"never")))
303 (,export org-babel-exp-reference-buffer
)
304 (,eval-no-export
(and ,export
(or (equal ,eval
"no-export")
305 (equal ,eval
"never-export"))))
306 (noeval (or ,eval-no
,eval-no-export
))
307 (query (or (equal ,eval
"query")
308 (and ,export
(equal ,eval
"query-export"))
309 (if (functionp org-confirm-babel-evaluate
)
312 (funcall org-confirm-babel-evaluate
314 org-confirm-babel-evaluate
)))
315 (code-block (if ,info
(format " %s " ,lang
) " "))
316 (block-name (if ,name
(format " (%s) " ,name
) " ")))
319 (defsubst org-babel-check-evaluate
(info)
320 "Check if code block INFO should be evaluated.
321 Do not query the user."
322 (org-babel-check-confirm-evaluate info
324 (message (format "Evaluation of this%scode-block%sis disabled."
325 code-block block-name
))))))
327 ;; dynamically scoped for asynchronous export
328 (defvar org-babel-confirm-evaluate-answer-no
)
330 (defsubst org-babel-confirm-evaluate
(info)
331 "Confirm evaluation of the code block INFO.
333 If the variable `org-babel-confirm-evaluate-answer-no' is bound
334 to a non-nil value, auto-answer with \"no\".
336 This query can also be suppressed by setting the value of
337 `org-confirm-babel-evaluate' to nil, in which case all future
338 interactive code block evaluations will proceed without any
339 confirmation from the user.
341 Note disabling confirmation may result in accidental evaluation
342 of potentially harmful code."
343 (org-babel-check-confirm-evaluate info
346 (and (not (org-bound-and-true-p
347 org-babel-confirm-evaluate-answer-no
))
349 (format "Evaluate this%scode block%son your system? "
350 code-block block-name
)))
351 (message (format "Evaluation of this%scode-block%sis aborted."
352 code-block block-name
)))))))
355 (defun org-babel-execute-safely-maybe ()
356 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
357 (org-babel-execute-maybe)))
359 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-execute-safely-maybe
)
362 (defun org-babel-execute-maybe ()
364 (or (org-babel-execute-src-block-maybe)
365 (org-babel-lob-execute-maybe)))
367 (defmacro org-babel-when-in-src-block
(&rest body
)
368 "Execute BODY if point is in a source block and return t.
370 Otherwise do nothing and return nil."
371 `(if (or (org-babel-where-is-src-block-head)
372 (org-babel-get-inline-src-block-matches))
378 (defun org-babel-execute-src-block-maybe ()
379 "Conditionally execute a source block.
380 Detect if this is context for a Babel src-block and if so
381 then run `org-babel-execute-src-block'."
383 (org-babel-when-in-src-block
384 (org-babel-eval-wipe-error-buffer)
385 (org-babel-execute-src-block current-prefix-arg
)))
388 (defun org-babel-view-src-block-info ()
389 "Display information on the current source block.
390 This includes header arguments, language and name, and is largely
391 a window into the `org-babel-get-src-block-info' function."
393 (let ((info (org-babel-get-src-block-info 'light
))
394 (full (lambda (it) (> (length it
) 0)))
395 (printf (lambda (fmt &rest args
) (princ (apply #'format fmt args
)))))
397 (with-help-window (help-buffer)
398 (let ((name (nth 4 info
))
400 (switches (nth 3 info
))
401 (header-args (nth 2 info
)))
402 (when name
(funcall printf
"Name: %s\n" name
))
403 (when lang
(funcall printf
"Lang: %s\n" lang
))
404 (funcall printf
"Properties:\n")
405 (funcall printf
"\t:header-args \t%s\n" (org-entry-get (point) "header-args" t
))
406 (funcall printf
"\t:header-args:%s \t%s\n" lang
(org-entry-get (point) (concat "header-args:" lang
) t
))
408 (when (funcall full switches
) (funcall printf
"Switches: %s\n" switches
))
409 (funcall printf
"Header Arguments:\n")
410 (dolist (pair (sort header-args
411 (lambda (a b
) (string< (symbol-name (car a
))
412 (symbol-name (car b
))))))
413 (when (funcall full
(format "%s" (cdr pair
)))
414 (funcall printf
"\t%S%s\t%s\n"
416 (if (> (length (format "%S" (car pair
))) 7) "" "\t")
420 (defun org-babel-expand-src-block-maybe ()
421 "Conditionally expand a source block.
422 Detect if this is context for a org-babel src-block and if so
423 then run `org-babel-expand-src-block'."
425 (org-babel-when-in-src-block
426 (org-babel-expand-src-block current-prefix-arg
)))
429 (defun org-babel-load-in-session-maybe ()
430 "Conditionally load a source block in a session.
431 Detect if this is context for a org-babel src-block and if so
432 then run `org-babel-load-in-session'."
434 (org-babel-when-in-src-block
435 (org-babel-load-in-session current-prefix-arg
)))
437 (add-hook 'org-metaup-hook
'org-babel-load-in-session-maybe
)
440 (defun org-babel-pop-to-session-maybe ()
441 "Conditionally pop to a session.
442 Detect if this is context for a org-babel src-block and if so
443 then run `org-babel-switch-to-session'."
445 (org-babel-when-in-src-block
446 (org-babel-switch-to-session current-prefix-arg
)))
448 (add-hook 'org-metadown-hook
'org-babel-pop-to-session-maybe
)
450 (defconst org-babel-common-header-args-w-values
451 '((cache .
((no yes
)))
453 (colnames .
((nil no yes
)))
454 (comments .
((no link yes org both noweb
)))
456 (eval .
((yes no no-export strip-export never-export eval never
458 (exports .
((code results both none
)))
463 (hlines .
((no yes
)))
464 (mkdirp .
((yes no
)))
467 (noweb .
((yes no tangle no-export strip-export
)))
471 (padline .
((yes no
)))
474 (results .
((file list vector table scalar verbatim
)
475 (raw html latex org code pp drawer
)
476 (replace silent none append prepend
)
478 (rownames .
((no yes
)))
482 (tangle .
((tangle yes no
:any
)))
483 (tangle-mode .
((#o755
#o555
#o444
:any
)))
487 (defconst org-babel-header-arg-names
488 (mapcar #'car org-babel-common-header-args-w-values
)
489 "Common header arguments used by org-babel.
490 Note that individual languages may define their own language
491 specific header arguments as well.")
493 (defconst org-babel-safe-header-args
494 '(:cache
:colnames
:comments
:exports
:epilogue
:hlines
:noeval
495 :noweb
:noweb-ref
:noweb-sep
:padline
:prologue
:rownames
496 :sep
:session
:tangle
:wrap
497 (:eval .
("never" "query"))
498 (:results .
(lambda (str) (not (string-match "file" str
)))))
499 "A list of safe header arguments for babel source blocks.
501 The list can have entries of the following forms:
502 - :ARG -> :ARG is always a safe header arg
503 - (:ARG . (VAL1 VAL2 ...)) -> :ARG is safe as a header arg if it is
504 `equal' to one of the VALs.
505 - (:ARG . FN) -> :ARG is safe as a header arg if the function FN
506 returns non-nil. FN is passed one
507 argument, the value of the header arg
510 (defmacro org-babel-header-args-safe-fn
(safe-list)
511 "Return a function that determines whether a list of header args are safe.
514 \(put 'org-babel-default-header-args 'safe-local-variable
515 (org-babel-header-args-safe-p org-babel-safe-header-args)
517 This allows org-babel languages to extend the list of safe values for
518 their `org-babel-default-header-args:foo' variable.
520 For the format of SAFE-LIST, see `org-babel-safe-header-args'."
526 (org-babel-one-header-arg-safe-p pair
,safe-list
)))
529 (defvar org-babel-default-header-args
530 '((:session .
"none") (:results .
"replace") (:exports .
"code")
531 (:cache .
"no") (:noweb .
"no") (:hlines .
"no") (:tangle .
"no"))
532 "Default arguments to use when evaluating a source block.")
533 (put 'org-babel-default-header-args
'safe-local-variable
534 (org-babel-header-args-safe-fn org-babel-safe-header-args
))
536 (defvar org-babel-default-inline-header-args
537 '((:session .
"none") (:results .
"replace")
538 (:exports .
"results") (:hlines .
"yes"))
539 "Default arguments to use when evaluating an inline source block.")
540 (put 'org-babel-default-inline-header-args
'safe-local-variable
541 (org-babel-header-args-safe-fn org-babel-safe-header-args
))
543 (defvar org-babel-data-names
'("tblname" "results" "name"))
545 (defvar org-babel-result-regexp
546 (concat "^[ \t]*#\\+"
547 (regexp-opt org-babel-data-names t
)
549 ;; FIXME The string below is `org-ts-regexp'
550 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
551 " \\)?\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*")
552 "Regular expression used to match result lines.
553 If the results are associated with a hash key then the hash will
554 be saved in the second match data.")
556 (defvar org-babel-result-w-name-regexp
557 (concat org-babel-result-regexp
558 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
560 (defvar org-babel-min-lines-for-block-output
10
561 "The minimum number of lines for block output.
562 If number of lines of output is equal to or exceeds this
563 value, the output is placed in a #+begin_example...#+end_example
564 block. Otherwise the output is marked as literal by inserting
565 colons at the starts of the lines. This variable only takes
566 effect if the :results output option is in effect.")
568 (defvar org-babel-noweb-error-all-langs nil
569 "Raise errors when noweb references don't resolve.
570 Also see `org-babel-noweb-error-langs' to control noweb errors on
571 a language by language bases.")
573 (defvar org-babel-noweb-error-langs nil
574 "Languages for which Babel will raise literate programming errors.
575 List of languages for which errors should be raised when the
576 source code block satisfying a noweb reference in this language
577 can not be resolved. Also see `org-babel-noweb-error-all-langs'
578 to raise errors for all languages.")
580 (defvar org-babel-hash-show
4
581 "Number of initial characters to show of a hidden results hash.")
583 (defvar org-babel-hash-show-time nil
584 "Non-nil means show the time the code block was evaluated in the result hash.")
586 (defvar org-babel-after-execute-hook nil
587 "Hook for functions to be called after `org-babel-execute-src-block'")
589 (defun org-babel-named-src-block-regexp-for-name (&optional name
)
590 "This generates a regexp used to match a src block named NAME.
591 If NAME is nil, match any name. Matched name is then put in
592 match group 9. Other match groups are defined in
593 `org-babel-src-block-regexp'."
594 (concat org-babel-src-name-regexp
595 (concat (if name
(regexp-quote name
) "\\(?9:.*?\\)") "[ \t]*" )
596 "\\(?:\n[ \t]*#\\+\\S-+:.*\\)*?"
598 (substring org-babel-src-block-regexp
1)))
600 (defun org-babel-named-data-regexp-for-name (name)
601 "This generates a regexp used to match data named NAME."
602 (concat org-babel-result-regexp
(regexp-quote name
) "\\([ \t]\\|$\\)"))
605 (defvar call-process-region
)
606 (defvar org-babel-current-src-block-location nil
607 "Marker pointing to the src block currently being executed.
608 This may also point to a call line or an inline code block. If
609 multiple blocks are being executed (e.g., in chained execution
610 through use of the :var header argument) this marker points to
611 the outer-most code block.")
614 (defun org-babel-execute-src-block (&optional arg info params
)
615 "Execute the current source code block.
616 Insert the results of execution into the buffer. Source code
617 execution and the collection and formatting of results can be
618 controlled through a variety of header arguments.
620 With prefix argument ARG, force re-execution even if an existing
621 result cached in the buffer would otherwise have been returned.
623 Optionally supply a value for INFO in the form returned by
624 `org-babel-get-src-block-info'.
626 Optionally supply a value for PARAMS which will be merged with
627 the header arguments specified at the front of the source code
630 (let* ((org-babel-current-src-block-location
631 (or org-babel-current-src-block-location
633 (org-babel-where-is-src-block-head)
635 (and (org-babel-get-inline-src-block-matches)
636 (match-beginning 0))))
639 (org-babel-get-src-block-info)))
640 (merged-params (org-babel-merge-params (nth 2 info
) params
)))
641 (when (org-babel-check-evaluate
642 (let ((i info
)) (setf (nth 2 i
) merged-params
) i
))
643 (let* ((params (if params
644 (org-babel-process-params merged-params
)
646 (cachep (and (not arg
) (cdr (assoc :cache params
))
647 (string= "yes" (cdr (assoc :cache params
)))))
648 (new-hash (when cachep
(org-babel-sha1-hash info
)))
649 (old-hash (when cachep
(org-babel-current-result-hash)))
650 (cache-current-p (and (not arg
) new-hash
651 (equal new-hash old-hash
))))
654 (save-excursion ;; return cached result
655 (goto-char (org-babel-where-is-src-block-result nil info
))
657 (skip-chars-forward " \t")
658 (let ((result (org-babel-read-result)))
659 (message (replace-regexp-in-string
660 "%" "%%" (format "%S" result
))) result
)))
661 ((org-babel-confirm-evaluate
662 (let ((i info
)) (setf (nth 2 i
) merged-params
) i
))
663 (let* ((lang (nth 0 info
))
664 (result-params (cdr (assoc :result-params params
)))
665 (body (setf (nth 1 info
)
666 (if (org-babel-noweb-p params
:eval
)
667 (org-babel-expand-noweb-references info
)
669 (dir (cdr (assoc :dir params
)))
671 (or (and dir
(file-name-as-directory (expand-file-name dir
)))
673 (org-babel-call-process-region-original ;; for tramp handler
674 (or (org-bound-and-true-p
675 org-babel-call-process-region-original
)
676 (symbol-function 'call-process-region
)))
677 (indent (nth 5 info
))
680 (let ((call-process-region
682 (apply 'org-babel-tramp-handle-call-process-region
686 (let ((f (intern (concat "org-babel-execute:" f
))))
687 (when (fboundp f
) f
)))))
689 (or (funcall lang-check lang
)
692 (cdr (assoc lang org-src-lang-modes
))))
693 (error "No org-babel-execute function for %s!"
695 (message "executing %s code block%s..."
697 (if (nth 4 info
) (format " (%s)" (nth 4 info
)) ""))
698 (if (member "none" result-params
)
700 (funcall cmd body params
)
701 (message "result silenced")
704 (let ((result (funcall cmd body params
)))
705 (if (and (eq (cdr (assoc :result-type params
))
707 (or (member "vector" result-params
)
708 (member "table" result-params
))
709 (not (listp result
)))
710 (list (list result
)) result
)))
711 ;; If non-empty result and :file then write to :file.
712 (when (cdr (assoc :file params
))
714 (with-temp-file (cdr (assoc :file params
))
716 (org-babel-format-result
717 result
(cdr (assoc :sep
(nth 2 info
)))))))
718 (setq result
(cdr (assoc :file params
))))
719 ;; Possibly perform post process provided its appropriate.
720 (when (cdr (assoc :post params
))
721 (let ((*this
* (if (cdr (assoc :file params
))
722 (org-babel-result-to-file
723 (cdr (assoc :file params
))
724 (when (assoc :file-desc params
)
725 (or (cdr (assoc :file-desc params
))
728 (setq result
(org-babel-ref-resolve
729 (cdr (assoc :post params
))))
730 (when (cdr (assoc :file params
))
732 (remove "file" result-params
)))))
733 (org-babel-insert-result
734 result result-params info new-hash indent lang
))
735 (run-hooks 'org-babel-after-execute-hook
)
737 (setq call-process-region
738 'org-babel-call-process-region-original
)))))))))
740 (defun org-babel-expand-body:generic
(body params
&optional var-lines
)
741 "Expand BODY with PARAMS.
742 Expand a block of code with org-babel according to its header
743 arguments. This generic implementation of body expansion is
744 called for languages which have not defined their own specific
745 org-babel-expand-body:lang function."
746 (let ((pro (cdr (assoc :prologue params
)))
747 (epi (cdr (assoc :epilogue params
))))
748 (mapconcat #'identity
749 (append (when pro
(list pro
))
752 (when epi
(list epi
)))
756 (defun org-babel-expand-src-block (&optional arg info params
)
757 "Expand the current source code block.
758 Expand according to the source code block's header
759 arguments and pop open the results in a preview buffer."
761 (let* ((info (or info
(org-babel-get-src-block-info)))
763 (params (setf (nth 2 info
)
764 (sort (org-babel-merge-params (nth 2 info
) params
)
765 (lambda (el1 el2
) (string< (symbol-name (car el1
))
766 (symbol-name (car el2
)))))))
767 (body (setf (nth 1 info
)
768 (if (org-babel-noweb-p params
:eval
)
769 (org-babel-expand-noweb-references info
) (nth 1 info
))))
770 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
771 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
774 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
775 (org-babel-expand-body:generic
776 body params
(and (fboundp assignments-cmd
)
777 (funcall assignments-cmd params
))))))
778 (if (org-called-interactively-p 'any
)
780 expanded
(concat "*Org-Babel Preview " (buffer-name) "[ " lang
" ]*"))
783 (defun org-babel-edit-distance (s1 s2
)
784 "Return the edit (levenshtein) distance between strings S1 S2."
785 (let* ((l1 (length s1
))
787 (dist (vconcat (mapcar (lambda (_) (make-vector (1+ l2
) nil
))
788 (number-sequence 1 (1+ l1
)))))
789 (in (lambda (i j
) (aref (aref dist i
) j
))))
790 (setf (aref (aref dist
0) 0) 0)
791 (dolist (j (number-sequence 1 l2
))
792 (setf (aref (aref dist
0) j
) j
))
793 (dolist (i (number-sequence 1 l1
))
794 (setf (aref (aref dist i
) 0) i
)
795 (dolist (j (number-sequence 1 l2
))
796 (setf (aref (aref dist i
) j
)
798 (1+ (funcall in
(1- i
) j
))
799 (1+ (funcall in i
(1- j
)))
800 (+ (if (equal (aref s1
(1- i
)) (aref s2
(1- j
))) 0 1)
801 (funcall in
(1- i
) (1- j
)))))))
804 (defun org-babel-combine-header-arg-lists (original &rest others
)
805 "Combine a number of lists of header argument names and arguments."
806 (let ((results (copy-sequence original
)))
807 (dolist (new-list others
)
808 (dolist (arg-pair new-list
)
809 (let ((header (car arg-pair
))
810 (args (cdr arg-pair
)))
812 (cons arg-pair
(org-remove-if
813 (lambda (pair) (equal header
(car pair
)))
818 (defun org-babel-check-src-block ()
819 "Check for misspelled header arguments in the current code block."
821 ;; TODO: report malformed code block
822 ;; TODO: report incompatible combinations of header arguments
823 ;; TODO: report uninitialized variables
824 (let ((too-close 2) ;; <- control closeness to report potential match
825 (names (mapcar #'symbol-name org-babel-header-arg-names
)))
826 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg
)) 1))
827 (and (org-babel-where-is-src-block-head)
828 (org-babel-parse-header-arguments
830 (match-string 4))))))
832 (when (and (not (string= header name
))
833 (<= (org-babel-edit-distance header name
) too-close
)
834 (not (member header names
)))
835 (error "Supplied header \"%S\" is suspiciously close to \"%S\""
837 (message "No suspicious header arguments found.")))
840 (defun org-babel-insert-header-arg (&optional header-arg value
)
841 "Insert a header argument selecting from lists of common args and values."
843 (let* ((info (org-babel-get-src-block-info 'light
))
846 (lang-headers (intern (concat "org-babel-header-args:" lang
)))
847 (headers (org-babel-combine-header-arg-lists
848 org-babel-common-header-args-w-values
849 (when (boundp lang-headers
) (eval lang-headers
))))
850 (header-arg (or header-arg
851 (org-icompleting-read
854 (lambda (header-spec) (symbol-name (car header-spec
)))
856 (vals (cdr (assoc (intern header-arg
) headers
)))
860 (read-from-minibuffer "value: "))
864 (let ((arg (org-icompleting-read
867 (mapcar #'symbol-name group
)))))
868 (if (and arg
(not (string= "default" arg
)))
874 (goto-char (point-at-eol))
875 (unless (= (char-before (point)) ?\
) (insert " "))
876 (insert ":" header-arg
) (when value
(insert " " value
)))))
878 ;; Add support for completing-read insertion of header arguments after ":"
879 (defun org-babel-header-arg-expand ()
880 "Call `org-babel-enter-header-arg-w-completion' in appropriate contexts."
881 (when (and (equal (char-before) ?\
:) (org-babel-where-is-src-block-head))
882 (org-babel-enter-header-arg-w-completion (match-string 2))))
884 (defun org-babel-enter-header-arg-w-completion (&optional lang
)
885 "Insert header argument appropriate for LANG with completion."
886 (let* ((lang-headers-var (intern (concat "org-babel-header-args:" lang
)))
887 (lang-headers (when (boundp lang-headers-var
) (eval lang-headers-var
)))
888 (headers-w-values (org-babel-combine-header-arg-lists
889 org-babel-common-header-args-w-values lang-headers
))
890 (headers (mapcar #'symbol-name
(mapcar #'car headers-w-values
)))
891 (header (org-completing-read "Header Arg: " headers
))
892 (args (cdr (assoc (intern header
) headers-w-values
)))
893 (arg (when (and args
(listp args
))
895 (format "%s: " header
)
896 (mapcar #'symbol-name
(apply #'append args
))))))
897 (insert (concat header
" " (or arg
"")))
900 (add-hook 'org-tab-first-hook
'org-babel-header-arg-expand
)
903 (defun org-babel-load-in-session (&optional arg info
)
904 "Load the body of the current source-code block.
905 Evaluate the header arguments for the source block before
906 entering the session. After loading the body this pops open the
909 (let* ((info (or info
(org-babel-get-src-block-info)))
911 (params (nth 2 info
))
913 (user-error "No src code block at point")
915 (if (org-babel-noweb-p params
:eval
)
916 (org-babel-expand-noweb-references info
)
918 (session (cdr (assoc :session params
)))
919 (dir (cdr (assoc :dir params
)))
921 (or (and dir
(file-name-as-directory dir
)) default-directory
))
922 (cmd (intern (concat "org-babel-load-session:" lang
))))
923 (unless (fboundp cmd
)
924 (error "No org-babel-load-session function for %s!" lang
))
925 (pop-to-buffer (funcall cmd session body params
))
929 (defun org-babel-initiate-session (&optional arg info
)
930 "Initiate session for current code block.
931 If called with a prefix argument then resolve any variable
932 references in the header arguments and assign these variables in
933 the session. Copy the body of the code block to the kill ring."
935 (let* ((info (or info
(org-babel-get-src-block-info (not arg
))))
938 (params (nth 2 info
))
939 (session (cdr (assoc :session params
)))
940 (dir (cdr (assoc :dir params
)))
942 (or (and dir
(file-name-as-directory dir
)) default-directory
))
943 (init-cmd (intern (format "org-babel-%s-initiate-session" lang
)))
944 (prep-cmd (intern (concat "org-babel-prep-session:" lang
))))
945 (if (and (stringp session
) (string= session
"none"))
946 (error "This block is not using a session!"))
947 (unless (fboundp init-cmd
)
948 (error "No org-babel-initiate-session function for %s!" lang
))
949 (with-temp-buffer (insert (org-babel-trim body
))
950 (copy-region-as-kill (point-min) (point-max)))
952 (unless (fboundp prep-cmd
)
953 (error "No org-babel-prep-session function for %s!" lang
))
954 (funcall prep-cmd session params
))
955 (funcall init-cmd session params
)))
958 (defun org-babel-switch-to-session (&optional arg info
)
959 "Switch to the session of the current code block.
960 Uses `org-babel-initiate-session' to start the session. If called
961 with a prefix argument then this is passed on to
962 `org-babel-initiate-session'."
964 (pop-to-buffer (org-babel-initiate-session arg info
))
967 (defalias 'org-babel-pop-to-session
'org-babel-switch-to-session
)
969 (defvar org-src-window-setup
)
972 (defun org-babel-switch-to-session-with-code (&optional arg info
)
973 "Switch to code buffer and display session."
977 (let ((other-window-buffer (window-buffer (next-window))))
978 (set-window-buffer (next-window) (current-buffer))
979 (set-window-buffer (selected-window) other-window-buffer
))
981 (info (org-babel-get-src-block-info))
982 (org-src-window-setup 'reorganize-frame
))
984 (org-babel-switch-to-session arg info
))
986 (funcall swap-windows
)))
989 (defmacro org-babel-do-in-edit-buffer
(&rest body
)
990 "Evaluate BODY in edit buffer if there is a code block at point.
991 Return t if a code block was found at point, nil otherwise."
992 `(let ((org-src-window-setup 'switch-invisibly
))
993 (when (and (org-babel-where-is-src-block-head)
995 (unwind-protect (progn ,@body
)
998 (def-edebug-spec org-babel-do-in-edit-buffer
(body))
1000 (defun org-babel-do-key-sequence-in-edit-buffer (key)
1001 "Read key sequence and execute the command in edit buffer.
1002 Enter a key sequence to be executed in the language major-mode
1003 edit buffer. For example, TAB will alter the contents of the
1004 Org-mode code block according to the effect of TAB in the
1005 language major-mode buffer. For languages that support
1006 interactive sessions, this can be used to send code from the Org
1007 buffer to the session for evaluation using the native major-mode
1008 evaluation mechanisms."
1009 (interactive "kEnter key-sequence to execute in edit buffer: ")
1010 (org-babel-do-in-edit-buffer
1012 (key-binding (or key
(read-key-sequence nil
))))))
1014 (defvar org-bracket-link-regexp
)
1016 (defun org-babel-active-location-p ()
1017 (memq (org-element-type (save-match-data (org-element-context)))
1018 '(babel-call inline-babel-call inline-src-block src-block
)))
1021 (defun org-babel-open-src-block-result (&optional re-run
)
1022 "If `point' is on a src block then open the results of the
1023 source code block, otherwise return nil. With optional prefix
1024 argument RE-RUN the source-code block is evaluated even if
1025 results already exist."
1027 (let ((info (org-babel-get-src-block-info 'light
)))
1030 ;; go to the results, if there aren't any then run the block
1031 (goto-char (or (and (not re-run
) (org-babel-where-is-src-block-result))
1032 (progn (org-babel-execute-src-block)
1033 (org-babel-where-is-src-block-result))))
1035 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
1037 (if (looking-at org-bracket-link-regexp
)
1040 (let ((r (org-babel-format-result
1041 (org-babel-read-result) (cdr (assoc :sep
(nth 2 info
))))))
1042 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
1043 (delete-region (point-min) (point-max))
1048 (defmacro org-babel-map-src-blocks
(file &rest body
)
1049 "Evaluate BODY forms on each source-block in FILE.
1050 If FILE is nil evaluate BODY forms on source blocks in current
1051 buffer. During evaluation of BODY the following local variables
1052 are set relative to the currently matched code block.
1054 full-block ------- string holding the entirety of the code block
1055 beg-block -------- point at the beginning of the code block
1056 end-block -------- point at the end of the matched code block
1057 lang ------------- string holding the language of the code block
1058 beg-lang --------- point at the beginning of the lang
1059 end-lang --------- point at the end of the lang
1060 switches --------- string holding the switches
1061 beg-switches ----- point at the beginning of the switches
1062 end-switches ----- point at the end of the switches
1063 header-args ------ string holding the header-args
1064 beg-header-args -- point at the beginning of the header-args
1065 end-header-args -- point at the end of the header-args
1066 body ------------- string holding the body of the code block
1067 beg-body --------- point at the beginning of the body
1068 end-body --------- point at the end of the body"
1069 (declare (indent 1))
1070 (let ((tempvar (make-symbol "file")))
1071 `(let* ((case-fold-search t
)
1073 (visited-p (or (null ,tempvar
)
1074 (get-file-buffer (expand-file-name ,tempvar
))))
1075 (point (point)) to-be-removed
)
1076 (save-window-excursion
1077 (when ,tempvar
(find-file ,tempvar
))
1078 (setq to-be-removed
(current-buffer))
1079 (goto-char (point-min))
1080 (while (re-search-forward org-babel-src-block-regexp nil t
)
1081 (when (org-babel-active-location-p)
1082 (goto-char (match-beginning 0))
1083 (let ((full-block (match-string 0))
1084 (beg-block (match-beginning 0))
1085 (end-block (match-end 0))
1086 (lang (match-string 2))
1087 (beg-lang (match-beginning 2))
1088 (end-lang (match-end 2))
1089 (switches (match-string 3))
1090 (beg-switches (match-beginning 3))
1091 (end-switches (match-end 3))
1092 (header-args (match-string 4))
1093 (beg-header-args (match-beginning 4))
1094 (end-header-args (match-end 4))
1095 (body (match-string 5))
1096 (beg-body (match-beginning 5))
1097 (end-body (match-end 5)))
1099 (goto-char end-block
)))))
1100 (unless visited-p
(kill-buffer to-be-removed
))
1101 (goto-char point
))))
1102 (def-edebug-spec org-babel-map-src-blocks
(form body
))
1105 (defmacro org-babel-map-inline-src-blocks
(file &rest body
)
1106 "Evaluate BODY forms on each inline source-block in FILE.
1107 If FILE is nil evaluate BODY forms on source blocks in current
1109 (declare (indent 1))
1110 (let ((tempvar (make-symbol "file")))
1111 `(let* ((case-fold-search t
)
1113 (visited-p (or (null ,tempvar
)
1114 (get-file-buffer (expand-file-name ,tempvar
))))
1115 (point (point)) to-be-removed
)
1116 (save-window-excursion
1117 (when ,tempvar
(find-file ,tempvar
))
1118 (setq to-be-removed
(current-buffer))
1119 (goto-char (point-min))
1120 (while (re-search-forward org-babel-inline-src-block-regexp nil t
)
1121 (when (org-babel-active-location-p)
1122 (goto-char (match-beginning 1))
1123 (save-match-data ,@body
))
1124 (goto-char (match-end 0))))
1125 (unless visited-p
(kill-buffer to-be-removed
))
1126 (goto-char point
))))
1127 (def-edebug-spec org-babel-map-inline-src-blocks
(form body
))
1129 (defvar org-babel-lob-one-liner-regexp
)
1132 (defmacro org-babel-map-call-lines
(file &rest body
)
1133 "Evaluate BODY forms on each call line in FILE.
1134 If FILE is nil evaluate BODY forms on source blocks in current
1136 (declare (indent 1))
1137 (let ((tempvar (make-symbol "file")))
1138 `(let* ((,tempvar
,file
)
1139 (visited-p (or (null ,tempvar
)
1140 (get-file-buffer (expand-file-name ,tempvar
))))
1141 (point (point)) to-be-removed
)
1142 (save-window-excursion
1143 (when ,tempvar
(find-file ,tempvar
))
1144 (setq to-be-removed
(current-buffer))
1145 (goto-char (point-min))
1146 (while (re-search-forward org-babel-lob-one-liner-regexp nil t
)
1147 (when (org-babel-active-location-p)
1148 (goto-char (match-beginning 1))
1149 (save-match-data ,@body
))
1150 (goto-char (match-end 0))))
1151 (unless visited-p
(kill-buffer to-be-removed
))
1152 (goto-char point
))))
1153 (def-edebug-spec org-babel-map-call-lines
(form body
))
1156 (defmacro org-babel-map-executables
(file &rest body
)
1157 (declare (indent 1))
1158 (let ((tempvar (make-symbol "file"))
1159 (rx (make-symbol "rx")))
1160 `(let* ((,tempvar
,file
)
1161 (,rx
(concat "\\(" org-babel-src-block-regexp
1162 "\\|" org-babel-inline-src-block-regexp
1163 "\\|" org-babel-lob-one-liner-regexp
"\\)"))
1164 (visited-p (or (null ,tempvar
)
1165 (get-file-buffer (expand-file-name ,tempvar
))))
1166 (point (point)) to-be-removed
)
1167 (save-window-excursion
1168 (when ,tempvar
(find-file ,tempvar
))
1169 (setq to-be-removed
(current-buffer))
1170 (goto-char (point-min))
1171 (while (re-search-forward ,rx nil t
)
1172 (when (org-babel-active-location-p)
1173 (goto-char (match-beginning 1))
1174 (when (looking-at org-babel-inline-src-block-regexp
)
1176 (save-match-data ,@body
))
1177 (goto-char (match-end 0))))
1178 (unless visited-p
(kill-buffer to-be-removed
))
1179 (goto-char point
))))
1180 (def-edebug-spec org-babel-map-executables
(form body
))
1183 (defun org-babel-execute-buffer (&optional arg
)
1184 "Execute source code blocks in a buffer.
1185 Call `org-babel-execute-src-block' on every source block in
1186 the current buffer."
1188 (org-babel-eval-wipe-error-buffer)
1189 (org-save-outline-visibility t
1190 (org-babel-map-executables nil
1191 (if (looking-at org-babel-lob-one-liner-regexp
)
1192 (org-babel-lob-execute-maybe)
1193 (org-babel-execute-src-block arg
)))))
1196 (defun org-babel-execute-subtree (&optional arg
)
1197 "Execute source code blocks in a subtree.
1198 Call `org-babel-execute-src-block' on every source block in
1199 the current subtree."
1203 (org-narrow-to-subtree)
1204 (org-babel-execute-buffer arg
)
1208 (defun org-babel-sha1-hash (&optional info
)
1209 "Generate an sha1 hash based on the value of info."
1211 (let ((print-level nil
)
1212 (info (or info
(org-babel-get-src-block-info))))
1214 (sort (copy-sequence (nth 2 info
))
1215 (lambda (a b
) (string< (car a
) (car b
)))))
1216 (let* ((rm (lambda (lst)
1217 (dolist (p '("replace" "silent" "none"
1218 "append" "prepend"))
1219 (setq lst
(remove p lst
)))
1222 (let ((v (if (and (listp (cdr arg
)) (null (cddr arg
)))
1223 (copy-sequence (cdr arg
))
1225 (when (and v
(not (and (sequencep v
)
1229 ((and (listp v
) ; lists are sorted
1230 (member (car arg
) '(:result-params
)))
1231 (sort (funcall rm v
) #'string
<))
1232 ((and (stringp v
) ; strings are sorted
1233 (member (car arg
) '(:results
:exports
)))
1234 (mapconcat #'identity
(sort (funcall rm
(split-string v
))
1239 (params (nth 2 info
))
1240 (body (if (org-babel-noweb-p params
:eval
)
1241 (org-babel-expand-noweb-references info
) (nth 1 info
)))
1242 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
1243 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
1246 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
1247 (org-babel-expand-body:generic
1248 body params
(and (fboundp assignments-cmd
)
1249 (funcall assignments-cmd params
))))))
1250 (let* ((it (format "%s-%s"
1253 (delq nil
(mapcar (lambda (arg)
1254 (let ((normalized (funcall norm arg
)))
1256 (format "%S" normalized
))))
1260 (when (org-called-interactively-p 'interactive
) (message hash
))
1263 (defun org-babel-current-result-hash (&optional info
)
1264 "Return the current in-buffer hash."
1265 (org-babel-where-is-src-block-result nil info
)
1266 (org-no-properties (match-string 5)))
1268 (defun org-babel-set-current-result-hash (hash info
)
1269 "Set the current in-buffer hash to HASH."
1270 (org-babel-where-is-src-block-result nil info
)
1271 (save-excursion (goto-char (match-beginning 5))
1272 (mapc #'delete-overlay
(overlays-at (point)))
1273 (forward-char org-babel-hash-show
)
1274 (mapc #'delete-overlay
(overlays-at (point)))
1275 (replace-match hash nil nil nil
5)
1276 (goto-char (point-at-bol))
1277 (org-babel-hide-hash)))
1279 (defun org-babel-hide-hash ()
1280 "Hide the hash in the current results line.
1281 Only the initial `org-babel-hash-show' characters of the hash
1282 will remain visible."
1283 (add-to-invisibility-spec '(org-babel-hide-hash . t
))
1285 (when (and (re-search-forward org-babel-result-regexp nil t
)
1287 (let* ((start (match-beginning 5))
1288 (hide-start (+ org-babel-hash-show start
))
1290 (hash (match-string 5))
1292 (setq ov1
(make-overlay start hide-start
))
1293 (setq ov2
(make-overlay hide-start end
))
1294 (overlay-put ov2
'invisible
'org-babel-hide-hash
)
1295 (overlay-put ov1
'babel-hash hash
)))))
1297 (defun org-babel-hide-all-hashes ()
1298 "Hide the hash in the current buffer.
1299 Only the initial `org-babel-hash-show' characters of each hash
1300 will remain visible. This function should be called as part of
1301 the `org-mode-hook'."
1303 (while (and (not org-babel-hash-show-time
)
1304 (re-search-forward org-babel-result-regexp nil t
))
1305 (goto-char (match-beginning 0))
1306 (org-babel-hide-hash)
1307 (goto-char (match-end 0)))))
1308 (add-hook 'org-mode-hook
'org-babel-hide-all-hashes
)
1310 (defun org-babel-hash-at-point (&optional point
)
1311 "Return the value of the hash at POINT.
1312 The hash is also added as the last element of the kill ring.
1313 This can be called with C-c C-c."
1315 (let ((hash (car (delq nil
(mapcar
1316 (lambda (ol) (overlay-get ol
'babel-hash
))
1317 (overlays-at (or point
(point))))))))
1318 (when hash
(kill-new hash
) (message hash
))))
1319 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-hash-at-point
)
1321 (defun org-babel-result-hide-spec ()
1322 "Hide portions of results lines.
1323 Add `org-babel-hide-result' as an invisibility spec for hiding
1324 portions of results lines."
1325 (add-to-invisibility-spec '(org-babel-hide-result . t
)))
1326 (add-hook 'org-mode-hook
'org-babel-result-hide-spec
)
1328 (defvar org-babel-hide-result-overlays nil
1329 "Overlays hiding results.")
1331 (defun org-babel-result-hide-all ()
1332 "Fold all results in the current buffer."
1334 (org-babel-show-result-all)
1336 (while (re-search-forward org-babel-result-regexp nil t
)
1337 (save-excursion (goto-char (match-beginning 0))
1338 (org-babel-hide-result-toggle-maybe)))))
1340 (defun org-babel-show-result-all ()
1341 "Unfold all results in the current buffer."
1342 (mapc 'delete-overlay org-babel-hide-result-overlays
)
1343 (setq org-babel-hide-result-overlays nil
))
1346 (defun org-babel-hide-result-toggle-maybe ()
1347 "Toggle visibility of result at point."
1349 (let ((case-fold-search t
))
1351 (beginning-of-line 1)
1352 (looking-at org-babel-result-regexp
))
1353 (progn (org-babel-hide-result-toggle)
1354 t
) ;; to signal that we took action
1355 nil
))) ;; to signal that we did not
1357 (defun org-babel-hide-result-toggle (&optional force
)
1358 "Toggle the visibility of the current result."
1362 (if (re-search-forward org-babel-result-regexp nil t
)
1363 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
1365 (while (looking-at org-babel-multi-line-header-regexp
)
1367 (goto-char (- (org-babel-result-end) 1)) (point)))
1369 (if (memq t
(mapcar (lambda (overlay)
1370 (eq (overlay-get overlay
'invisible
)
1371 'org-babel-hide-result
))
1372 (overlays-at start
)))
1373 (if (or (not force
) (eq force
'off
))
1375 (when (member ov org-babel-hide-result-overlays
)
1376 (setq org-babel-hide-result-overlays
1377 (delq ov org-babel-hide-result-overlays
)))
1378 (when (eq (overlay-get ov
'invisible
)
1379 'org-babel-hide-result
)
1380 (delete-overlay ov
)))
1381 (overlays-at start
)))
1382 (setq ov
(make-overlay start end
))
1383 (overlay-put ov
'invisible
'org-babel-hide-result
)
1384 ;; make the block accessible to isearch
1386 ov
'isearch-open-invisible
1388 (when (member ov org-babel-hide-result-overlays
)
1389 (setq org-babel-hide-result-overlays
1390 (delq ov org-babel-hide-result-overlays
)))
1391 (when (eq (overlay-get ov
'invisible
)
1392 'org-babel-hide-result
)
1393 (delete-overlay ov
))))
1394 (push ov org-babel-hide-result-overlays
)))
1395 (error "Not looking at a result line"))))
1397 ;; org-tab-after-check-for-cycling-hook
1398 (add-hook 'org-tab-first-hook
'org-babel-hide-result-toggle-maybe
)
1399 ;; Remove overlays when changing major mode
1400 (add-hook 'org-mode-hook
1401 (lambda () (org-add-hook 'change-major-mode-hook
1402 'org-babel-show-result-all
'append
'local
)))
1404 (defvar org-file-properties
)
1405 (defun org-babel-params-from-properties (&optional lang
)
1406 "Retrieve parameters specified as properties.
1407 Return a list of association lists of source block params
1408 specified in the properties of the current outline entry."
1411 ;; DEPRECATED header arguments specified as separate property at
1412 ;; point of definition.
1413 (org-babel-parse-multiple-vars
1417 (let* ((arg (symbol-name (car header
)))
1418 (val (org-entry-get (point) arg t
)))
1420 (cons (intern (concat ":" arg
))
1421 (org-babel-read val
)))))
1422 (org-babel-combine-header-arg-lists
1423 org-babel-common-header-args-w-values
1424 (let ((sym (intern (concat "org-babel-header-args:" lang
))))
1425 (and (boundp sym
) (symbol-value sym
)))))))
1426 ;; header arguments specified with the header-args property at
1428 (org-babel-parse-header-arguments
1429 (org-entry-get org-babel-current-src-block-location
1432 (and lang
; language-specific header arguments at point of call
1433 (org-babel-parse-header-arguments
1434 (org-entry-get org-babel-current-src-block-location
1435 (concat "header-args:" lang
)
1438 (defvar org-src-preserve-indentation
) ;; declare defcustom from org-src
1439 (defun org-babel-parse-src-block-match ()
1440 "Parse the results from a match of the `org-babel-src-block-regexp'."
1441 (let* ((block-indentation (length (match-string 1)))
1442 (lang (org-no-properties (match-string 2)))
1443 (lang-headers (intern (concat "org-babel-default-header-args:" lang
)))
1444 (switches (match-string 3))
1445 (body (org-no-properties
1446 (let* ((body (match-string 5))
1447 (sub-length (- (length body
) 1)))
1448 (if (and (> sub-length
0)
1449 (string= "\n" (substring body sub-length
)))
1450 (substring body
0 sub-length
)
1452 (preserve-indentation (or org-src-preserve-indentation
1454 (string-match "-i\\>" switches
)))))
1456 ;; get block body less properties, protective commas, and indentation
1459 (insert (org-unescape-code-in-string body
))
1460 (unless preserve-indentation
(org-do-remove-indentation))
1462 (apply #'org-babel-merge-params
1463 org-babel-default-header-args
1464 (when (boundp lang-headers
) (eval lang-headers
))
1466 (org-babel-params-from-properties lang
)
1467 (list (org-babel-parse-header-arguments
1468 (org-no-properties (or (match-string 4) ""))))))
1470 block-indentation
)))
1472 (defun org-babel-parse-inline-src-block-match ()
1473 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
1474 (let* ((lang (org-no-properties (match-string 2)))
1475 (lang-headers (intern (concat "org-babel-default-header-args:" lang
))))
1477 (org-unescape-code-in-string (org-no-properties (match-string 5)))
1478 (apply #'org-babel-merge-params
1479 org-babel-default-inline-header-args
1480 (if (boundp lang-headers
) (eval lang-headers
) nil
)
1482 (org-babel-params-from-properties lang
)
1483 (list (org-babel-parse-header-arguments
1484 (org-no-properties (or (match-string 4) ""))))))
1487 (defun org-babel-balanced-split (string alts
)
1488 "Split STRING on instances of ALTS.
1489 ALTS is a cons of two character options where each option may be
1490 either the numeric code of a single character or a list of
1491 character alternatives. For example to split on balanced
1492 instances of \"[ \t]:\" set ALTS to '((32 9) . 58)."
1493 (let* ((matches (lambda (ch spec
) (if (listp spec
) (member ch spec
) (equal spec ch
))))
1494 (matched (lambda (ch last
)
1496 (and (funcall matches ch
(cdr alts
))
1497 (funcall matches last
(car alts
)))
1498 (funcall matches ch alts
))))
1499 (balance 0) (last 0)
1501 (mapc (lambda (ch) ; split on [], (), "" balanced instances of [ \t]:
1502 (setq balance
(+ balance
1503 (cond ((or (equal 91 ch
) (equal 40 ch
)) 1)
1504 ((or (equal 93 ch
) (equal 41 ch
)) -
1)
1506 (when (and (equal 34 ch
) (not (equal 92 last
)))
1507 (setq quote
(not quote
)))
1508 (setq partial
(cons ch partial
))
1509 (when (and (= balance
0) (not quote
) (funcall matched ch last
))
1510 (setq lst
(cons (apply #'string
(nreverse
1517 (string-to-list string
))
1518 (nreverse (cons (apply #'string
(nreverse partial
)) lst
))))
1520 (defun org-babel-join-splits-near-ch (ch list
)
1521 "Join splits where \"=\" is on either end of the split."
1522 (let ((last= (lambda (str) (= ch
(aref str
(1- (length str
))))))
1523 (first= (lambda (str) (= ch
(aref str
0)))))
1525 (org-reduce (lambda (acc el
)
1526 (let ((head (car acc
)))
1527 (if (and head
(or (funcall last
= head
) (funcall first
= el
)))
1528 (cons (concat head el
) (cdr acc
))
1530 list
:initial-value nil
))))
1532 (defun org-babel-parse-header-arguments (arg-string)
1533 "Parse a string of header arguments returning an alist."
1534 (when (> (length arg-string
) 0)
1535 (org-babel-parse-multiple-vars
1540 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1542 (cons (intern (match-string 1 arg
))
1543 (org-babel-read (org-babel-chomp (match-string 2 arg
))))
1544 (cons (intern (org-babel-chomp arg
)) nil
)))
1545 (let ((raw (org-babel-balanced-split arg-string
'((32 9) .
58))))
1546 (cons (car raw
) (mapcar (lambda (r) (concat ":" r
)) (cdr raw
)))))))))
1548 (defun org-babel-parse-multiple-vars (header-arguments)
1549 "Expand multiple variable assignments behind a single :var keyword.
1551 This allows expression of multiple variables with one :var as
1554 #+PROPERTY: var foo=1, bar=2"
1556 (mapc (lambda (pair)
1557 (if (eq (car pair
) :var
)
1558 (mapcar (lambda (v) (push (cons :var
(org-babel-trim v
)) results
))
1559 (org-babel-join-splits-near-ch
1560 61 (org-babel-balanced-split (cdr pair
) 32)))
1561 (push pair results
)))
1563 (nreverse results
)))
1565 (defun org-babel-process-params (params)
1566 "Expand variables in PARAMS and add summary parameters."
1567 (let* ((processed-vars (mapcar (lambda (el)
1568 (if (consp (cdr el
))
1570 (org-babel-ref-parse (cdr el
))))
1571 (org-babel-get-header params
:var
)))
1572 (vars-and-names (if (and (assoc :colname-names params
)
1573 (assoc :rowname-names params
))
1574 (list processed-vars
)
1575 (org-babel-disassemble-tables
1577 (cdr (assoc :hlines params
))
1578 (cdr (assoc :colnames params
))
1579 (cdr (assoc :rownames params
)))))
1580 (raw-result (or (cdr (assoc :results params
)) ""))
1581 (result-params (append
1582 (split-string (if (stringp raw-result
)
1585 (cdr (assoc :result-params params
)))))
1587 (mapcar (lambda (var) (cons :var var
)) (car vars-and-names
))
1589 (cons :colname-names
(or (cdr (assoc :colname-names params
))
1590 (cadr vars-and-names
)))
1591 (cons :rowname-names
(or (cdr (assoc :rowname-names params
))
1592 (caddr vars-and-names
)))
1593 (cons :result-params result-params
)
1594 (cons :result-type
(cond ((member "output" result-params
) 'output
)
1595 ((member "value" result-params
) 'value
)
1597 (org-babel-get-header params
:var
'other
))))
1599 ;; row and column names
1600 (defun org-babel-del-hlines (table)
1601 "Remove all 'hlines from TABLE."
1602 (remq 'hline table
))
1604 (defun org-babel-get-colnames (table)
1605 "Return the column names of TABLE.
1606 Return a cons cell, the `car' of which contains the TABLE less
1607 colnames, and the `cdr' of which contains a list of the column
1609 (if (equal 'hline
(nth 1 table
))
1610 (cons (cddr table
) (car table
))
1611 (cons (cdr table
) (car table
))))
1613 (defun org-babel-get-rownames (table)
1614 "Return the row names of TABLE.
1615 Return a cons cell, the `car' of which contains the TABLE less
1616 rownames, and the `cdr' of which contains a list of the rownames.
1617 Note: this function removes any hlines in TABLE."
1618 (let* ((table (org-babel-del-hlines table
))
1619 (rownames (funcall (lambda ()
1625 (setq tp
(cdr tp
))))
1627 (cons table rownames
)))
1629 (defun org-babel-put-colnames (table colnames
)
1630 "Add COLNAMES to TABLE if they exist."
1631 (if colnames
(apply 'list colnames
'hline table
) table
))
1633 (defun org-babel-put-rownames (table rownames
)
1634 "Add ROWNAMES to TABLE if they exist."
1636 (mapcar (lambda (row)
1638 (cons (or (pop rownames
) "") row
)
1642 (defun org-babel-pick-name (names selector
)
1643 "Select one out of an alist of row or column names.
1644 SELECTOR can be either a list of names in which case those names
1645 will be returned directly, or an index into the list NAMES in
1646 which case the indexed names will be return."
1647 (if (listp selector
)
1650 (if (and selector
(symbolp selector
) (not (equal t selector
)))
1651 (cdr (assoc selector names
))
1652 (if (integerp selector
)
1653 (nth (- selector
1) names
)
1654 (cdr (car (last names
))))))))
1656 (defun org-babel-disassemble-tables (vars hlines colnames rownames
)
1657 "Parse tables for further processing.
1658 Process the variables in VARS according to the HLINES,
1659 ROWNAMES and COLNAMES header arguments. Return a list consisting
1660 of the vars, cnames and rnames."
1661 (let (cnames rnames
)
1665 (when (listp (cdr var
))
1666 (when (and (not (equal colnames
"no"))
1667 (or colnames
(and (equal (nth 1 (cdr var
)) 'hline
)
1668 (not (member 'hline
(cddr (cdr var
)))))))
1669 (let ((both (org-babel-get-colnames (cdr var
))))
1670 (setq cnames
(cons (cons (car var
) (cdr both
))
1672 (setq var
(cons (car var
) (car both
)))))
1673 (when (and rownames
(not (equal rownames
"no")))
1674 (let ((both (org-babel-get-rownames (cdr var
))))
1675 (setq rnames
(cons (cons (car var
) (cdr both
))
1677 (setq var
(cons (car var
) (car both
)))))
1678 (when (and hlines
(not (equal hlines
"yes")))
1679 (setq var
(cons (car var
) (org-babel-del-hlines (cdr var
))))))
1682 (reverse cnames
) (reverse rnames
))))
1684 (defun org-babel-reassemble-table (table colnames rownames
)
1685 "Add column and row names to a table.
1686 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1687 to the table for reinsertion to org-mode."
1689 (let ((table (if (and rownames
(= (length table
) (length rownames
)))
1690 (org-babel-put-rownames table rownames
) table
)))
1691 (if (and colnames
(listp (car table
)) (= (length (car table
))
1693 (org-babel-put-colnames table colnames
) table
))
1696 (defun org-babel-where-is-src-block-head ()
1697 "Find where the current source block begins.
1698 Return the point at the beginning of the current source block.
1699 Specifically at the beginning of the #+BEGIN_SRC line. Also set
1700 match-data relatively to `org-babel-src-block-regexp', which see.
1701 If the point is not on a source block then return nil."
1702 (let ((element (org-element-at-point)))
1703 (when (eq (org-element-type element
) 'src-block
)
1704 (let ((end (org-element-property :end element
)))
1705 (org-with-wide-buffer
1706 ;; Ensure point is not on a blank line after the block.
1708 (skip-chars-forward " \r\t\n" end
)
1709 (when (< (point) end
)
1710 (prog1 (goto-char (org-element-property :post-affiliated element
))
1711 (looking-at org-babel-src-block-regexp
))))))))
1714 (defun org-babel-goto-src-block-head ()
1715 "Go to the beginning of the current code block."
1717 (let ((head (org-babel-where-is-src-block-head)))
1718 (if head
(goto-char head
) (error "Not currently in a code block"))))
1721 (defun org-babel-goto-named-src-block (name)
1722 "Go to a named source-code block."
1724 (let ((completion-ignore-case t
)
1725 (case-fold-search t
)
1726 (under-point (thing-at-point 'line
)))
1727 (list (org-icompleting-read
1728 "source-block name: " (org-babel-src-block-names) nil t
1731 ((string-match (org-babel-noweb-wrap) under-point
)
1732 (let ((block-name (match-string 1 under-point
)))
1733 (string-match "[^(]*" block-name
)
1734 (match-string 0 block-name
)))
1736 ((string-match org-babel-lob-one-liner-regexp under-point
)
1737 (let ((source-info (car (org-babel-lob-get-info))))
1738 (if (string-match "^\\([^\\[]+?\\)\\(\\[.*\\]\\)?(" source-info
)
1739 (let ((source-name (match-string 1 source-info
)))
1742 ((string-match (concat "#\\+" org-babel-results-keyword
1743 "\\:\s+\\([^\\(]*\\)") under-point
)
1744 (match-string 1 under-point
))
1746 ((and (thing-at-point 'symbol
))
1747 (org-babel-find-named-block (thing-at-point 'symbol
))
1748 (thing-at-point 'symbol
))
1750 (let ((point (org-babel-find-named-block name
)))
1752 ;; taken from `org-open-at-point'
1753 (progn (org-mark-ring-push) (goto-char point
) (org-show-context))
1754 (message "source-code block '%s' not found in this buffer" name
))))
1756 (defun org-babel-find-named-block (name)
1757 "Find a named source-code block.
1758 Return the location of the source block identified by source
1759 NAME, or nil if no such block exists. Set match data according
1760 to `org-babel-named-src-block-regexp'."
1762 (goto-char (point-min))
1764 (org-next-block 1 nil
(org-babel-named-src-block-regexp-for-name name
)))))
1766 (defun org-babel-src-block-names (&optional file
)
1767 "Returns the names of source blocks in FILE or the current buffer."
1768 (when file
(find-file file
))
1770 (goto-char (point-min))
1771 (let ((re (org-babel-named-src-block-regexp-for-name))
1773 (while (ignore-errors (org-next-block 1 nil re
))
1774 (push (org-match-string-no-properties 9) names
))
1778 (defun org-babel-goto-named-result (name)
1779 "Go to a named result."
1781 (let ((completion-ignore-case t
))
1782 (list (org-icompleting-read "source-block name: "
1783 (org-babel-result-names) nil t
))))
1784 (let ((point (org-babel-find-named-result name
)))
1786 ;; taken from `org-open-at-point'
1787 (progn (goto-char point
) (org-show-context))
1788 (message "result '%s' not found in this buffer" name
))))
1790 (defun org-babel-find-named-result (name &optional point
)
1791 "Find a named result.
1792 Return the location of the result named NAME in the current
1793 buffer or nil if no such result exists."
1795 (let ((case-fold-search t
))
1796 (goto-char (or point
(point-min)))
1797 (catch 'is-a-code-block
1798 (when (re-search-forward
1799 (concat org-babel-result-regexp
1800 "[ \t]" (regexp-quote name
) "[ \t]*[\n\f\v\r]") nil t
)
1801 (when (and (string= "name" (downcase (match-string 1)))
1802 (or (beginning-of-line 1)
1803 (looking-at org-babel-src-block-regexp
)
1804 (looking-at org-babel-multi-line-header-regexp
)
1805 (looking-at org-babel-lob-one-liner-regexp
)))
1806 (throw 'is-a-code-block
(org-babel-find-named-result name
(point))))
1807 (beginning-of-line 0) (point))))))
1809 (defun org-babel-result-names (&optional file
)
1810 "Returns the names of results in FILE or the current buffer."
1812 (when file
(find-file file
)) (goto-char (point-min))
1813 (let ((case-fold-search t
) names
)
1814 (while (re-search-forward org-babel-result-w-name-regexp nil t
)
1815 (setq names
(cons (match-string 4) names
)))
1819 (defun org-babel-next-src-block (&optional arg
)
1820 "Jump to the next source block.
1821 With optional prefix argument ARG, jump forward ARG many source blocks."
1823 (org-next-block arg nil org-babel-src-block-regexp
))
1826 (defun org-babel-previous-src-block (&optional arg
)
1827 "Jump to the previous source block.
1828 With optional prefix argument ARG, jump backward ARG many source blocks."
1830 (org-previous-block arg org-babel-src-block-regexp
))
1832 (defvar org-babel-load-languages
)
1835 (defun org-babel-mark-block ()
1836 "Mark current src block."
1838 (let ((head (org-babel-where-is-src-block-head)))
1842 (looking-at org-babel-src-block-regexp
))
1843 (push-mark (match-end 5) nil t
)
1844 (goto-char (match-beginning 5)))))
1846 (defun org-babel-demarcate-block (&optional arg
)
1847 "Wrap or split the code in the region or on the point.
1848 When called from inside of a code block the current block is
1849 split. When called from outside of a code block a new code block
1850 is created. In both cases if the region is demarcated and if the
1851 region is not active then the point is demarcated."
1853 (let* ((info (org-babel-get-src-block-info 'light
))
1854 (start (org-babel-where-is-src-block-head))
1855 (block (and start
(match-string 0)))
1856 (headers (and start
(match-string 4)))
1857 (stars (concat (make-string (or (org-current-level) 1) ?
*) " "))
1858 (lower-case-p (and block
1859 (let (case-fold-search)
1860 (org-string-match-p "#\\+begin_src" block
)))))
1866 (let ((lang (nth 0 info
))
1867 (indent (make-string (nth 5 info
) ?
)))
1868 (when (string-match "^[[:space:]]*$"
1869 (buffer-substring (point-at-bol)
1871 (delete-region (point-at-bol) (point-at-eol)))
1873 (if (looking-at "^") "" "\n")
1874 indent
(funcall (if lower-case-p
'downcase
'upcase
) "#+end_src\n")
1875 (if arg stars indent
) "\n"
1876 indent
(funcall (if lower-case-p
'downcase
'upcase
) "#+begin_src ")
1878 (if (> (length headers
) 1)
1879 (concat " " headers
) headers
)
1880 (if (looking-at "[\n\r]")
1882 (concat "\n" (make-string (current-column) ?
)))))))
1883 (move-end-of-line 2))
1884 (sort (if (org-region-active-p) (list (mark) (point)) (list (point))) #'>))
1885 (let ((start (point))
1886 (lang (org-icompleting-read
1888 (mapcar #'symbol-name
1890 (append (mapcar #'car org-babel-load-languages
)
1891 (mapcar (lambda (el) (intern (car el
)))
1892 org-src-lang-modes
))))))
1893 (body (delete-and-extract-region
1894 (if (org-region-active-p) (mark) (point)) (point))))
1895 (insert (concat (if (looking-at "^") "" "\n")
1896 (if arg
(concat stars
"\n") "")
1897 (funcall (if lower-case-p
'downcase
'upcase
) "#+begin_src ")
1900 (if (or (= (length body
) 0)
1901 (string-match "[\r\n]$" body
)) "" "\n")
1902 (funcall (if lower-case-p
'downcase
'upcase
) "#+end_src\n")))
1903 (goto-char start
) (move-end-of-line 1)))))
1905 (defvar org-babel-lob-one-liner-regexp
)
1906 (defun org-babel-where-is-src-block-result (&optional insert info hash indent
)
1907 "Find where the current source block results begin.
1908 Return the point at the beginning of the result of the current
1909 source block. Specifically at the beginning of the results line.
1910 If no result exists for this block then create a results line
1911 following the source block."
1913 (let* ((case-fold-search t
)
1914 (on-lob-line (save-excursion
1915 (beginning-of-line 1)
1916 (looking-at org-babel-lob-one-liner-regexp
)))
1917 (inlinep (when (org-babel-get-inline-src-block-matches)
1919 (name (nth 4 (or info
(org-babel-get-src-block-info 'light
))))
1920 (head (unless on-lob-line
(org-babel-where-is-src-block-head)))
1922 (when head
(goto-char head
))
1923 (org-with-wide-buffer
1925 found
;; was there a result (before we potentially insert one)
1930 ;; - return t if it is found, else return nil
1931 ;; - if it does not need to be rebuilt, then don't set end
1932 ;; - if it does need to be rebuilt then do set end
1933 name
(setq beg
(org-babel-find-named-result name
))
1935 (when (and hash
(not (string= hash
(match-string 5))))
1936 (goto-char beg
) (setq end beg
) ;; beginning of result
1938 (delete-region end
(org-babel-result-end)) nil
)))
1941 ;; - return t if it is found, else return nil
1942 ;; - if it is found, and the hash doesn't match, delete and set end
1943 (or on-lob-line
(re-search-forward "^[ \t]*#\\+end_src" nil t
))
1944 (progn (end-of-line 1)
1945 (if (eobp) (insert "\n") (forward-char 1))
1949 (progn ;; unnamed results line already exists
1951 (while (re-search-forward "[^ \f\t\n\r\v]" nil t
)
1952 (beginning-of-line 1)
1954 ((looking-at (concat org-babel-result-regexp
"\n"))
1955 (throw 'non-comment t
))
1956 ((and (looking-at "^[ \t]*#")
1958 org-babel-lob-one-liner-regexp
)))
1960 (t (throw 'non-comment nil
))))))
1961 (let ((this-hash (match-string 5)))
1963 ;; must remove and rebuild if hash!=old-hash
1964 (if (and hash
(not (string= hash this-hash
)))
1966 (setq end
(point-at-bol))
1968 (delete-region end
(org-babel-result-end))
1970 (setq end nil
))))))))))
1971 (if (not (and insert end
)) found
1974 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1976 (when (wholenump indent
) (make-string indent ?
))
1977 "#+" org-babel-results-keyword
1979 (if org-babel-hash-show-time
1981 "["(format-time-string "<%Y-%m-%d %H:%M:%S>")" "hash
"]")
1982 (concat "["hash
"]")))
1984 (when name
(concat " " name
)) "\n"))
1985 (unless beg
(insert "\n") (backward-char))
1986 (beginning-of-line 0)
1987 (if hash
(org-babel-hide-hash))
1990 (defvar org-block-regexp
)
1991 (defun org-babel-read-result ()
1992 "Read the result at `point' into emacs-lisp."
1993 (let ((case-fold-search t
) result-string
)
1995 ((org-at-table-p) (org-babel-read-table))
1996 ((org-at-item-p) (org-babel-read-list))
1997 ((looking-at org-bracket-link-regexp
) (org-babel-read-link))
1998 ((looking-at org-block-regexp
) (org-remove-indentation (match-string 4)))
1999 ((or (looking-at "^[ \t]*: ") (looking-at "^[ \t]*:$"))
2002 (mapconcat (lambda (line)
2003 (or (and (> (length line
) 1)
2004 (string-match "^[ \t]*: ?\\(.+\\)" line
)
2005 (match-string 1 line
))
2009 (point) (org-babel-result-end)) "[\r\n]+")
2011 (or (org-babel-number-p result-string
) result-string
))
2012 ((looking-at org-babel-result-regexp
)
2013 (save-excursion (forward-line 1) (org-babel-read-result))))))
2015 (defun org-babel-read-table ()
2016 "Read the table at `point' into emacs-lisp."
2017 (mapcar (lambda (row)
2018 (if (and (symbolp row
) (equal row
'hline
)) row
2019 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
)) row
)))
2020 (org-table-to-lisp)))
2022 (defun org-babel-read-list ()
2023 "Read the list at `point' into emacs-lisp."
2024 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
))
2025 (mapcar #'cadr
(cdr (org-list-parse-list)))))
2027 (defvar org-link-types-re
)
2028 (defun org-babel-read-link ()
2029 "Read the link at `point' into emacs-lisp.
2030 If the path of the link is a file path it is expanded using
2031 `expand-file-name'."
2032 (let* ((case-fold-search t
)
2033 (raw (and (looking-at org-bracket-link-regexp
)
2034 (org-no-properties (match-string 1))))
2035 (type (and (string-match org-link-types-re raw
)
2036 (match-string 1 raw
))))
2038 ((not type
) (expand-file-name raw
))
2039 ((string= type
"file")
2040 (and (string-match "file\\(.*\\):\\(.+\\)" raw
)
2041 (expand-file-name (match-string 2 raw
))))
2044 (defun org-babel-format-result (result &optional sep
)
2045 "Format RESULT for writing to file."
2046 (let ((echo-res (lambda (r) (if (stringp r
) r
(format "%S" r
)))))
2050 result
(list :sep
(or sep
"\t") :fmt echo-res
))
2052 (funcall echo-res result
))))
2054 (defun org-babel-insert-result
2055 (result &optional result-params info hash indent lang
)
2056 "Insert RESULT into the current buffer.
2058 By default RESULT is inserted after the end of the current source
2059 block. The RESULT of an inline source block usually will be
2060 wrapped inside a `results' macro and placed on the same line as
2061 the inline source block. The macro is stripped upon export.
2062 Multiline and non-scalar RESULTS from inline source blocks are
2063 not allowed. With optional argument RESULT-PARAMS controls
2064 insertion of results in the Org mode file. RESULT-PARAMS can
2065 take the following values:
2067 replace - (default option) insert results after the source block
2068 or inline source block replacing any previously
2071 silent -- no results are inserted into the Org-mode buffer but
2072 the results are echoed to the minibuffer and are
2073 ingested by Emacs (a potentially time consuming
2076 file ---- the results are interpreted as a file path, and are
2077 inserted into the buffer using the Org-mode file syntax.
2079 list ---- the results are interpreted as an Org-mode list.
2081 raw ----- results are added directly to the Org-mode file. This
2082 is a good option if you code block will output org-mode
2085 drawer -- results are added directly to the Org-mode file as with
2086 \"raw\", but are wrapped in a RESULTS drawer or results
2087 macro, allowing them to later be replaced or removed
2090 org ----- results are added inside of a \"src_org{}\" or \"#+BEGIN_SRC
2091 org\" block depending on whether the current source block is
2092 inline or not. They are not comma-escaped when inserted,
2093 but Org syntax here will be discarded when exporting the
2096 html ---- results are added inside of a #+BEGIN_HTML block or
2097 html export snippet depending on whether the current
2098 source block is inline or not. This is a good option
2099 if your code block will output html formatted text.
2101 latex --- results are added inside of a #+BEGIN_LATEX block or
2102 latex export snippet depending on whether the current
2103 source block is inline or not. This is a good option
2104 if your code block will output latex formatted text.
2106 code ---- the results are extracted in the syntax of the source
2107 code of the language being evaluated and are added
2108 inside of a source block with the source-code language
2109 set appropriately. Also, source block inlining is
2110 preserved in this case. Note this relies on the
2111 optional LANG argument.
2113 list ---- the results are rendered as a list. This option not
2114 allowed for inline src blocks.
2116 table --- the results are rendered as a table. This option not
2117 allowed for inline src blocks.
2119 INFO may provide the values of these header arguments (in the
2120 `header-arguments-alist' see the docstring for
2121 `org-babel-get-src-block-info'):
2123 :file --- the name of the file to which output should be written.
2125 :wrap --- the effect is similar to `latex' in RESULT-PARAMS but
2126 using the argument supplied to specify the export block
2129 (if (stringp result
)
2131 (setq result
(org-no-properties result
))
2132 (when (member "file" result-params
)
2133 (setq result
(org-babel-result-to-file
2134 result
(when (assoc :file-desc
(nth 2 info
))
2135 (or (cdr (assoc :file-desc
(nth 2 info
)))
2137 (unless (listp result
) (setq result
(format "%S" result
))))
2138 (if (and result-params
(member "silent" result-params
))
2140 (message (replace-regexp-in-string "%" "%%" (format "%S" result
)))
2145 (when (or (org-babel-get-inline-src-block-matches)
2146 (org-babel-get-lob-one-liner-matches))
2147 (goto-char (match-end 0))
2148 (org-babel-remove-inline-result)
2153 (org-babel-where-is-src-block-result t info hash indent
)))
2157 (and (member "table" result-params
) "`:results table'")
2158 (and (listp result
) "list result")
2159 (and (org-string-match-p "\n." result
) "multiline result")
2160 (and (member "list" result-params
) "`:results list'"))))
2162 (cdr (assoc :results_switches
(nth 2 info
))))
2163 (visible-beg (copy-marker (point-min)))
2164 (visible-end (copy-marker (point-max)))
2165 ;; When results exist outside of the current visible
2166 ;; region of the buffer, be sure to widen buffer to
2168 (outside-scope-p (and existing-result
2169 (or (> visible-beg existing-result
)
2170 (<= visible-end existing-result
))))
2172 (when (and (stringp result
) ; ensure results end in a newline
2174 (> (length result
) 0)
2175 (not (or (string-equal (substring result -
1) "\n")
2176 (string-equal (substring result -
1) "\r"))))
2177 (setq result
(concat result
"\n")))
2180 (when outside-scope-p
(widen))
2181 (if (not existing-result
)
2182 (setq beg
(or inlinep
(point)))
2183 (goto-char existing-result
)
2185 (re-search-forward "#" nil t
)
2186 (setq indent
(- (current-column) 1)))
2190 ((member "replace" result-params
)
2191 (delete-region (point) (org-babel-result-end)))
2192 ((member "append" result-params
)
2193 (goto-char (org-babel-result-end)) (setq beg
(point-marker)))
2194 ((member "prepend" result-params
)))) ; already there
2195 (setq results-switches
2196 (if results-switches
(concat " " results-switches
) ""))
2197 (let ((wrap (lambda (start finish
&optional no-escape no-newlines
2198 inline-start inline-finish
)
2200 (setq start inline-start
)
2201 (setq finish inline-finish
)
2202 (setq no-newlines t
))
2204 (insert (concat finish
(unless no-newlines
"\n")))
2206 (insert (concat start
(unless no-newlines
"\n")))
2208 (org-escape-code-in-region (min (point) end
) end
))
2210 (unless no-newlines
(goto-char (point-at-eol)))
2211 (setq end
(point-marker))))
2214 ;; Non-nil when result R can be turned into
2217 (null (cdr (last r
)))
2219 (lambda (e) (or (atom e
) (null (cdr (last e
)))))
2221 ;; insert results based on type
2223 ;; Do nothing for an empty result.
2225 ;; Illegal inline result or params.
2227 (error "Inline error: %s cannot be used" bad-inline-p
))
2228 ;; insert a list if preferred
2229 ((member "list" result-params
)
2232 (org-list-to-generic
2235 (lambda (el) (list nil
(if (stringp el
) el
(format "%S" el
))))
2236 (if (listp result
) result
(split-string result
"\n" t
))))
2237 '(:splicep nil
:istart
"- " :iend
"\n")))
2239 ;; Try hard to print RESULT as a table. Give up if
2240 ;; it contains an improper list.
2241 ((funcall tabulablep result
)
2243 (insert (concat (orgtbl-to-orgtbl
2246 (or (eq e
'hline
) (listp e
)))
2253 (when (org-at-table-p) (org-table-align))
2254 (goto-char (org-table-end)))
2255 ;; Print verbatim a list that cannot be turned into
2257 ((listp result
) (insert (format "%s\n" result
)))
2258 ((member "file" result-params
)
2261 (setq result
(org-macro-escape-arguments result
)))
2264 (not (member "raw" result-params
)))
2266 (insert (org-macro-escape-arguments
2267 (org-babel-chomp result
"\n"))))
2268 (t (goto-char beg
) (insert result
)))
2269 (setq end
(point-marker))
2270 ;; possibly wrap result
2272 (bad-inline-p) ; Do nothing.
2273 ((assoc :wrap
(nth 2 info
))
2274 (let ((name (or (cdr (assoc :wrap
(nth 2 info
))) "RESULTS")))
2275 (funcall wrap
(concat "#+BEGIN_" name
)
2276 (concat "#+END_" (car (org-split-string name
)))
2277 nil nil
(concat "{{{results(@@" name
":") "@@)}}}")))
2278 ((member "html" result-params
)
2279 (funcall wrap
"#+BEGIN_HTML" "#+END_HTML" nil nil
2280 "{{{results(@@html:" "@@)}}}"))
2281 ((member "latex" result-params
)
2282 (funcall wrap
"#+BEGIN_LaTeX" "#+END_LaTeX" nil nil
2283 "{{{results(@@latex:" "@@)}}}"))
2284 ((member "org" result-params
)
2285 (goto-char beg
) (if (org-at-table-p) (org-cycle))
2286 (funcall wrap
"#+BEGIN_SRC org" "#+END_SRC" nil nil
2287 "{{{results(src_org{" "})}}}"))
2288 ((member "code" result-params
)
2289 (let ((lang (or lang
"none")))
2290 (funcall wrap
(format "#+BEGIN_SRC %s%s" lang results-switches
)
2292 (format "{{{results(src_%s[%s]{" lang results-switches
)
2294 ((member "raw" result-params
)
2295 (goto-char beg
) (if (org-at-table-p) (org-cycle)))
2296 ((or (member "drawer" result-params
)
2297 ;; Stay backward compatible with <7.9.2
2298 (member "wrap" result-params
))
2299 (goto-char beg
) (if (org-at-table-p) (org-cycle))
2300 (funcall wrap
":RESULTS:" ":END:" 'no-escape nil
2301 "{{{results(" ")}}}"))
2302 ((and inlinep
(member "file" result-params
))
2303 (funcall wrap nil nil nil nil
"{{{results(" ")}}}"))
2304 ((and (not (funcall tabulablep result
))
2305 (not (member "file" result-params
)))
2306 (let ((org-babel-inline-result-wrap
2307 ;; Hard code {{{results(...)}}} on top of customization.
2308 (format "{{{results(%s)}}}" org-babel-inline-result-wrap
)))
2309 (org-babel-examplify-region beg end results-switches
)
2310 (setq end
(point))))))
2311 ;; possibly indent the results to match the #+results line
2312 (when (and (not inlinep
) (numberp indent
) indent
(> indent
0)
2313 ;; in this case `table-align' does the work for us
2314 (not (and (listp result
)
2315 (member "append" result-params
))))
2316 (indent-rigidly beg end indent
))
2318 (if (member "value" result-params
)
2319 (message "Code block returned no value.")
2320 (message "Code block produced no output."))
2321 (message "Code block evaluation complete.")))
2322 (when outside-scope-p
(narrow-to-region visible-beg visible-end
))
2323 (set-marker visible-beg nil
)
2324 (set-marker visible-end nil
))))))
2326 (defun org-babel-remove-result (&optional info keep-keyword
)
2327 "Remove the result of the current source block."
2329 (let ((location (org-babel-where-is-src-block-result nil info
)))
2332 (goto-char location
)
2333 (when (looking-at (concat org-babel-result-regexp
".*$"))
2335 (if keep-keyword
(1+ (match-end 0)) (1- (match-beginning 0)))
2336 (progn (forward-line 1) (org-babel-result-end))))))))
2338 (defun org-babel-remove-inline-result ()
2339 "Remove the result of the current inline-src-block or babel call.
2340 The result must be wrapped in a `results' macro to be removed.
2341 Leading whitespace is trimmed."
2343 (let* ((el (org-element-context))
2344 (post-blank (org-element-property :post-blank el
)))
2345 (when (memq (org-element-type el
) '(inline-src-block inline-babel-call
))
2346 (org-with-wide-buffer
2347 (goto-char (org-element-property :end el
))
2348 (let ((el (org-element-context)))
2349 (when (and (eq (org-element-type el
) 'macro
)
2350 (string= (org-element-property :key el
) "results"))
2351 (delete-region ; And leading whitespace.
2352 (- (org-element-property :begin el
) post-blank
)
2353 (- (org-element-property :end el
)
2354 (org-element-property :post-blank el
)))))))))
2356 (defun org-babel-remove-result-one-or-many (x)
2357 "Remove the result of the current source block.
2358 If called with a prefix argument, remove all result blocks
2362 (org-babel-map-src-blocks nil
(org-babel-remove-result))
2363 (org-babel-remove-result)))
2365 (defun org-babel-result-end ()
2366 "Return the point at the end of the current set of results."
2369 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
2370 ((org-at-item-p) (let* ((struct (org-list-struct))
2371 (prvs (org-list-prevs-alist struct
)))
2372 (org-list-get-list-end (point-at-bol) struct prvs
)))
2373 ((let ((case-fold-search t
)) (looking-at "^\\([ \t]*\\):results:"))
2374 (progn (re-search-forward (concat "^" (match-string 1) ":END:"))
2375 (forward-char 1) (point)))
2377 (let ((case-fold-search t
))
2378 (if (looking-at (concat "[ \t]*#\\+begin_\\([^ \t\n\r]+\\)"))
2379 (progn (re-search-forward (concat "[ \t]*#\\+end_" (match-string 1))
2382 (while (looking-at "[ \t]*\\(: \\|:$\\|\\[\\[\\)")
2386 (defun org-babel-result-to-file (result &optional description
)
2387 "Convert RESULT into an `org-mode' link with optional DESCRIPTION.
2388 If the `default-directory' is different from the containing
2389 file's directory then expand relative links."
2390 (when (stringp result
)
2391 (format "[[file:%s]%s]"
2392 (if (and default-directory
2394 (not (string= (expand-file-name default-directory
)
2396 (file-name-directory buffer-file-name
)))))
2397 (expand-file-name result default-directory
)
2399 (if description
(concat "[" description
"]") ""))))
2401 (defvar org-babel-capitalize-example-region-markers nil
2402 "Make true to capitalize begin/end example markers inserted by code blocks.")
2404 (define-obsolete-function-alias
2405 'org-babel-examplize-region
2406 'org-babel-examplify-region
"25.1")
2408 (defun org-babel-examplify-region (beg end
&optional results-switches
)
2409 "Comment out region using the inline '==' or ': ' org example quote."
2411 (let ((chars-between (lambda (b e
)
2412 (not (string-match "^[\\s]*$"
2413 (buffer-substring b e
)))))
2414 (maybe-cap (lambda (str) (if org-babel-capitalize-example-region-markers
2416 (beg-bol (save-excursion (goto-char beg
) (point-at-bol)))
2417 (end-bol (save-excursion (goto-char end
) (point-at-bol)))
2418 (end-eol (save-excursion (goto-char end
) (point-at-eol))))
2419 (if (and (not (= end end-bol
))
2420 (or (funcall chars-between beg-bol beg
)
2421 (funcall chars-between end end-eol
)))
2424 (insert (format org-babel-inline-result-wrap
2425 (prog1 (buffer-substring beg end
)
2426 (delete-region beg end
)))))
2427 (let ((size (count-lines beg end
)))
2429 (cond ((= size
0)) ; do nothing for an empty result
2430 ((< size org-babel-min-lines-for-block-output
)
2433 (beginning-of-line 1) (insert ": ") (forward-line 1)))
2436 (insert (if results-switches
2438 (funcall maybe-cap
"#+begin_example")
2440 (funcall maybe-cap
"#+begin_example\n")))
2441 (if (markerp end
) (goto-char end
) (forward-char (- end beg
)))
2442 (insert (funcall maybe-cap
"#+end_example\n")))))))))
2444 (defun org-babel-update-block-body (new-body)
2445 "Update the body of the current code block to NEW-BODY."
2446 (if (not (org-babel-where-is-src-block-head))
2447 (error "Not in a source block")
2449 (replace-match (concat (org-babel-trim (org-remove-indentation new-body
))
2451 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
2453 (defun org-babel-merge-params (&rest plists
)
2454 "Combine all parameter association lists in PLISTS.
2455 Later elements of PLISTS override the values of previous elements.
2456 This takes into account some special considerations for certain
2457 parameters when merging lists."
2458 (let* ((results-exclusive-groups
2459 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2460 (cdr (assoc 'results org-babel-common-header-args-w-values
))))
2461 (exports-exclusive-groups
2462 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2463 (cdr (assoc 'exports org-babel-common-header-args-w-values
))))
2465 (e-merge (lambda (exclusive-groups &rest result-params
)
2466 ;; maintain exclusivity of mutually exclusive parameters
2468 (mapc (lambda (new-params)
2469 (mapc (lambda (new-param)
2470 (mapc (lambda (exclusive-group)
2471 (when (member new-param exclusive-group
)
2472 (mapcar (lambda (excluded-param)
2479 (setq output
(org-uniquify
2480 (cons new-param output
))))
2484 params results exports tangle noweb cache vars shebang comments padline
2493 (let ((name (if (listp (cdr pair
))
2495 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
2497 (intern (match-string 1 (cdr pair
)))))))
2501 (if (member name
(mapcar #'car vars
))
2503 (push name clearnames
)
2507 (unless (equal (car p
) name
) p
))
2510 (list (cons name pair
))))
2511 ;; if no name is given and we already have named variables
2512 ;; then assign to named variables in order
2513 (if (and vars
(nth variable-index vars
))
2514 (let ((name (car (nth variable-index vars
))))
2515 (push name clearnames
) ; clear out colnames
2518 (prog1 (setf (cddr (nth variable-index vars
))
2519 (concat (symbol-name name
) "=" (cdr pair
)))
2520 (incf variable-index
)))
2521 (error "Variable \"%s\" must be assigned a default value"
2524 (setq results
(funcall e-merge results-exclusive-groups
2527 (let ((r (cdr pair
)))
2528 (if (stringp r
) r
(eval r
)))))))
2531 (setq results
(funcall e-merge results-exclusive-groups
2533 (unless (or (member "both" exports
)
2534 (member "none" exports
)
2535 (member "code" exports
))
2536 (setq exports
(funcall e-merge exports-exclusive-groups
2537 exports
'("results"))))
2538 (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))
2541 (setq results
(funcall e-merge results-exclusive-groups
2543 (unless (or (member "both" exports
)
2544 (member "none" exports
)
2545 (member "code" exports
))
2546 (setq exports
(funcall e-merge exports-exclusive-groups
2547 exports
'("results"))))
2548 (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))
2550 (setq exports
(funcall e-merge exports-exclusive-groups
2551 exports
(split-string (cdr pair
)))))
2552 (:tangle
;; take the latest -- always overwrite
2553 (setq tangle
(or (list (cdr pair
)) tangle
)))
2555 (setq noweb
(funcall e-merge
2556 '(("yes" "no" "tangle" "no-export"
2557 "strip-export" "eval"))
2559 (split-string (or (cdr pair
) "")))))
2561 (setq cache
(funcall e-merge
'(("yes" "no")) cache
2562 (split-string (or (cdr pair
) "")))))
2564 (setq padline
(funcall e-merge
'(("yes" "no")) padline
2565 (split-string (or (cdr pair
) "")))))
2566 (:shebang
;; take the latest -- always overwrite
2567 (setq shebang
(or (list (cdr pair
)) shebang
)))
2569 (setq comments
(funcall e-merge
'(("yes" "no")) comments
2570 (split-string (or (cdr pair
) "")))))
2571 (t ;; replace: this covers e.g. :session
2572 (setq params
(cons pair
(assq-delete-all (car pair
) params
))))))
2575 (setq vars
(reverse vars
))
2576 (while vars
(setq params
(cons (cons :var
(cddr (pop vars
))) params
)))
2577 ;; clear out col-names and row-names for replaced variables
2582 (when (assoc param params
)
2583 (setf (cdr (assoc param params
))
2584 (org-remove-if (lambda (pair) (equal (car pair
) name
))
2585 (cdr (assoc param params
))))
2586 (setf params
(org-remove-if (lambda (pair) (and (equal (car pair
) param
)
2589 (list :colname-names
:rowname-names
)))
2593 (let ((key (intern (concat ":" (symbol-name hd
))))
2595 (setf params
(cons (cons key
(mapconcat 'identity val
" ")) params
))))
2596 '(results exports tangle noweb padline cache shebang comments
))
2599 (defvar org-babel-use-quick-and-dirty-noweb-expansion nil
2600 "Set to true to use regular expressions to expand noweb references.
2601 This results in much faster noweb reference expansion but does
2602 not properly allow code blocks to inherit the \":noweb-ref\"
2603 header argument from buffer or subtree wide properties.")
2605 (defun org-babel-noweb-p (params context
)
2606 "Check if PARAMS require expansion in CONTEXT.
2607 CONTEXT may be one of :tangle, :export or :eval."
2609 (intersect (lambda (as bs
)
2611 (if (member (car as
) bs
)
2613 (funcall intersect
(cdr as
) bs
))))))
2614 (funcall intersect
(case context
2615 (:tangle
'("yes" "tangle" "no-export" "strip-export"))
2616 (:eval
'("yes" "no-export" "strip-export" "eval"))
2618 (split-string (or (cdr (assoc :noweb params
)) "")))))
2620 (defun org-babel-expand-noweb-references (&optional info parent-buffer
)
2621 "Expand Noweb references in the body of the current source code block.
2623 For example the following reference would be replaced with the
2624 body of the source-code block named 'example-block'.
2628 Note that any text preceding the <<foo>> construct on a line will
2629 be interposed between the lines of the replacement text. So for
2630 example if <<foo>> is placed behind a comment, then the entire
2631 replacement text will also be commented.
2633 This function must be called from inside of the buffer containing
2634 the source-code block which holds BODY.
2636 In addition the following syntax can be used to insert the
2637 results of evaluating the source-code block named 'example-block'.
2641 Any optional arguments can be passed to example-block by placing
2642 the arguments inside the parenthesis following the convention
2643 defined by `org-babel-lob'. For example
2645 <<example-block(a=9)>>
2647 would set the value of argument \"a\" equal to \"9\". Note that
2648 these arguments are not evaluated in the current source-code
2649 block but are passed literally to the \"example-block\"."
2650 (let* ((parent-buffer (or parent-buffer
(current-buffer)))
2651 (info (or info
(org-babel-get-src-block-info 'light
)))
2654 (ob-nww-start org-babel-noweb-wrap-start
)
2655 (ob-nww-end org-babel-noweb-wrap-end
)
2656 (comment (string= "noweb" (cdr (assoc :comments
(nth 2 info
)))))
2657 (rx-prefix (concat "\\(" org-babel-src-name-regexp
"\\|"
2658 ":noweb-ref[ \t]+" "\\)"))
2660 (nb-add (lambda (text) (setq new-body
(concat new-body text
))))
2661 (c-wrap (lambda (text)
2663 (funcall (intern (concat lang
"-mode")))
2664 (comment-region (point) (progn (insert text
) (point)))
2665 (org-babel-trim (buffer-string)))))
2666 index source-name evaluate prefix
)
2668 (org-set-local 'org-babel-noweb-wrap-start ob-nww-start
)
2669 (org-set-local 'org-babel-noweb-wrap-end ob-nww-end
)
2670 (insert body
) (goto-char (point-min))
2671 (setq index
(point))
2672 (while (and (re-search-forward (org-babel-noweb-wrap) nil t
))
2673 (save-match-data (setf source-name
(match-string 1)))
2674 (save-match-data (setq evaluate
(string-match "\(.*\)" source-name
)))
2677 (buffer-substring (match-beginning 0)
2679 (beginning-of-line 1) (point)))))
2680 ;; add interval to new-body (removing noweb reference)
2681 (goto-char (match-beginning 0))
2682 (funcall nb-add
(buffer-substring index
(point)))
2683 (goto-char (match-end 0))
2684 (setq index
(point))
2687 (with-current-buffer parent-buffer
2690 (mapconcat ;; Interpose PREFIX between every line.
2694 (let ((raw (org-babel-ref-resolve source-name
)))
2695 (if (stringp raw
) raw
(format "%S" raw
)))
2697 ;; Retrieve from the library of babel.
2698 (nth 2 (assoc (intern source-name
)
2699 org-babel-library-of-babel
))
2700 ;; Return the contents of headlines literally.
2702 (when (org-babel-ref-goto-headline-id source-name
)
2703 (org-babel-ref-headline-body)))
2704 ;; Find the expansion of reference in this buffer.
2705 (let ((rx (concat rx-prefix source-name
"[ \t\n]"))
2708 (goto-char (point-min))
2709 (if org-babel-use-quick-and-dirty-noweb-expansion
2710 (while (re-search-forward rx nil t
)
2711 (let* ((i (org-babel-get-src-block-info 'light
))
2712 (body (org-babel-expand-noweb-references i
))
2713 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2716 (let ((cs (org-babel-tangle-comment-links i
)))
2717 (concat (funcall c-wrap
(car cs
)) "\n"
2719 (funcall c-wrap
(cadr cs
))))
2721 (setq expansion
(cons sep
(cons full expansion
)))))
2722 (org-babel-map-src-blocks nil
2723 (let ((i (org-babel-get-src-block-info 'light
)))
2724 (when (equal (or (cdr (assoc :noweb-ref
(nth 2 i
)))
2727 (let* ((body (org-babel-expand-noweb-references i
))
2728 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2731 (let ((cs (org-babel-tangle-comment-links i
)))
2732 (concat (funcall c-wrap
(car cs
)) "\n"
2734 (funcall c-wrap
(cadr cs
))))
2737 (cons sep
(cons full expansion
)))))))))
2739 (mapconcat #'identity
(nreverse (cdr expansion
)) "")))
2740 ;; Possibly raise an error if named block doesn't exist.
2741 (if (or org-babel-noweb-error-all-langs
2742 (member lang org-babel-noweb-error-langs
))
2744 (org-babel-noweb-wrap source-name
)
2745 "could not be resolved (see "
2746 "`org-babel-noweb-error-langs')"))
2748 "[\n\r]") (concat "\n" prefix
))))))
2749 (funcall nb-add
(buffer-substring index
(point-max))))
2752 (defun org-babel--script-escape-inner (str)
2753 (let (in-single in-double backslash out
)
2760 (setq backslash nil
)
2762 ((and in-single
(eq ch ?
'))
2763 ;; Escaped single quote inside single quoted string:
2764 ;; emit just a single quote, since we've changed the
2765 ;; outer quotes to double.
2768 ;; Escaped double quote
2770 ;; This should be interpreted as backslash+quote,
2771 ;; not an escape. Emit a three backslashes
2772 ;; followed by a quote (because one layer of
2773 ;; quoting will be stripped by `org-babel-read').
2774 (append (list ch ?
\\ ?
\\ ?
\\) out
)
2775 ;; Otherwise we are in a double-quoted string. Emit
2776 ;; a single escaped quote
2777 (append (list ch ?
\\) out
)))
2779 ;; Escaped backslash: emit a single escaped backslash
2780 (append (list ?
\\ ?
\\) out
))
2781 ;; Other: emit a quoted backslash followed by whatever
2782 ;; the character was (because one layer of quoting will
2783 ;; be stripped by `org-babel-read').
2784 (t (append (list ch ?
\\ ?
\\) out
))))
2786 (?\
[ (if (or in-double in-single
)
2789 (?\
] (if (or in-double in-single
)
2792 (?\
{ (if (or in-double in-single
)
2795 (?\
} (if (or in-double in-single
)
2798 (?
, (if (or in-double in-single
)
2799 (cons ?
, out
) (cons ?\s out
)))
2802 (setq in-single
(not in-single
)) (cons ?
\" out
)))
2804 (append (list ?
\" ?
\\) out
)
2805 (setq in-double
(not in-double
)) (cons ?
\" out
)))
2806 (?
\\ (unless (or in-single in-double
)
2807 (error "Can't handle backslash outside string in `org-babel-script-escape'"))
2810 (t (cons ch out
))))))
2811 (string-to-list str
))
2812 (when (or in-single in-double
)
2813 (error "Unterminated string in `org-babel-script-escape'"))
2814 (apply #'string
(reverse out
))))
2816 (defun org-babel-script-escape (str &optional force
)
2817 "Safely convert tables into elisp lists."
2818 (unless (stringp str
)
2819 (error "`org-babel-script-escape' expects a string"))
2822 ((and (> (length str
) 2)
2823 (or (and (string-equal "[" (substring str
0 1))
2824 (string-equal "]" (substring str -
1)))
2825 (and (string-equal "{" (substring str
0 1))
2826 (string-equal "}" (substring str -
1)))
2827 (and (string-equal "(" (substring str
0 1))
2828 (string-equal ")" (substring str -
1)))))
2830 (concat "'" (org-babel--script-escape-inner str
)))
2832 (and (> (length str
) 2)
2833 (or (and (string-equal "'" (substring str
0 1))
2834 (string-equal "'" (substring str -
1)))
2835 ;; We need to pass double-quoted strings
2836 ;; through the backslash-twiddling bits, even
2837 ;; though we don't need to change their
2839 (and (string-equal "\"" (substring str
0 1))
2840 (string-equal "\"" (substring str -
1))))))
2841 (org-babel--script-escape-inner str
))
2843 (condition-case nil
(org-babel-read escaped
) (error escaped
))))
2845 (defun org-babel-read (cell &optional inhibit-lisp-eval
)
2846 "Convert the string value of CELL to a number if appropriate.
2847 Otherwise if CELL looks like lisp (meaning it starts with a
2848 \"(\", \"'\", \"`\" or a \"[\") then read and evaluate it as
2849 lisp, otherwise return it unmodified as a string. Optional
2850 argument INHIBIT-LISP-EVAL inhibits lisp evaluation for
2851 situations in which is it not appropriate."
2852 (if (and (stringp cell
) (not (equal cell
"")))
2853 (or (org-babel-number-p cell
)
2854 (if (and (not inhibit-lisp-eval
)
2855 (or (member (substring cell
0 1) '("(" "'" "`" "["))
2856 (string= cell
"*this*")))
2858 (if (string= (substring cell
0 1) "\"")
2860 (progn (set-text-properties 0 (length cell
) nil cell
) cell
))))
2863 (defun org-babel-number-p (string)
2864 "If STRING represents a number return its value."
2865 (if (and (string-match "[0-9]+" string
)
2866 (string-match "^-?[0-9]*\\.?[0-9]*$" string
)
2867 (= (length (substring string
(match-beginning 0)
2870 (string-to-number string
)))
2872 (defun org-babel-import-elisp-from-file (file-name &optional separator
)
2873 "Read the results located at FILE-NAME into an elisp table.
2874 If the table is trivial, then return it as a scalar."
2876 (save-window-excursion
2880 (org-table-import file-name separator
)
2881 (delete-file file-name
)
2882 (setq result
(mapcar (lambda (row)
2883 (mapcar #'org-babel-string-read row
))
2884 (org-table-to-lisp))))
2885 (error (message "Error reading results: %s" err
) nil
)))
2886 (if (null (cdr result
)) ;; if result is trivial vector, then scalarize it
2887 (if (consp (car result
))
2888 (if (null (cdr (car result
)))
2894 (defun org-babel-string-read (cell)
2895 "Strip nested \"s from around strings."
2896 (org-babel-read (or (and (stringp cell
)
2897 (string-match "\\\"\\(.+\\)\\\"" cell
)
2898 (match-string 1 cell
))
2901 (defun org-babel-chomp (string &optional regexp
)
2902 "Strip a trailing space or carriage return from STRING.
2903 The default regexp used is \"[ \\f\\t\\n\\r\\v]\" but another one
2904 can be specified as the REGEXP argument."
2905 (let ((regexp (or regexp
"[ \f\t\n\r\v]")))
2906 (while (and (> (length string
) 0)
2907 (string-match regexp
(substring string -
1)))
2908 (setq string
(substring string
0 -
1)))
2911 (defun org-babel-trim (string &optional regexp
)
2912 "Strip a leading and trailing space or carriage return from STRING.
2913 Like `org-babel-chomp', but run on both the first and last
2914 character of the string."
2917 (org-babel-chomp (org-reverse-string string
) regexp
)) regexp
))
2919 (defun org-babel-tramp-handle-call-process-region
2920 (start end program
&optional delete buffer display
&rest args
)
2921 "Use Tramp to handle `call-process-region'.
2922 Fixes a bug in `tramp-handle-call-process-region'."
2923 (if (and (featurep 'tramp
) (file-remote-p default-directory
))
2924 (let ((tmpfile (tramp-compat-make-temp-file "")))
2925 (write-region start end tmpfile
)
2926 (when delete
(delete-region start end
))
2928 ;; (apply 'call-process program tmpfile buffer display args)
2930 (apply 'process-file program tmpfile buffer display args
)
2931 (delete-file tmpfile
)))
2932 ;; org-babel-call-process-region-original is the original emacs
2933 ;; definition. It is in scope from the let binding in
2934 ;; org-babel-execute-src-block
2935 (apply org-babel-call-process-region-original
2936 start end program delete buffer display args
)))
2938 (defun org-babel-local-file-name (file)
2939 "Return the local name component of FILE."
2940 (or (file-remote-p file
'localname
) file
))
2942 (defun org-babel-process-file-name (name &optional no-quote-p
)
2943 "Prepare NAME to be used in an external process.
2944 If NAME specifies a remote location, the remote portion of the
2945 name is removed, since in that case the process will be executing
2946 remotely. The file name is then processed by `expand-file-name'.
2947 Unless second argument NO-QUOTE-P is non-nil, the file name is
2948 additionally processed by `shell-quote-argument'"
2949 (let ((f (org-babel-local-file-name (expand-file-name name
))))
2950 (if no-quote-p f
(shell-quote-argument f
))))
2952 (defvar org-babel-temporary-directory
)
2953 (unless (or noninteractive
(boundp 'org-babel-temporary-directory
))
2954 (defvar org-babel-temporary-directory
2955 (or (and (boundp 'org-babel-temporary-directory
)
2956 (file-exists-p org-babel-temporary-directory
)
2957 org-babel-temporary-directory
)
2958 (make-temp-file "babel-" t
))
2959 "Directory to hold temporary files created to execute code blocks.
2960 Used by `org-babel-temp-file'. This directory will be removed on
2963 (defcustom org-babel-remote-temporary-directory
"/tmp/"
2964 "Directory to hold temporary files on remote hosts."
2968 (defmacro org-babel-result-cond
(result-params scalar-form
&rest table-forms
)
2969 "Call the code to parse raw string results according to RESULT-PARAMS."
2971 (debug (form form
&rest form
)))
2972 (org-with-gensyms (params)
2973 `(let ((,params
,result-params
))
2974 (unless (member "none" ,params
)
2975 (if (or (member "scalar" ,params
)
2976 (member "verbatim" ,params
)
2977 (member "html" ,params
)
2978 (member "code" ,params
)
2979 (member "pp" ,params
)
2980 (member "file" ,params
)
2981 (and (or (member "output" ,params
)
2982 (member "raw" ,params
)
2983 (member "org" ,params
)
2984 (member "drawer" ,params
))
2985 (not (member "table" ,params
))))
2988 (def-edebug-spec org-babel-result-cond
(form form body
))
2990 (defun org-babel-temp-file (prefix &optional suffix
)
2991 "Create a temporary file in the `org-babel-temporary-directory'.
2992 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2993 value of `temporary-file-directory' temporarily set to the value
2994 of `org-babel-temporary-directory'."
2995 (if (file-remote-p default-directory
)
2997 (concat (file-remote-p default-directory
)
2999 prefix org-babel-remote-temporary-directory
))))
3000 (make-temp-file prefix nil suffix
))
3001 (let ((temporary-file-directory
3002 (or (and (boundp 'org-babel-temporary-directory
)
3003 (file-exists-p org-babel-temporary-directory
)
3004 org-babel-temporary-directory
)
3005 temporary-file-directory
)))
3006 (make-temp-file prefix nil suffix
))))
3008 (defun org-babel-remove-temporary-directory ()
3009 "Remove `org-babel-temporary-directory' on Emacs shutdown."
3010 (when (and (boundp 'org-babel-temporary-directory
)
3011 (file-exists-p org-babel-temporary-directory
))
3012 ;; taken from `delete-directory' in files.el
3015 (mapc (lambda (file)
3016 ;; This test is equivalent to
3017 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
3018 ;; but more efficient
3019 (if (eq t
(car (file-attributes file
)))
3020 (delete-directory file
)
3021 (delete-file file
)))
3022 ;; We do not want to delete "." and "..".
3023 (directory-files org-babel-temporary-directory
'full
3024 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
3025 (delete-directory org-babel-temporary-directory
))
3027 (message "Failed to remove temporary Org-babel directory %s"
3028 (if (boundp 'org-babel-temporary-directory
)
3029 org-babel-temporary-directory
3030 "[directory not defined]"))))))
3032 (add-hook 'kill-emacs-hook
'org-babel-remove-temporary-directory
)
3034 (defun org-babel-one-header-arg-safe-p (pair safe-list
)
3035 "Determine if the PAIR is a safe babel header arg according to SAFE-LIST.
3037 For the format of SAFE-LIST, see `org-babel-safe-header-args'."
3039 (keywordp (car pair
))
3040 (stringp (cdr pair
))
3042 (memq (car pair
) safe-list
)
3043 (let ((entry (assq (car pair
) safe-list
)))
3046 (cond ((functionp (cdr entry
))
3047 (funcall (cdr entry
) (cdr pair
)))
3048 ((listp (cdr entry
))
3049 (member (cdr pair
) (cdr entry
)))
3052 (defun org-babel-generate-file-param (src-name params
)
3053 "Calculate the filename for source block results.
3055 The directory is calculated from the :output-dir property of the
3056 source block; if not specified, use the current directory.
3058 If the source block has a #+NAME and the :file parameter does not
3059 contain any period characters, then the :file parameter is
3060 treated as an extension, and the output file name is the
3061 concatenation of the directory (as calculated above), the block
3062 name, a period, and the parameter value as a file extension.
3063 Otherwise, the :file parameter is treated as a full file name,
3064 and the output file name is the directory (as calculated above)
3065 plus the parameter value."
3066 (let* ((file-cons (assq :file params
))
3067 (file-ext-cons (assq :file-ext params
))
3068 (file-ext (cdr-safe file-ext-cons
))
3069 (dir (cdr-safe (assq :output-dir params
)))
3071 ;; create the output-dir if it does not exist
3073 (make-directory dir t
))
3075 ;; :file given; add :output-dir if given
3077 (setcdr file-cons
(concat (file-name-as-directory dir
) (cdr file-cons
))))
3078 ;; :file not given; compute from name and :file-ext if possible
3079 (when (and src-name file-ext
)
3081 (setq fname
(concat (file-name-as-directory (or dir
""))
3082 src-name
"." file-ext
))
3083 (setq fname
(concat src-name
"." file-ext
)))
3084 (setq params
(cons (cons :file fname
) params
))))
3087 ;;; Used by backends: R, Maxima, Octave.
3088 (defun org-babel-graphical-output-file (params)
3089 "File where a babel block should send graphical output, per PARAMS."
3090 (unless (assq :file params
)
3091 (if (assq :file-ext params
)
3092 (user-error ":file-ext given but no :file generated; did you forget to give a block a #+NAME?")
3093 (user-error "No :file header argument given; cannot create graphical result.")))
3094 (and (member "graphics" (cdr (assq :result-params params
)))
3095 (cdr (assq :file params
))))
3100 ;; generated-autoload-file: "org-loaddefs.el"
3103 ;;; ob-core.el ends here