1 ;;; ob-core.el --- working with code blocks in org-mode
3 ;; Copyright (C) 2009-2014 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
))
105 (defgroup org-babel nil
106 "Code block evaluation and management in `org-mode' documents."
110 (defcustom org-confirm-babel-evaluate t
111 "Confirm before evaluation.
112 Require confirmation before interactively evaluating code
113 blocks in Org-mode buffers. The default value of this variable
114 is t, meaning confirmation is required for any code block
115 evaluation. This variable can be set to nil to inhibit any
116 future confirmation requests. This variable can also be set to a
117 function which takes two arguments the language of the code block
118 and the body of the code block. Such a function should then
119 return a non-nil value if the user should be prompted for
120 execution or nil if no prompt is required.
122 Warning: Disabling confirmation may result in accidental
123 evaluation of potentially harmful code. It may be advisable
124 remove code block execution from C-c C-c as further protection
125 against accidental code block evaluation. The
126 `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
127 remove code block execution from the C-c C-c keybinding."
130 :type
'(choice boolean function
))
131 ;; don't allow this variable to be changed through file settings
132 (put 'org-confirm-babel-evaluate
'safe-local-variable
(lambda (x) (eq x t
)))
134 (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
135 "Remove code block evaluation from the C-c C-c key binding."
140 (defcustom org-babel-results-keyword
"RESULTS"
141 "Keyword used to name results generated by code blocks.
142 It should be \"RESULTS\". However any capitalization may be
146 :package-version
'(Org .
"8.0")
150 (eq (compare-strings "RESULTS" nil nil v nil nil t
)
153 (defcustom org-babel-noweb-wrap-start
"<<"
154 "String used to begin a noweb reference in a code block.
155 See also `org-babel-noweb-wrap-end'."
159 (defcustom org-babel-noweb-wrap-end
">>"
160 "String used to end a noweb reference in a code block.
161 See also `org-babel-noweb-wrap-start'."
165 (defcustom org-babel-inline-result-wrap
"=%s="
166 "Format string used to wrap inline results.
167 This string must include a \"%s\" which will be replaced by the results."
170 (put 'org-babel-inline-result-wrap
174 (string-match-p "%s" value
))))
176 (defun org-babel-noweb-wrap (&optional regexp
)
177 (concat org-babel-noweb-wrap-start
178 (or regexp
"\\([^ \t\n].+?[^ \t]\\|[^ \t\n]\\)")
179 org-babel-noweb-wrap-end
))
181 (defvar org-babel-src-name-regexp
182 "^[ \t]*#\\+name:[ \t]*"
183 "Regular expression used to match a source name line.")
185 (defvar org-babel-multi-line-header-regexp
186 "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
187 "Regular expression used to match multi-line header arguments.")
189 (defvar org-babel-src-name-w-name-regexp
190 (concat org-babel-src-name-regexp
192 org-babel-multi-line-header-regexp
194 "\\([^ ()\f\t\n\r\v]+\\)")
195 "Regular expression matching source name lines with a name.")
197 (defvar org-babel-src-block-regexp
199 ;; (1) indentation (2) lang
200 "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
202 "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
203 ;; (4) header arguments
206 "\\([^\000]*?\n\\)??[ \t]*#\\+end_src")
207 "Regexp used to identify code blocks.")
209 (defvar org-babel-inline-src-block-regexp
211 ;; (1) replacement target (2) lang
212 "\\(?:^\\|[^-[:alnum:]]\\)\\(src_\\([^ \f\t\n\r\v[]+\\)"
213 ;; (3,4) (unused, headers)
214 "\\(\\|\\[[ \t]*\\(.*?\\)\\]\\)"
216 "{\\([^\f\n\r\v]+?\\)}\\)")
217 "Regexp used to identify inline src-blocks.")
219 (defun org-babel-get-header (params key
&optional others
)
220 "Select only header argument of type KEY from a list.
221 Optional argument OTHERS indicates that only the header that do
222 not match KEY should be returned."
225 (lambda (p) (when (funcall (if others
#'not
#'identity
) (eq (car p
) key
)) p
))
228 (defun org-babel-get-inline-src-block-matches ()
229 "Set match data if within body of an inline source block.
230 Returns non-nil if match-data set"
231 (let ((src-at-0-p (save-excursion
232 (beginning-of-line 1)
233 (org-looking-at-p "src")))
234 (first-line-p (= (line-beginning-position) (point-min)))
236 (let ((search-for (cond ((and src-at-0-p first-line-p
"src_"))
237 (first-line-p "[[:punct:] \t]src_")
238 (t "[[:punct:] \f\t\n\r\v]src_")))
239 (lower-limit (if first-line-p
241 (- (point-at-bol) 1))))
243 (when (or (and src-at-0-p
(bobp))
244 (and (re-search-forward "}" (point-at-eol) t
)
245 (re-search-backward search-for lower-limit t
)
247 (when (looking-at org-babel-inline-src-block-regexp
)
250 (defvar org-babel-inline-lob-one-liner-regexp
)
251 (defun org-babel-get-lob-one-liner-matches ()
252 "Set match data if on line of an lob one liner.
253 Returns non-nil if match-data set"
255 (unless (= (point) (point-at-bol)) ;; move before inline block
256 (re-search-backward "[ \f\t\n\r\v]" nil t
))
257 (if (looking-at org-babel-inline-lob-one-liner-regexp
)
261 (defun org-babel-get-src-block-info (&optional light
)
262 "Get information on the current source block.
264 Optional argument LIGHT does not resolve remote variable
265 references; a process which could likely result in the execution
266 of other code blocks.
269 (language body header-arguments-alist switches name indent block-head)."
270 (let ((case-fold-search t
) head info name indent
)
272 (if (setq head
(org-babel-where-is-src-block-head))
275 (setq info
(org-babel-parse-src-block-match))
276 (setq indent
(car (last info
)))
277 (setq info
(butlast info
))
278 (while (and (forward-line -
1)
279 (looking-at org-babel-multi-line-header-regexp
))
281 (org-babel-merge-params
283 (org-babel-parse-header-arguments (match-string 1)))))
284 (when (looking-at org-babel-src-name-w-name-regexp
)
285 (setq name
(org-no-properties (match-string 3)))))
286 ;; inline source block
287 (when (org-babel-get-inline-src-block-matches)
288 (setq head
(match-beginning 0))
289 (setq info
(org-babel-parse-inline-src-block-match))))
290 ;; resolve variable references and add summary parameters
291 (when (and info
(not light
))
292 (setf (nth 2 info
) (org-babel-process-params (nth 2 info
))))
294 (setf (nth 2 info
) (org-babel-generate-file-param name
(nth 2 info
))))
295 (when info
(append info
(list name indent head
)))))
297 (defvar org-babel-exp-reference-buffer nil
298 "Buffer containing original contents of the exported buffer.
299 This is used by Babel to resolve references in source blocks.
300 Its value is dynamically bound during export.")
302 (defmacro org-babel-check-confirm-evaluate
(info &rest body
)
303 "Evaluate BODY with special execution confirmation variables set.
305 Specifically; NOEVAL will indicate if evaluation is allowed,
306 QUERY will indicate if a user query is required, CODE-BLOCK will
307 hold the language of the code block, and BLOCK-NAME will hold the
308 name of the code block."
309 (declare (indent defun
))
311 (lang block-body headers name head eval eval-no export eval-no-export
)
312 `(let* ((,lang
(nth 0 ,info
))
313 (,block-body
(nth 1 ,info
))
314 (,headers
(nth 2 ,info
))
315 (,name
(nth 4 ,info
))
316 (,head
(nth 6 ,info
))
317 (,eval
(or (cdr (assoc :eval
,headers
))
318 (when (assoc :noeval
,headers
) "no")))
319 (,eval-no
(or (equal ,eval
"no")
320 (equal ,eval
"never")))
321 (,export org-babel-exp-reference-buffer
)
322 (,eval-no-export
(and ,export
(or (equal ,eval
"no-export")
323 (equal ,eval
"never-export"))))
324 (noeval (or ,eval-no
,eval-no-export
))
325 (query (or (equal ,eval
"query")
326 (and ,export
(equal ,eval
"query-export"))
327 (if (functionp org-confirm-babel-evaluate
)
330 (funcall org-confirm-babel-evaluate
332 org-confirm-babel-evaluate
)))
333 (code-block (if ,info
(format " %s " ,lang
) " "))
334 (block-name (if ,name
(format " (%s) " ,name
) " ")))
337 (defsubst org-babel-check-evaluate
(info)
338 "Check if code block INFO should be evaluated.
339 Do not query the user."
340 (org-babel-check-confirm-evaluate info
342 (message (format "Evaluation of this%scode-block%sis disabled."
343 code-block block-name
))))))
345 ;; dynamically scoped for asynchronous export
346 (defvar org-babel-confirm-evaluate-answer-no
)
348 (defsubst org-babel-confirm-evaluate
(info)
349 "Confirm evaluation of the code block INFO.
351 If the variable `org-babel-confirm-evaluate-answer-no' is bound
352 to a non-nil value, auto-answer with \"no\".
354 This query can also be suppressed by setting the value of
355 `org-confirm-babel-evaluate' to nil, in which case all future
356 interactive code block evaluations will proceed without any
357 confirmation from the user.
359 Note disabling confirmation may result in accidental evaluation
360 of potentially harmful code."
361 (org-babel-check-confirm-evaluate info
364 (and (not (org-bound-and-true-p
365 org-babel-confirm-evaluate-answer-no
))
367 (format "Evaluate this%scode block%son your system? "
368 code-block block-name
)))
369 (message (format "Evaluation of this%scode-block%sis aborted."
370 code-block block-name
)))))))
373 (defun org-babel-execute-safely-maybe ()
374 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
375 (org-babel-execute-maybe)))
377 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-execute-safely-maybe
)
380 (defun org-babel-execute-maybe ()
382 (or (org-babel-execute-src-block-maybe)
383 (org-babel-lob-execute-maybe)))
385 (defmacro org-babel-when-in-src-block
(&rest body
)
386 "Execute BODY if point is in a source block and return t.
388 Otherwise do nothing and return nil."
389 `(if (or (org-babel-where-is-src-block-head)
390 (org-babel-get-inline-src-block-matches))
396 (defun org-babel-execute-src-block-maybe ()
397 "Conditionally execute a source block.
398 Detect if this is context for a Babel src-block and if so
399 then run `org-babel-execute-src-block'."
401 (org-babel-when-in-src-block
402 (org-babel-eval-wipe-error-buffer)
403 (org-babel-execute-src-block current-prefix-arg
)))
406 (defun org-babel-view-src-block-info ()
407 "Display information on the current source block.
408 This includes header arguments, language and name, and is largely
409 a window into the `org-babel-get-src-block-info' function."
411 (let ((info (org-babel-get-src-block-info 'light
))
412 (full (lambda (it) (> (length it
) 0)))
413 (printf (lambda (fmt &rest args
) (princ (apply #'format fmt args
)))))
415 (with-help-window (help-buffer)
416 (let ((name (nth 4 info
))
418 (switches (nth 3 info
))
419 (header-args (nth 2 info
)))
420 (when name
(funcall printf
"Name: %s\n" name
))
421 (when lang
(funcall printf
"Lang: %s\n" lang
))
422 (when (funcall full switches
) (funcall printf
"Switches: %s\n" switches
))
423 (funcall printf
"Header Arguments:\n")
424 (dolist (pair (sort header-args
425 (lambda (a b
) (string< (symbol-name (car a
))
426 (symbol-name (car b
))))))
427 (when (funcall full
(cdr pair
))
428 (funcall printf
"\t%S%s\t%s\n"
430 (if (> (length (format "%S" (car pair
))) 7) "" "\t")
434 (defun org-babel-expand-src-block-maybe ()
435 "Conditionally expand a source block.
436 Detect if this is context for a org-babel src-block and if so
437 then run `org-babel-expand-src-block'."
439 (org-babel-when-in-src-block
440 (org-babel-expand-src-block current-prefix-arg
)))
443 (defun org-babel-load-in-session-maybe ()
444 "Conditionally load a source block in a session.
445 Detect if this is context for a org-babel src-block and if so
446 then run `org-babel-load-in-session'."
448 (org-babel-when-in-src-block
449 (org-babel-load-in-session current-prefix-arg
)))
451 (add-hook 'org-metaup-hook
'org-babel-load-in-session-maybe
)
454 (defun org-babel-pop-to-session-maybe ()
455 "Conditionally pop to a session.
456 Detect if this is context for a org-babel src-block and if so
457 then run `org-babel-switch-to-session'."
459 (org-babel-when-in-src-block
460 (org-babel-switch-to-session current-prefix-arg
)))
462 (add-hook 'org-metadown-hook
'org-babel-pop-to-session-maybe
)
464 (defconst org-babel-common-header-args-w-values
465 '((cache .
((no yes
)))
467 (colnames .
((nil no yes
)))
468 (comments .
((no link yes org both noweb
)))
470 (eval .
((never query
)))
471 (exports .
((code results both none
)))
475 (hlines .
((no yes
)))
476 (mkdirp .
((yes no
)))
479 (noweb .
((yes no tangle no-export strip-export
)))
483 (padline .
((yes no
)))
486 (results .
((file list vector table scalar verbatim
)
487 (raw html latex org code pp drawer
)
488 (replace silent none append prepend
)
490 (rownames .
((no yes
)))
494 (tangle .
((tangle yes no
:any
)))
495 (tangle-mode .
((#o755
#o555
#o444
:any
)))
499 (defconst org-babel-header-arg-names
500 (mapcar #'car org-babel-common-header-args-w-values
)
501 "Common header arguments used by org-babel.
502 Note that individual languages may define their own language
503 specific header arguments as well.")
505 (defconst org-babel-safe-header-args
506 '(:cache
:colnames
:comments
:exports
:epilogue
:hlines
:noeval
507 :noweb
:noweb-ref
:noweb-sep
:padline
:prologue
:rownames
508 :sep
:session
:tangle
:wrap
509 (:eval .
("never" "query"))
510 (:results .
(lambda (str) (not (string-match "file" str
)))))
511 "A list of safe header arguments for babel source blocks.
513 The list can have entries of the following forms:
514 - :ARG -> :ARG is always a safe header arg
515 - (:ARG . (VAL1 VAL2 ...)) -> :ARG is safe as a header arg if it is
516 `equal' to one of the VALs.
517 - (:ARG . FN) -> :ARG is safe as a header arg if the function FN
518 returns non-nil. FN is passed one
519 argument, the value of the header arg
522 (defmacro org-babel-header-args-safe-fn
(safe-list)
523 "Return a function that determines whether a list of header args are safe.
526 \(put 'org-babel-default-header-args 'safe-local-variable
527 (org-babel-header-args-safe-p org-babel-safe-header-args)
529 This allows org-babel languages to extend the list of safe values for
530 their `org-babel-default-header-args:foo' variable.
532 For the format of SAFE-LIST, see `org-babel-safe-header-args'."
538 (org-babel-one-header-arg-safe-p pair
,safe-list
)))
541 (defvar org-babel-default-header-args
542 '((:session .
"none") (:results .
"replace") (:exports .
"code")
543 (:cache .
"no") (:noweb .
"no") (:hlines .
"no") (:tangle .
"no"))
544 "Default arguments to use when evaluating a source block.")
545 (put 'org-babel-default-header-args
'safe-local-variable
546 (org-babel-header-args-safe-fn org-babel-safe-header-args
))
548 (defvar org-babel-default-inline-header-args
549 '((:session .
"none") (:results .
"replace")
550 (:exports .
"results") (:hlines .
"yes"))
551 "Default arguments to use when evaluating an inline source block.")
552 (put 'org-babel-default-inline-header-args
'safe-local-variable
553 (org-babel-header-args-safe-fn org-babel-safe-header-args
))
555 (defvar org-babel-data-names
'("tblname" "results" "name"))
557 (defvar org-babel-result-regexp
558 (concat "^[ \t]*#\\+"
559 (regexp-opt org-babel-data-names t
)
561 ;; FIXME The string below is `org-ts-regexp'
562 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
563 " \\)?\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*")
564 "Regular expression used to match result lines.
565 If the results are associated with a hash key then the hash will
566 be saved in the second match data.")
568 (defvar org-babel-result-w-name-regexp
569 (concat org-babel-result-regexp
570 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
572 (defvar org-babel-min-lines-for-block-output
10
573 "The minimum number of lines for block output.
574 If number of lines of output is equal to or exceeds this
575 value, the output is placed in a #+begin_example...#+end_example
576 block. Otherwise the output is marked as literal by inserting
577 colons at the starts of the lines. This variable only takes
578 effect if the :results output option is in effect.")
580 (defvar org-babel-noweb-error-all-langs nil
581 "Raise errors when noweb references don't resolve.
582 Also see `org-babel-noweb-error-langs' to control noweb errors on
583 a language by language bases.")
585 (defvar org-babel-noweb-error-langs nil
586 "Languages for which Babel will raise literate programming errors.
587 List of languages for which errors should be raised when the
588 source code block satisfying a noweb reference in this language
589 can not be resolved. Also see `org-babel-noweb-error-all-langs'
590 to raise errors for all languages.")
592 (defvar org-babel-hash-show
4
593 "Number of initial characters to show of a hidden results hash.")
595 (defvar org-babel-hash-show-time nil
596 "Non-nil means show the time the code block was evaluated in the result hash.")
598 (defvar org-babel-after-execute-hook nil
599 "Hook for functions to be called after `org-babel-execute-src-block'")
601 (defun org-babel-named-src-block-regexp-for-name (name)
602 "This generates a regexp used to match a src block named NAME."
603 (concat org-babel-src-name-regexp
(regexp-quote name
)
604 "[ \t(]*[\r\n]\\(?:^[[:space:]]*#.*[\r\n]\\)*"
605 (substring org-babel-src-block-regexp
1)))
607 (defun org-babel-named-data-regexp-for-name (name)
608 "This generates a regexp used to match data named NAME."
609 (concat org-babel-result-regexp
(regexp-quote name
) "\\([ \t]\\|$\\)"))
612 (defvar call-process-region
)
613 (defvar org-babel-current-src-block-location nil
614 "Marker pointing to the src block currently being executed.
615 This may also point to a call line or an inline code block. If
616 multiple blocks are being executed (e.g., in chained execution
617 through use of the :var header argument) this marker points to
618 the outer-most code block.")
621 (defun org-babel-execute-src-block (&optional arg info params
)
622 "Execute the current source code block.
623 Insert the results of execution into the buffer. Source code
624 execution and the collection and formatting of results can be
625 controlled through a variety of header arguments.
627 With prefix argument ARG, force re-execution even if an existing
628 result cached in the buffer would otherwise have been returned.
630 Optionally supply a value for INFO in the form returned by
631 `org-babel-get-src-block-info'.
633 Optionally supply a value for PARAMS which will be merged with
634 the header arguments specified at the front of the source code
637 (let* ((org-babel-current-src-block-location
638 (or org-babel-current-src-block-location
640 (org-babel-where-is-src-block-head)
642 (and (org-babel-get-inline-src-block-matches)
643 (match-beginning 0))))
646 (org-babel-get-src-block-info)))
647 (merged-params (org-babel-merge-params (nth 2 info
) params
)))
648 (when (org-babel-check-evaluate
649 (let ((i info
)) (setf (nth 2 i
) merged-params
) i
))
650 (let* ((params (if params
651 (org-babel-process-params merged-params
)
653 (cachep (and (not arg
) (cdr (assoc :cache params
))
654 (string= "yes" (cdr (assoc :cache params
)))))
655 (new-hash (when cachep
(org-babel-sha1-hash info
)))
656 (old-hash (when cachep
(org-babel-current-result-hash)))
657 (cache-current-p (and (not arg
) new-hash
658 (equal new-hash old-hash
))))
661 (save-excursion ;; return cached result
662 (goto-char (org-babel-where-is-src-block-result nil info
))
663 (end-of-line 1) (forward-char 1)
664 (let ((result (org-babel-read-result)))
665 (message (replace-regexp-in-string
666 "%" "%%" (format "%S" result
))) result
)))
667 ((org-babel-confirm-evaluate
668 (let ((i info
)) (setf (nth 2 i
) merged-params
) i
))
669 (let* ((lang (nth 0 info
))
670 (result-params (cdr (assoc :result-params params
)))
671 (body (setf (nth 1 info
)
672 (if (org-babel-noweb-p params
:eval
)
673 (org-babel-expand-noweb-references info
)
675 (dir (cdr (assoc :dir params
)))
677 (or (and dir
(file-name-as-directory (expand-file-name dir
)))
679 (org-babel-call-process-region-original ;; for tramp handler
680 (or (org-bound-and-true-p
681 org-babel-call-process-region-original
)
682 (symbol-function 'call-process-region
)))
683 (indent (nth 5 info
))
686 (let ((call-process-region
688 (apply 'org-babel-tramp-handle-call-process-region
692 (let ((f (intern (concat "org-babel-execute:" f
))))
693 (when (fboundp f
) f
)))))
695 (or (funcall lang-check lang
)
698 (cdr (assoc lang org-src-lang-modes
))))
699 (error "No org-babel-execute function for %s!"
701 (message "executing %s code block%s..."
703 (if (nth 4 info
) (format " (%s)" (nth 4 info
)) ""))
704 (if (member "none" result-params
)
706 (funcall cmd body params
)
707 (message "result silenced")
710 (let ((result (funcall cmd body params
)))
711 (if (and (eq (cdr (assoc :result-type params
))
713 (or (member "vector" result-params
)
714 (member "table" result-params
))
715 (not (listp result
)))
716 (list (list result
)) result
)))
717 ;; If non-empty result and :file then write to :file.
718 (when (cdr (assoc :file params
))
720 (with-temp-file (cdr (assoc :file params
))
722 (org-babel-format-result
723 result
(cdr (assoc :sep
(nth 2 info
)))))))
724 (setq result
(cdr (assoc :file params
))))
725 ;; Possibly perform post process provided its appropriate.
726 (when (cdr (assoc :post params
))
727 (let ((*this
* (if (cdr (assoc :file params
))
728 (org-babel-result-to-file
729 (cdr (assoc :file params
))
730 (when (assoc :file-desc params
)
731 (or (cdr (assoc :file-desc params
))
734 (setq result
(org-babel-ref-resolve
735 (cdr (assoc :post params
))))
736 (when (cdr (assoc :file params
))
738 (remove "file" result-params
)))))
739 (org-babel-insert-result
740 result result-params info new-hash indent lang
))
741 (run-hooks 'org-babel-after-execute-hook
)
743 (setq call-process-region
744 'org-babel-call-process-region-original
)))))))))
746 (defun org-babel-expand-body:generic
(body params
&optional var-lines
)
747 "Expand BODY with PARAMS.
748 Expand a block of code with org-babel according to its header
749 arguments. This generic implementation of body expansion is
750 called for languages which have not defined their own specific
751 org-babel-expand-body:lang function."
752 (let ((pro (cdr (assoc :prologue params
)))
753 (epi (cdr (assoc :epilogue params
))))
754 (mapconcat #'identity
755 (append (when pro
(list pro
))
758 (when epi
(list epi
)))
762 (defun org-babel-expand-src-block (&optional arg info params
)
763 "Expand the current source code block.
764 Expand according to the source code block's header
765 arguments and pop open the results in a preview buffer."
767 (let* ((info (or info
(org-babel-get-src-block-info)))
769 (params (setf (nth 2 info
)
770 (sort (org-babel-merge-params (nth 2 info
) params
)
771 (lambda (el1 el2
) (string< (symbol-name (car el1
))
772 (symbol-name (car el2
)))))))
773 (body (setf (nth 1 info
)
774 (if (org-babel-noweb-p params
:eval
)
775 (org-babel-expand-noweb-references info
) (nth 1 info
))))
776 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
777 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
780 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
781 (org-babel-expand-body:generic
782 body params
(and (fboundp assignments-cmd
)
783 (funcall assignments-cmd params
))))))
784 (if (org-called-interactively-p 'any
)
786 expanded
(concat "*Org-Babel Preview " (buffer-name) "[ " lang
" ]*"))
789 (defun org-babel-edit-distance (s1 s2
)
790 "Return the edit (levenshtein) distance between strings S1 S2."
791 (let* ((l1 (length s1
))
793 (dist (vconcat (mapcar (lambda (_) (make-vector (1+ l2
) nil
))
794 (number-sequence 1 (1+ l1
)))))
795 (in (lambda (i j
) (aref (aref dist i
) j
))))
796 (setf (aref (aref dist
0) 0) 0)
797 (dolist (j (number-sequence 1 l2
))
798 (setf (aref (aref dist
0) j
) j
))
799 (dolist (i (number-sequence 1 l1
))
800 (setf (aref (aref dist i
) 0) i
)
801 (dolist (j (number-sequence 1 l2
))
802 (setf (aref (aref dist i
) j
)
804 (1+ (funcall in
(1- i
) j
))
805 (1+ (funcall in i
(1- j
)))
806 (+ (if (equal (aref s1
(1- i
)) (aref s2
(1- j
))) 0 1)
807 (funcall in
(1- i
) (1- j
)))))))
810 (defun org-babel-combine-header-arg-lists (original &rest others
)
811 "Combine a number of lists of header argument names and arguments."
812 (let ((results (copy-sequence original
)))
813 (dolist (new-list others
)
814 (dolist (arg-pair new-list
)
815 (let ((header (car arg-pair
))
816 (args (cdr arg-pair
)))
818 (cons arg-pair
(org-remove-if
819 (lambda (pair) (equal header
(car pair
)))
824 (defun org-babel-check-src-block ()
825 "Check for misspelled header arguments in the current code block."
827 ;; TODO: report malformed code block
828 ;; TODO: report incompatible combinations of header arguments
829 ;; TODO: report uninitialized variables
830 (let ((too-close 2) ;; <- control closeness to report potential match
831 (names (mapcar #'symbol-name org-babel-header-arg-names
)))
832 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg
)) 1))
833 (and (org-babel-where-is-src-block-head)
834 (org-babel-parse-header-arguments
836 (match-string 4))))))
838 (when (and (not (string= header name
))
839 (<= (org-babel-edit-distance header name
) too-close
)
840 (not (member header names
)))
841 (error "Supplied header \"%S\" is suspiciously close to \"%S\""
843 (message "No suspicious header arguments found.")))
846 (defun org-babel-insert-header-arg (&optional header-arg value
)
847 "Insert a header argument selecting from lists of common args and values."
849 (let* ((info (org-babel-get-src-block-info 'light
))
852 (lang-headers (intern (concat "org-babel-header-args:" lang
)))
853 (headers (org-babel-combine-header-arg-lists
854 org-babel-common-header-args-w-values
855 (when (boundp lang-headers
) (eval lang-headers
))))
856 (header-arg (or header-arg
857 (org-icompleting-read
860 (lambda (header-spec) (symbol-name (car header-spec
)))
862 (vals (cdr (assoc (intern header-arg
) headers
)))
866 (read-from-minibuffer "value: "))
870 (let ((arg (org-icompleting-read
873 (mapcar #'symbol-name group
)))))
874 (if (and arg
(not (string= "default" arg
)))
880 (goto-char (point-at-eol))
881 (unless (= (char-before (point)) ?\
) (insert " "))
882 (insert ":" header-arg
) (when value
(insert " " value
)))))
884 ;; Add support for completing-read insertion of header arguments after ":"
885 (defun org-babel-header-arg-expand ()
886 "Call `org-babel-enter-header-arg-w-completion' in appropriate contexts."
887 (when (and (equal (char-before) ?\
:) (org-babel-where-is-src-block-head))
888 (org-babel-enter-header-arg-w-completion (match-string 2))))
890 (defun org-babel-enter-header-arg-w-completion (&optional lang
)
891 "Insert header argument appropriate for LANG with completion."
892 (let* ((lang-headers-var (intern (concat "org-babel-header-args:" lang
)))
893 (lang-headers (when (boundp lang-headers-var
) (eval lang-headers-var
)))
894 (headers-w-values (org-babel-combine-header-arg-lists
895 org-babel-common-header-args-w-values lang-headers
))
896 (headers (mapcar #'symbol-name
(mapcar #'car headers-w-values
)))
897 (header (org-completing-read "Header Arg: " headers
))
898 (args (cdr (assoc (intern header
) headers-w-values
)))
899 (arg (when (and args
(listp args
))
901 (format "%s: " header
)
902 (mapcar #'symbol-name
(apply #'append args
))))))
903 (insert (concat header
" " (or arg
"")))
906 (add-hook 'org-tab-first-hook
'org-babel-header-arg-expand
)
909 (defun org-babel-load-in-session (&optional arg info
)
910 "Load the body of the current source-code block.
911 Evaluate the header arguments for the source block before
912 entering the session. After loading the body this pops open the
915 (let* ((info (or info
(org-babel-get-src-block-info)))
917 (params (nth 2 info
))
919 (user-error "No src code block at point")
921 (if (org-babel-noweb-p params
:eval
)
922 (org-babel-expand-noweb-references info
)
924 (session (cdr (assoc :session params
)))
925 (dir (cdr (assoc :dir params
)))
927 (or (and dir
(file-name-as-directory dir
)) default-directory
))
928 (cmd (intern (concat "org-babel-load-session:" lang
))))
929 (unless (fboundp cmd
)
930 (error "No org-babel-load-session function for %s!" lang
))
931 (pop-to-buffer (funcall cmd session body params
))
935 (defun org-babel-initiate-session (&optional arg info
)
936 "Initiate session for current code block.
937 If called with a prefix argument then resolve any variable
938 references in the header arguments and assign these variables in
939 the session. Copy the body of the code block to the kill ring."
941 (let* ((info (or info
(org-babel-get-src-block-info (not arg
))))
944 (params (nth 2 info
))
945 (session (cdr (assoc :session params
)))
946 (dir (cdr (assoc :dir params
)))
948 (or (and dir
(file-name-as-directory dir
)) default-directory
))
949 (init-cmd (intern (format "org-babel-%s-initiate-session" lang
)))
950 (prep-cmd (intern (concat "org-babel-prep-session:" lang
))))
951 (if (and (stringp session
) (string= session
"none"))
952 (error "This block is not using a session!"))
953 (unless (fboundp init-cmd
)
954 (error "No org-babel-initiate-session function for %s!" lang
))
955 (with-temp-buffer (insert (org-babel-trim body
))
956 (copy-region-as-kill (point-min) (point-max)))
958 (unless (fboundp prep-cmd
)
959 (error "No org-babel-prep-session function for %s!" lang
))
960 (funcall prep-cmd session params
))
961 (funcall init-cmd session params
)))
964 (defun org-babel-switch-to-session (&optional arg info
)
965 "Switch to the session of the current code block.
966 Uses `org-babel-initiate-session' to start the session. If called
967 with a prefix argument then this is passed on to
968 `org-babel-initiate-session'."
970 (pop-to-buffer (org-babel-initiate-session arg info
))
973 (defalias 'org-babel-pop-to-session
'org-babel-switch-to-session
)
975 (defvar org-src-window-setup
)
978 (defun org-babel-switch-to-session-with-code (&optional arg info
)
979 "Switch to code buffer and display session."
983 (let ((other-window-buffer (window-buffer (next-window))))
984 (set-window-buffer (next-window) (current-buffer))
985 (set-window-buffer (selected-window) other-window-buffer
))
987 (info (org-babel-get-src-block-info))
988 (org-src-window-setup 'reorganize-frame
))
990 (org-babel-switch-to-session arg info
))
992 (funcall swap-windows
)))
995 (defmacro org-babel-do-in-edit-buffer
(&rest body
)
996 "Evaluate BODY in edit buffer if there is a code block at point.
997 Return t if a code block was found at point, nil otherwise."
998 `(let ((org-src-window-setup 'switch-invisibly
))
999 (when (and (org-babel-where-is-src-block-head)
1000 (org-edit-src-code))
1001 (unwind-protect (progn ,@body
)
1002 (org-edit-src-exit))
1004 (def-edebug-spec org-babel-do-in-edit-buffer
(body))
1006 (defun org-babel-do-key-sequence-in-edit-buffer (key)
1007 "Read key sequence and execute the command in edit buffer.
1008 Enter a key sequence to be executed in the language major-mode
1009 edit buffer. For example, TAB will alter the contents of the
1010 Org-mode code block according to the effect of TAB in the
1011 language major-mode buffer. For languages that support
1012 interactive sessions, this can be used to send code from the Org
1013 buffer to the session for evaluation using the native major-mode
1014 evaluation mechanisms."
1015 (interactive "kEnter key-sequence to execute in edit buffer: ")
1016 (org-babel-do-in-edit-buffer
1018 (key-binding (or key
(read-key-sequence nil
))))))
1020 (defvar org-bracket-link-regexp
)
1022 (defun org-babel-active-location-p ()
1023 (memq (org-element-type (save-match-data (org-element-context)))
1024 '(babel-call inline-babel-call inline-src-block src-block
)))
1027 (defun org-babel-open-src-block-result (&optional re-run
)
1028 "If `point' is on a src block then open the results of the
1029 source code block, otherwise return nil. With optional prefix
1030 argument RE-RUN the source-code block is evaluated even if
1031 results already exist."
1033 (let ((info (org-babel-get-src-block-info 'light
)))
1036 ;; go to the results, if there aren't any then run the block
1037 (goto-char (or (and (not re-run
) (org-babel-where-is-src-block-result))
1038 (progn (org-babel-execute-src-block)
1039 (org-babel-where-is-src-block-result))))
1041 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
1043 (if (looking-at org-bracket-link-regexp
)
1046 (let ((r (org-babel-format-result
1047 (org-babel-read-result) (cdr (assoc :sep
(nth 2 info
))))))
1048 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
1049 (delete-region (point-min) (point-max))
1054 (defmacro org-babel-map-src-blocks
(file &rest body
)
1055 "Evaluate BODY forms on each source-block in FILE.
1056 If FILE is nil evaluate BODY forms on source blocks in current
1057 buffer. During evaluation of BODY the following local variables
1058 are set relative to the currently matched code block.
1060 full-block ------- string holding the entirety of the code block
1061 beg-block -------- point at the beginning of the code block
1062 end-block -------- point at the end of the matched code block
1063 lang ------------- string holding the language of the code block
1064 beg-lang --------- point at the beginning of the lang
1065 end-lang --------- point at the end of the lang
1066 switches --------- string holding the switches
1067 beg-switches ----- point at the beginning of the switches
1068 end-switches ----- point at the end of the switches
1069 header-args ------ string holding the header-args
1070 beg-header-args -- point at the beginning of the header-args
1071 end-header-args -- point at the end of the header-args
1072 body ------------- string holding the body of the code block
1073 beg-body --------- point at the beginning of the body
1074 end-body --------- point at the end of the body"
1075 (declare (indent 1))
1076 (let ((tempvar (make-symbol "file")))
1077 `(let* ((case-fold-search t
)
1079 (visited-p (or (null ,tempvar
)
1080 (get-file-buffer (expand-file-name ,tempvar
))))
1081 (point (point)) to-be-removed
)
1082 (save-window-excursion
1083 (when ,tempvar
(find-file ,tempvar
))
1084 (setq to-be-removed
(current-buffer))
1085 (goto-char (point-min))
1086 (while (re-search-forward org-babel-src-block-regexp nil t
)
1087 (when (org-babel-active-location-p)
1088 (goto-char (match-beginning 0))
1089 (let ((full-block (match-string 0))
1090 (beg-block (match-beginning 0))
1091 (end-block (match-end 0))
1092 (lang (match-string 2))
1093 (beg-lang (match-beginning 2))
1094 (end-lang (match-end 2))
1095 (switches (match-string 3))
1096 (beg-switches (match-beginning 3))
1097 (end-switches (match-end 3))
1098 (header-args (match-string 4))
1099 (beg-header-args (match-beginning 4))
1100 (end-header-args (match-end 4))
1101 (body (match-string 5))
1102 (beg-body (match-beginning 5))
1103 (end-body (match-end 5)))
1105 (goto-char end-block
)))))
1106 (unless visited-p
(kill-buffer to-be-removed
))
1107 (goto-char point
))))
1108 (def-edebug-spec org-babel-map-src-blocks
(form body
))
1111 (defmacro org-babel-map-inline-src-blocks
(file &rest body
)
1112 "Evaluate BODY forms on each inline source-block in FILE.
1113 If FILE is nil evaluate BODY forms on source blocks in current
1115 (declare (indent 1))
1116 (let ((tempvar (make-symbol "file")))
1117 `(let* ((case-fold-search t
)
1119 (visited-p (or (null ,tempvar
)
1120 (get-file-buffer (expand-file-name ,tempvar
))))
1121 (point (point)) to-be-removed
)
1122 (save-window-excursion
1123 (when ,tempvar
(find-file ,tempvar
))
1124 (setq to-be-removed
(current-buffer))
1125 (goto-char (point-min))
1126 (while (re-search-forward org-babel-inline-src-block-regexp nil t
)
1127 (when (org-babel-active-location-p)
1128 (goto-char (match-beginning 1))
1129 (save-match-data ,@body
))
1130 (goto-char (match-end 0))))
1131 (unless visited-p
(kill-buffer to-be-removed
))
1132 (goto-char point
))))
1133 (def-edebug-spec org-babel-map-inline-src-blocks
(form body
))
1135 (defvar org-babel-lob-one-liner-regexp
)
1138 (defmacro org-babel-map-call-lines
(file &rest body
)
1139 "Evaluate BODY forms on each call line in FILE.
1140 If FILE is nil evaluate BODY forms on source blocks in current
1142 (declare (indent 1))
1143 (let ((tempvar (make-symbol "file")))
1144 `(let* ((,tempvar
,file
)
1145 (visited-p (or (null ,tempvar
)
1146 (get-file-buffer (expand-file-name ,tempvar
))))
1147 (point (point)) to-be-removed
)
1148 (save-window-excursion
1149 (when ,tempvar
(find-file ,tempvar
))
1150 (setq to-be-removed
(current-buffer))
1151 (goto-char (point-min))
1152 (while (re-search-forward org-babel-lob-one-liner-regexp nil t
)
1153 (when (org-babel-active-location-p)
1154 (goto-char (match-beginning 1))
1155 (save-match-data ,@body
))
1156 (goto-char (match-end 0))))
1157 (unless visited-p
(kill-buffer to-be-removed
))
1158 (goto-char point
))))
1159 (def-edebug-spec org-babel-map-call-lines
(form body
))
1162 (defmacro org-babel-map-executables
(file &rest body
)
1163 (declare (indent 1))
1164 (let ((tempvar (make-symbol "file"))
1165 (rx (make-symbol "rx")))
1166 `(let* ((,tempvar
,file
)
1167 (,rx
(concat "\\(" org-babel-src-block-regexp
1168 "\\|" org-babel-inline-src-block-regexp
1169 "\\|" org-babel-lob-one-liner-regexp
"\\)"))
1170 (visited-p (or (null ,tempvar
)
1171 (get-file-buffer (expand-file-name ,tempvar
))))
1172 (point (point)) to-be-removed
)
1173 (save-window-excursion
1174 (when ,tempvar
(find-file ,tempvar
))
1175 (setq to-be-removed
(current-buffer))
1176 (goto-char (point-min))
1177 (while (re-search-forward ,rx nil t
)
1178 (when (org-babel-active-location-p)
1179 (goto-char (match-beginning 1))
1180 (when (looking-at org-babel-inline-src-block-regexp
)
1182 (save-match-data ,@body
))
1183 (goto-char (match-end 0))))
1184 (unless visited-p
(kill-buffer to-be-removed
))
1185 (goto-char point
))))
1186 (def-edebug-spec org-babel-map-executables
(form body
))
1189 (defun org-babel-execute-buffer (&optional arg
)
1190 "Execute source code blocks in a buffer.
1191 Call `org-babel-execute-src-block' on every source block in
1192 the current buffer."
1194 (org-babel-eval-wipe-error-buffer)
1195 (org-save-outline-visibility t
1196 (org-babel-map-executables nil
1197 (if (looking-at org-babel-lob-one-liner-regexp
)
1198 (org-babel-lob-execute-maybe)
1199 (org-babel-execute-src-block arg
)))))
1202 (defun org-babel-execute-subtree (&optional arg
)
1203 "Execute source code blocks in a subtree.
1204 Call `org-babel-execute-src-block' on every source block in
1205 the current subtree."
1209 (org-narrow-to-subtree)
1210 (org-babel-execute-buffer arg
)
1214 (defun org-babel-sha1-hash (&optional info
)
1215 "Generate an sha1 hash based on the value of info."
1217 (let ((print-level nil
)
1218 (info (or info
(org-babel-get-src-block-info))))
1220 (sort (copy-sequence (nth 2 info
))
1221 (lambda (a b
) (string< (car a
) (car b
)))))
1222 (let* ((rm (lambda (lst)
1223 (dolist (p '("replace" "silent" "none"
1224 "append" "prepend"))
1225 (setq lst
(remove p lst
)))
1228 (let ((v (if (and (listp (cdr arg
)) (null (cddr arg
)))
1229 (copy-sequence (cdr arg
))
1231 (when (and v
(not (and (sequencep v
)
1235 ((and (listp v
) ; lists are sorted
1236 (member (car arg
) '(:result-params
)))
1237 (sort (funcall rm v
) #'string
<))
1238 ((and (stringp v
) ; strings are sorted
1239 (member (car arg
) '(:results
:exports
)))
1240 (mapconcat #'identity
(sort (funcall rm
(split-string v
))
1245 (params (nth 2 info
))
1246 (body (if (org-babel-noweb-p params
:eval
)
1247 (org-babel-expand-noweb-references info
) (nth 1 info
)))
1248 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
1249 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
1252 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
1253 (org-babel-expand-body:generic
1254 body params
(and (fboundp assignments-cmd
)
1255 (funcall assignments-cmd params
))))))
1256 (let* ((it (format "%s-%s"
1259 (delq nil
(mapcar (lambda (arg)
1260 (let ((normalized (funcall norm arg
)))
1262 (format "%S" normalized
))))
1266 (when (org-called-interactively-p 'interactive
) (message hash
))
1269 (defun org-babel-current-result-hash (&optional info
)
1270 "Return the current in-buffer hash."
1271 (org-babel-where-is-src-block-result nil info
)
1272 (org-no-properties (match-string 5)))
1274 (defun org-babel-set-current-result-hash (hash info
)
1275 "Set the current in-buffer hash to HASH."
1276 (org-babel-where-is-src-block-result nil info
)
1277 (save-excursion (goto-char (match-beginning 5))
1278 (mapc #'delete-overlay
(overlays-at (point)))
1279 (forward-char org-babel-hash-show
)
1280 (mapc #'delete-overlay
(overlays-at (point)))
1281 (replace-match hash nil nil nil
5)
1282 (goto-char (point-at-bol))
1283 (org-babel-hide-hash)))
1285 (defun org-babel-hide-hash ()
1286 "Hide the hash in the current results line.
1287 Only the initial `org-babel-hash-show' characters of the hash
1288 will remain visible."
1289 (add-to-invisibility-spec '(org-babel-hide-hash . t
))
1291 (when (and (re-search-forward org-babel-result-regexp nil t
)
1293 (let* ((start (match-beginning 5))
1294 (hide-start (+ org-babel-hash-show start
))
1296 (hash (match-string 5))
1298 (setq ov1
(make-overlay start hide-start
))
1299 (setq ov2
(make-overlay hide-start end
))
1300 (overlay-put ov2
'invisible
'org-babel-hide-hash
)
1301 (overlay-put ov1
'babel-hash hash
)))))
1303 (defun org-babel-hide-all-hashes ()
1304 "Hide the hash in the current buffer.
1305 Only the initial `org-babel-hash-show' characters of each hash
1306 will remain visible. This function should be called as part of
1307 the `org-mode-hook'."
1309 (while (and (not org-babel-hash-show-time
)
1310 (re-search-forward org-babel-result-regexp nil t
))
1311 (goto-char (match-beginning 0))
1312 (org-babel-hide-hash)
1313 (goto-char (match-end 0)))))
1314 (add-hook 'org-mode-hook
'org-babel-hide-all-hashes
)
1316 (defun org-babel-hash-at-point (&optional point
)
1317 "Return the value of the hash at POINT.
1318 The hash is also added as the last element of the kill ring.
1319 This can be called with C-c C-c."
1321 (let ((hash (car (delq nil
(mapcar
1322 (lambda (ol) (overlay-get ol
'babel-hash
))
1323 (overlays-at (or point
(point))))))))
1324 (when hash
(kill-new hash
) (message hash
))))
1325 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-hash-at-point
)
1327 (defun org-babel-result-hide-spec ()
1328 "Hide portions of results lines.
1329 Add `org-babel-hide-result' as an invisibility spec for hiding
1330 portions of results lines."
1331 (add-to-invisibility-spec '(org-babel-hide-result . t
)))
1332 (add-hook 'org-mode-hook
'org-babel-result-hide-spec
)
1334 (defvar org-babel-hide-result-overlays nil
1335 "Overlays hiding results.")
1337 (defun org-babel-result-hide-all ()
1338 "Fold all results in the current buffer."
1340 (org-babel-show-result-all)
1342 (while (re-search-forward org-babel-result-regexp nil t
)
1343 (save-excursion (goto-char (match-beginning 0))
1344 (org-babel-hide-result-toggle-maybe)))))
1346 (defun org-babel-show-result-all ()
1347 "Unfold all results in the current buffer."
1348 (mapc 'delete-overlay org-babel-hide-result-overlays
)
1349 (setq org-babel-hide-result-overlays nil
))
1352 (defun org-babel-hide-result-toggle-maybe ()
1353 "Toggle visibility of result at point."
1355 (let ((case-fold-search t
))
1357 (beginning-of-line 1)
1358 (looking-at org-babel-result-regexp
))
1359 (progn (org-babel-hide-result-toggle)
1360 t
) ;; to signal that we took action
1361 nil
))) ;; to signal that we did not
1363 (defun org-babel-hide-result-toggle (&optional force
)
1364 "Toggle the visibility of the current result."
1368 (if (re-search-forward org-babel-result-regexp nil t
)
1369 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
1371 (while (looking-at org-babel-multi-line-header-regexp
)
1373 (goto-char (- (org-babel-result-end) 1)) (point)))
1375 (if (memq t
(mapcar (lambda (overlay)
1376 (eq (overlay-get overlay
'invisible
)
1377 'org-babel-hide-result
))
1378 (overlays-at start
)))
1379 (if (or (not force
) (eq force
'off
))
1381 (when (member ov org-babel-hide-result-overlays
)
1382 (setq org-babel-hide-result-overlays
1383 (delq ov org-babel-hide-result-overlays
)))
1384 (when (eq (overlay-get ov
'invisible
)
1385 'org-babel-hide-result
)
1386 (delete-overlay ov
)))
1387 (overlays-at start
)))
1388 (setq ov
(make-overlay start end
))
1389 (overlay-put ov
'invisible
'org-babel-hide-result
)
1390 ;; make the block accessible to isearch
1392 ov
'isearch-open-invisible
1394 (when (member ov org-babel-hide-result-overlays
)
1395 (setq org-babel-hide-result-overlays
1396 (delq ov org-babel-hide-result-overlays
)))
1397 (when (eq (overlay-get ov
'invisible
)
1398 'org-babel-hide-result
)
1399 (delete-overlay ov
))))
1400 (push ov org-babel-hide-result-overlays
)))
1401 (error "Not looking at a result line"))))
1403 ;; org-tab-after-check-for-cycling-hook
1404 (add-hook 'org-tab-first-hook
'org-babel-hide-result-toggle-maybe
)
1405 ;; Remove overlays when changing major mode
1406 (add-hook 'org-mode-hook
1407 (lambda () (org-add-hook 'change-major-mode-hook
1408 'org-babel-show-result-all
'append
'local
)))
1410 (defvar org-file-properties
)
1411 (defun org-babel-params-from-properties (&optional lang
)
1412 "Retrieve parameters specified as properties.
1413 Return a list of association lists of source block params
1414 specified in the properties of the current outline entry."
1417 ;; DEPRECATED header arguments specified as separate property at
1418 ;; point of definition
1420 (org-babel-parse-multiple-vars
1423 (lambda (header-arg)
1424 (and (setq val
(org-entry-get (point) header-arg t
))
1425 (cons (intern (concat ":" header-arg
))
1426 (org-babel-read val
))))
1431 (org-babel-combine-header-arg-lists
1432 org-babel-common-header-args-w-values
1434 (setq sym
(intern (concat "org-babel-header-args:" lang
)))
1435 (and (boundp sym
) (eval sym
))))))))))
1436 ;; header arguments specified with the header-args property at
1438 (org-babel-parse-header-arguments
1439 (org-entry-get org-babel-current-src-block-location
1440 "header-args" 'inherit
))
1441 (when lang
;; language-specific header arguments at point of call
1442 (org-babel-parse-header-arguments
1443 (org-entry-get org-babel-current-src-block-location
1444 (concat "header-args:" lang
) 'inherit
))))))
1446 (defvar org-src-preserve-indentation
) ;; declare defcustom from org-src
1447 (defun org-babel-parse-src-block-match ()
1448 "Parse the results from a match of the `org-babel-src-block-regexp'."
1449 (let* ((block-indentation (length (match-string 1)))
1450 (lang (org-no-properties (match-string 2)))
1451 (lang-headers (intern (concat "org-babel-default-header-args:" lang
)))
1452 (switches (match-string 3))
1453 (body (org-no-properties
1454 (let* ((body (match-string 5))
1455 (sub-length (- (length body
) 1)))
1456 (if (and (> sub-length
0)
1457 (string= "\n" (substring body sub-length
)))
1458 (substring body
0 sub-length
)
1460 (preserve-indentation (or org-src-preserve-indentation
1462 (string-match "-i\\>" switches
)))))
1464 ;; get block body less properties, protective commas, and indentation
1467 (insert (org-unescape-code-in-string body
))
1468 (unless preserve-indentation
(org-do-remove-indentation))
1470 (apply #'org-babel-merge-params
1471 org-babel-default-header-args
1472 (when (boundp lang-headers
) (eval lang-headers
))
1474 (org-babel-params-from-properties lang
)
1475 (list (org-babel-parse-header-arguments
1476 (org-no-properties (or (match-string 4) ""))))))
1478 block-indentation
)))
1480 (defun org-babel-parse-inline-src-block-match ()
1481 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
1482 (let* ((lang (org-no-properties (match-string 2)))
1483 (lang-headers (intern (concat "org-babel-default-header-args:" lang
))))
1485 (org-unescape-code-in-string (org-no-properties (match-string 5)))
1486 (apply #'org-babel-merge-params
1487 org-babel-default-inline-header-args
1488 (if (boundp lang-headers
) (eval lang-headers
) nil
)
1490 (org-babel-params-from-properties lang
)
1491 (list (org-babel-parse-header-arguments
1492 (org-no-properties (or (match-string 4) ""))))))
1495 (defun org-babel-balanced-split (string alts
)
1496 "Split STRING on instances of ALTS.
1497 ALTS is a cons of two character options where each option may be
1498 either the numeric code of a single character or a list of
1499 character alternatives. For example to split on balanced
1500 instances of \"[ \t]:\" set ALTS to '((32 9) . 58)."
1501 (let* ((matches (lambda (ch spec
) (if (listp spec
) (member ch spec
) (equal spec ch
))))
1502 (matched (lambda (ch last
)
1504 (and (funcall matches ch
(cdr alts
))
1505 (funcall matches last
(car alts
)))
1506 (funcall matches ch alts
))))
1507 (balance 0) (last 0)
1509 (mapc (lambda (ch) ; split on [], (), "" balanced instances of [ \t]:
1510 (setq balance
(+ balance
1511 (cond ((or (equal 91 ch
) (equal 40 ch
)) 1)
1512 ((or (equal 93 ch
) (equal 41 ch
)) -
1)
1514 (when (and (equal 34 ch
) (not (equal 92 last
)))
1515 (setq quote
(not quote
)))
1516 (setq partial
(cons ch partial
))
1517 (when (and (= balance
0) (not quote
) (funcall matched ch last
))
1518 (setq lst
(cons (apply #'string
(nreverse
1525 (string-to-list string
))
1526 (nreverse (cons (apply #'string
(nreverse partial
)) lst
))))
1528 (defun org-babel-join-splits-near-ch (ch list
)
1529 "Join splits where \"=\" is on either end of the split."
1530 (let ((last= (lambda (str) (= ch
(aref str
(1- (length str
))))))
1531 (first= (lambda (str) (= ch
(aref str
0)))))
1533 (org-reduce (lambda (acc el
)
1534 (let ((head (car acc
)))
1535 (if (and head
(or (funcall last
= head
) (funcall first
= el
)))
1536 (cons (concat head el
) (cdr acc
))
1538 list
:initial-value nil
))))
1540 (defun org-babel-parse-header-arguments (arg-string)
1541 "Parse a string of header arguments returning an alist."
1542 (when (> (length arg-string
) 0)
1543 (org-babel-parse-multiple-vars
1548 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1550 (cons (intern (match-string 1 arg
))
1551 (org-babel-read (org-babel-chomp (match-string 2 arg
))))
1552 (cons (intern (org-babel-chomp arg
)) nil
)))
1553 (let ((raw (org-babel-balanced-split arg-string
'((32 9) .
58))))
1554 (cons (car raw
) (mapcar (lambda (r) (concat ":" r
)) (cdr raw
)))))))))
1556 (defun org-babel-parse-multiple-vars (header-arguments)
1557 "Expand multiple variable assignments behind a single :var keyword.
1559 This allows expression of multiple variables with one :var as
1562 #+PROPERTY: var foo=1, bar=2"
1564 (mapc (lambda (pair)
1565 (if (eq (car pair
) :var
)
1566 (mapcar (lambda (v) (push (cons :var
(org-babel-trim v
)) results
))
1567 (org-babel-join-splits-near-ch
1568 61 (org-babel-balanced-split (cdr pair
) 32)))
1569 (push pair results
)))
1571 (nreverse results
)))
1573 (defun org-babel-process-params (params)
1574 "Expand variables in PARAMS and add summary parameters."
1575 (let* ((processed-vars (mapcar (lambda (el)
1576 (if (consp (cdr el
))
1578 (org-babel-ref-parse (cdr el
))))
1579 (org-babel-get-header params
:var
)))
1580 (vars-and-names (if (and (assoc :colname-names params
)
1581 (assoc :rowname-names params
))
1582 (list processed-vars
)
1583 (org-babel-disassemble-tables
1585 (cdr (assoc :hlines params
))
1586 (cdr (assoc :colnames params
))
1587 (cdr (assoc :rownames params
)))))
1588 (raw-result (or (cdr (assoc :results params
)) ""))
1589 (result-params (append
1590 (split-string (if (stringp raw-result
)
1593 (cdr (assoc :result-params params
)))))
1595 (mapcar (lambda (var) (cons :var var
)) (car vars-and-names
))
1597 (cons :colname-names
(or (cdr (assoc :colname-names params
))
1598 (cadr vars-and-names
)))
1599 (cons :rowname-names
(or (cdr (assoc :rowname-names params
))
1600 (caddr vars-and-names
)))
1601 (cons :result-params result-params
)
1602 (cons :result-type
(cond ((member "output" result-params
) 'output
)
1603 ((member "value" result-params
) 'value
)
1605 (org-babel-get-header params
:var
'other
))))
1607 ;; row and column names
1608 (defun org-babel-del-hlines (table)
1609 "Remove all 'hlines from TABLE."
1610 (remq 'hline table
))
1612 (defun org-babel-get-colnames (table)
1613 "Return the column names of TABLE.
1614 Return a cons cell, the `car' of which contains the TABLE less
1615 colnames, and the `cdr' of which contains a list of the column
1617 (if (equal 'hline
(nth 1 table
))
1618 (cons (cddr table
) (car table
))
1619 (cons (cdr table
) (car table
))))
1621 (defun org-babel-get-rownames (table)
1622 "Return the row names of TABLE.
1623 Return a cons cell, the `car' of which contains the TABLE less
1624 rownames, and the `cdr' of which contains a list of the rownames.
1625 Note: this function removes any hlines in TABLE."
1626 (let* ((table (org-babel-del-hlines table
))
1627 (rownames (funcall (lambda ()
1633 (setq tp
(cdr tp
))))
1635 (cons table rownames
)))
1637 (defun org-babel-put-colnames (table colnames
)
1638 "Add COLNAMES to TABLE if they exist."
1639 (if colnames
(apply 'list colnames
'hline table
) table
))
1641 (defun org-babel-put-rownames (table rownames
)
1642 "Add ROWNAMES to TABLE if they exist."
1644 (mapcar (lambda (row)
1646 (cons (or (pop rownames
) "") row
)
1650 (defun org-babel-pick-name (names selector
)
1651 "Select one out of an alist of row or column names.
1652 SELECTOR can be either a list of names in which case those names
1653 will be returned directly, or an index into the list NAMES in
1654 which case the indexed names will be return."
1655 (if (listp selector
)
1658 (if (and selector
(symbolp selector
) (not (equal t selector
)))
1659 (cdr (assoc selector names
))
1660 (if (integerp selector
)
1661 (nth (- selector
1) names
)
1662 (cdr (car (last names
))))))))
1664 (defun org-babel-disassemble-tables (vars hlines colnames rownames
)
1665 "Parse tables for further processing.
1666 Process the variables in VARS according to the HLINES,
1667 ROWNAMES and COLNAMES header arguments. Return a list consisting
1668 of the vars, cnames and rnames."
1669 (let (cnames rnames
)
1673 (when (listp (cdr var
))
1674 (when (and (not (equal colnames
"no"))
1675 (or colnames
(and (equal (nth 1 (cdr var
)) 'hline
)
1676 (not (member 'hline
(cddr (cdr var
)))))))
1677 (let ((both (org-babel-get-colnames (cdr var
))))
1678 (setq cnames
(cons (cons (car var
) (cdr both
))
1680 (setq var
(cons (car var
) (car both
)))))
1681 (when (and rownames
(not (equal rownames
"no")))
1682 (let ((both (org-babel-get-rownames (cdr var
))))
1683 (setq rnames
(cons (cons (car var
) (cdr both
))
1685 (setq var
(cons (car var
) (car both
)))))
1686 (when (and hlines
(not (equal hlines
"yes")))
1687 (setq var
(cons (car var
) (org-babel-del-hlines (cdr var
))))))
1690 (reverse cnames
) (reverse rnames
))))
1692 (defun org-babel-reassemble-table (table colnames rownames
)
1693 "Add column and row names to a table.
1694 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1695 to the table for reinsertion to org-mode."
1697 (let ((table (if (and rownames
(= (length table
) (length rownames
)))
1698 (org-babel-put-rownames table rownames
) table
)))
1699 (if (and colnames
(listp (car table
)) (= (length (car table
))
1701 (org-babel-put-colnames table colnames
) table
))
1704 (defun org-babel-where-is-src-block-head ()
1705 "Find where the current source block begins.
1706 Return the point at the beginning of the current source block.
1707 Specifically at the beginning of the #+BEGIN_SRC line. Also set
1708 match-data relatively to `org-babel-src-block-regexp', which see.
1709 If the point is not on a source block then return nil."
1710 (let ((element (org-element-at-point)))
1711 (when (eq (org-element-type element
) 'src-block
)
1712 (let ((end (org-element-property :end element
)))
1713 (org-with-wide-buffer
1714 ;; Ensure point is not on a blank line after the block.
1716 (skip-chars-forward " \r\t\n" end
)
1717 (when (< (point) end
)
1718 (prog1 (goto-char (org-element-property :post-affiliated element
))
1719 (looking-at org-babel-src-block-regexp
))))))))
1722 (defun org-babel-goto-src-block-head ()
1723 "Go to the beginning of the current code block."
1725 (let ((head (org-babel-where-is-src-block-head)))
1726 (if head
(goto-char head
) (error "Not currently in a code block"))))
1729 (defun org-babel-goto-named-src-block (name)
1730 "Go to a named source-code block."
1732 (let ((completion-ignore-case t
)
1733 (case-fold-search t
)
1734 (under-point (thing-at-point 'line
)))
1735 (list (org-icompleting-read
1736 "source-block name: " (org-babel-src-block-names) nil t
1739 ((string-match (org-babel-noweb-wrap) under-point
)
1740 (let ((block-name (match-string 1 under-point
)))
1741 (string-match "[^(]*" block-name
)
1742 (match-string 0 block-name
)))
1744 ((string-match org-babel-lob-one-liner-regexp under-point
)
1745 (let ((source-info (car (org-babel-lob-get-info))))
1746 (if (string-match "^\\([^\\[]+?\\)\\(\\[.*\\]\\)?(" source-info
)
1747 (let ((source-name (match-string 1 source-info
)))
1750 ((string-match (concat "#\\+" org-babel-results-keyword
1751 "\\:\s+\\([^\\(]*\\)") under-point
)
1752 (match-string 1 under-point
))
1754 ((and (thing-at-point 'symbol
))
1755 (org-babel-find-named-block (thing-at-point 'symbol
))
1756 (thing-at-point 'symbol
))
1758 (let ((point (org-babel-find-named-block name
)))
1760 ;; taken from `org-open-at-point'
1761 (progn (org-mark-ring-push) (goto-char point
) (org-show-context))
1762 (message "source-code block '%s' not found in this buffer" name
))))
1764 (defun org-babel-find-named-block (name)
1765 "Find a named source-code block.
1766 Return the location of the source block identified by source
1767 NAME, or nil if no such block exists. Set match data according to
1768 org-babel-named-src-block-regexp."
1770 (let ((case-fold-search t
)
1771 (regexp (org-babel-named-src-block-regexp-for-name name
)) msg
)
1772 (goto-char (point-min))
1773 (when (or (re-search-forward regexp nil t
)
1774 (re-search-backward regexp nil t
))
1775 (match-beginning 0)))))
1777 (defun org-babel-src-block-names (&optional file
)
1778 "Returns the names of source blocks in FILE or the current buffer."
1780 (when file
(find-file file
)) (goto-char (point-min))
1781 (let ((case-fold-search t
) names
)
1782 (while (re-search-forward org-babel-src-name-w-name-regexp nil t
)
1783 (setq names
(cons (match-string 3) names
)))
1787 (defun org-babel-goto-named-result (name)
1788 "Go to a named result."
1790 (let ((completion-ignore-case t
))
1791 (list (org-icompleting-read "source-block name: "
1792 (org-babel-result-names) nil t
))))
1793 (let ((point (org-babel-find-named-result name
)))
1795 ;; taken from `org-open-at-point'
1796 (progn (goto-char point
) (org-show-context))
1797 (message "result '%s' not found in this buffer" name
))))
1799 (defun org-babel-find-named-result (name &optional point
)
1800 "Find a named result.
1801 Return the location of the result named NAME in the current
1802 buffer or nil if no such result exists."
1804 (let ((case-fold-search t
))
1805 (goto-char (or point
(point-min)))
1806 (catch 'is-a-code-block
1807 (when (re-search-forward
1808 (concat org-babel-result-regexp
1809 "[ \t]" (regexp-quote name
) "[ \t]*[\n\f\v\r]") nil t
)
1810 (when (and (string= "name" (downcase (match-string 1)))
1811 (or (beginning-of-line 1)
1812 (looking-at org-babel-src-block-regexp
)
1813 (looking-at org-babel-multi-line-header-regexp
)
1814 (looking-at org-babel-lob-one-liner-regexp
)))
1815 (throw 'is-a-code-block
(org-babel-find-named-result name
(point))))
1816 (beginning-of-line 0) (point))))))
1818 (defun org-babel-result-names (&optional file
)
1819 "Returns the names of results in FILE or the current buffer."
1821 (when file
(find-file file
)) (goto-char (point-min))
1822 (let ((case-fold-search t
) names
)
1823 (while (re-search-forward org-babel-result-w-name-regexp nil t
)
1824 (setq names
(cons (match-string 4) names
)))
1828 (defun org-babel-next-src-block (&optional arg
)
1829 "Jump to the next source block.
1830 With optional prefix argument ARG, jump forward ARG many source blocks."
1832 (org-next-block arg nil org-babel-src-block-regexp
))
1835 (defun org-babel-previous-src-block (&optional arg
)
1836 "Jump to the previous source block.
1837 With optional prefix argument ARG, jump backward ARG many source blocks."
1839 (org-previous-block arg org-babel-src-block-regexp
))
1841 (defvar org-babel-load-languages
)
1844 (defun org-babel-mark-block ()
1845 "Mark current src block."
1847 (let ((head (org-babel-where-is-src-block-head)))
1851 (looking-at org-babel-src-block-regexp
))
1852 (push-mark (match-end 5) nil t
)
1853 (goto-char (match-beginning 5)))))
1855 (defun org-babel-demarcate-block (&optional arg
)
1856 "Wrap or split the code in the region or on the point.
1857 When called from inside of a code block the current block is
1858 split. When called from outside of a code block a new code block
1859 is created. In both cases if the region is demarcated and if the
1860 region is not active then the point is demarcated."
1862 (let* ((info (org-babel-get-src-block-info 'light
))
1863 (start (org-babel-where-is-src-block-head))
1864 (block (and start
(match-string 0)))
1865 (headers (and start
(match-string 4)))
1866 (stars (concat (make-string (or (org-current-level) 1) ?
*) " "))
1867 (lower-case-p (and block
1868 (let (case-fold-search)
1869 (org-string-match-p "#\\+begin_src" block
)))))
1875 (let ((lang (nth 0 info
))
1876 (indent (make-string (nth 5 info
) ?
)))
1877 (when (string-match "^[[:space:]]*$"
1878 (buffer-substring (point-at-bol)
1880 (delete-region (point-at-bol) (point-at-eol)))
1882 (if (looking-at "^") "" "\n")
1883 indent
(funcall (if lower-case-p
'downcase
'upcase
) "#+end_src\n")
1884 (if arg stars indent
) "\n"
1885 indent
(funcall (if lower-case-p
'downcase
'upcase
) "#+begin_src ")
1887 (if (> (length headers
) 1)
1888 (concat " " headers
) headers
)
1889 (if (looking-at "[\n\r]")
1891 (concat "\n" (make-string (current-column) ?
)))))))
1892 (move-end-of-line 2))
1893 (sort (if (org-region-active-p) (list (mark) (point)) (list (point))) #'>))
1894 (let ((start (point))
1895 (lang (org-icompleting-read
1897 (mapcar #'symbol-name
1899 (append (mapcar #'car org-babel-load-languages
)
1900 (mapcar (lambda (el) (intern (car el
)))
1901 org-src-lang-modes
))))))
1902 (body (delete-and-extract-region
1903 (if (org-region-active-p) (mark) (point)) (point))))
1904 (insert (concat (if (looking-at "^") "" "\n")
1905 (if arg
(concat stars
"\n") "")
1906 (funcall (if lower-case-p
'downcase
'upcase
) "#+begin_src ")
1909 (if (or (= (length body
) 0)
1910 (string-match "[\r\n]$" body
)) "" "\n")
1911 (funcall (if lower-case-p
'downcase
'upcase
) "#+end_src\n")))
1912 (goto-char start
) (move-end-of-line 1)))))
1914 (defvar org-babel-lob-one-liner-regexp
)
1915 (defun org-babel-where-is-src-block-result (&optional insert info hash indent
)
1916 "Find where the current source block results begin.
1917 Return the point at the beginning of the result of the current
1918 source block. Specifically at the beginning of the results line.
1919 If no result exists for this block then create a results line
1920 following the source block."
1922 (let* ((case-fold-search t
)
1923 (on-lob-line (save-excursion
1924 (beginning-of-line 1)
1925 (looking-at org-babel-lob-one-liner-regexp
)))
1926 (inlinep (when (org-babel-get-inline-src-block-matches)
1928 (name (nth 4 (or info
(org-babel-get-src-block-info 'light
))))
1929 (head (unless on-lob-line
(org-babel-where-is-src-block-head)))
1931 (when head
(goto-char head
))
1932 (org-with-wide-buffer
1934 found
;; was there a result (before we potentially insert one)
1939 ;; - return t if it is found, else return nil
1940 ;; - if it does not need to be rebuilt, then don't set end
1941 ;; - if it does need to be rebuilt then do set end
1942 name
(setq beg
(org-babel-find-named-result name
))
1944 (when (and hash
(not (string= hash
(match-string 5))))
1945 (goto-char beg
) (setq end beg
) ;; beginning of result
1947 (delete-region end
(org-babel-result-end)) nil
)))
1950 ;; - return t if it is found, else return nil
1951 ;; - if it is found, and the hash doesn't match, delete and set end
1952 (or on-lob-line
(re-search-forward "^[ \t]*#\\+end_src" nil t
))
1953 (progn (end-of-line 1)
1954 (if (eobp) (insert "\n") (forward-char 1))
1958 (progn ;; unnamed results line already exists
1960 (while (re-search-forward "[^ \f\t\n\r\v]" nil t
)
1961 (beginning-of-line 1)
1963 ((looking-at (concat org-babel-result-regexp
"\n"))
1964 (throw 'non-comment t
))
1965 ((and (looking-at "^[ \t]*#")
1967 org-babel-lob-one-liner-regexp
)))
1969 (t (throw 'non-comment nil
))))))
1970 (let ((this-hash (match-string 5)))
1972 ;; must remove and rebuild if hash!=old-hash
1973 (if (and hash
(not (string= hash this-hash
)))
1975 (setq end
(point-at-bol))
1977 (delete-region end
(org-babel-result-end))
1979 (setq end nil
))))))))))
1980 (if (not (and insert end
)) found
1983 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1985 (when (wholenump indent
) (make-string indent ?
))
1986 "#+" org-babel-results-keyword
1988 (if org-babel-hash-show-time
1990 "["(format-time-string "<%Y-%m-%d %H:%M:%S>")" "hash
"]")
1991 (concat "["hash
"]")))
1993 (when name
(concat " " name
)) "\n"))
1994 (unless beg
(insert "\n") (backward-char))
1995 (beginning-of-line 0)
1996 (if hash
(org-babel-hide-hash))
1999 (defvar org-block-regexp
)
2000 (defun org-babel-read-result ()
2001 "Read the result at `point' into emacs-lisp."
2002 (let ((case-fold-search t
) result-string
)
2004 ((org-at-table-p) (org-babel-read-table))
2005 ((org-at-item-p) (org-babel-read-list))
2006 ((looking-at org-bracket-link-regexp
) (org-babel-read-link))
2007 ((looking-at org-block-regexp
) (org-remove-indentation (match-string 4)))
2008 ((or (looking-at "^[ \t]*: ") (looking-at "^[ \t]*:$"))
2011 (mapconcat (lambda (line)
2012 (or (and (> (length line
) 1)
2013 (string-match "^[ \t]*: ?\\(.+\\)" line
)
2014 (match-string 1 line
))
2018 (point) (org-babel-result-end)) "[\r\n]+")
2020 (or (org-babel-number-p result-string
) result-string
))
2021 ((looking-at org-babel-result-regexp
)
2022 (save-excursion (forward-line 1) (org-babel-read-result))))))
2024 (defun org-babel-read-table ()
2025 "Read the table at `point' into emacs-lisp."
2026 (mapcar (lambda (row)
2027 (if (and (symbolp row
) (equal row
'hline
)) row
2028 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
)) row
)))
2029 (org-table-to-lisp)))
2031 (defun org-babel-read-list ()
2032 "Read the list at `point' into emacs-lisp."
2033 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
))
2034 (mapcar #'cadr
(cdr (org-list-parse-list)))))
2036 (defvar org-link-types-re
)
2037 (defun org-babel-read-link ()
2038 "Read the link at `point' into emacs-lisp.
2039 If the path of the link is a file path it is expanded using
2040 `expand-file-name'."
2041 (let* ((case-fold-search t
)
2042 (raw (and (looking-at org-bracket-link-regexp
)
2043 (org-no-properties (match-string 1))))
2044 (type (and (string-match org-link-types-re raw
)
2045 (match-string 1 raw
))))
2047 ((not type
) (expand-file-name raw
))
2048 ((string= type
"file")
2049 (and (string-match "file\\(.*\\):\\(.+\\)" raw
)
2050 (expand-file-name (match-string 2 raw
))))
2053 (defun org-babel-format-result (result &optional sep
)
2054 "Format RESULT for writing to file."
2055 (let ((echo-res (lambda (r) (if (stringp r
) r
(format "%S" r
)))))
2059 result
(list :sep
(or sep
"\t") :fmt echo-res
))
2061 (funcall echo-res result
))))
2063 (defun org-babel-insert-result
2064 (result &optional result-params info hash indent lang
)
2065 "Insert RESULT into the current buffer.
2066 By default RESULT is inserted after the end of the
2067 current source block. With optional argument RESULT-PARAMS
2068 controls insertion of results in the org-mode file.
2069 RESULT-PARAMS can take the following values:
2071 replace - (default option) insert results after the source block
2072 replacing any previously inserted results
2074 silent -- no results are inserted into the Org-mode buffer but
2075 the results are echoed to the minibuffer and are
2076 ingested by Emacs (a potentially time consuming
2079 file ---- the results are interpreted as a file path, and are
2080 inserted into the buffer using the Org-mode file syntax
2082 list ---- the results are interpreted as an Org-mode list.
2084 raw ----- results are added directly to the Org-mode file. This
2085 is a good option if you code block will output org-mode
2088 drawer -- results are added directly to the Org-mode file as with
2089 \"raw\", but are wrapped in a RESULTS drawer, allowing
2090 them to later be replaced or removed automatically.
2092 org ----- results are added inside of a \"src_org{}\" or \"#+BEGIN_SRC
2093 org\" block depending on whether the current source block is
2094 inline or not. They are not comma-escaped when inserted,
2095 but Org syntax here will be discarded when exporting the
2098 html ---- results are added inside of a #+BEGIN_HTML block. This
2099 is a good option if you code block will output html
2102 latex --- results are added inside of a #+BEGIN_LATEX block.
2103 This is a good option if you code block will output
2104 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."
2112 (if (stringp result
)
2114 (setq result
(org-no-properties result
))
2115 (when (member "file" result-params
)
2116 (setq result
(org-babel-result-to-file
2117 result
(when (assoc :file-desc
(nth 2 info
))
2118 (or (cdr (assoc :file-desc
(nth 2 info
)))
2120 (unless (listp result
) (setq result
(format "%S" result
))))
2121 (if (and result-params
(member "silent" result-params
))
2123 (message (replace-regexp-in-string "%" "%%" (format "%S" result
)))
2128 (when (or (org-babel-get-inline-src-block-matches)
2129 (org-babel-get-lob-one-liner-matches))
2130 (goto-char (match-end 0))
2131 (insert (if (listp result
) "\n" " "))
2133 (existing-result (unless inlinep
2134 (org-babel-where-is-src-block-result
2135 t info hash indent
)))
2137 (cdr (assoc :results_switches
(nth 2 info
))))
2138 (visible-beg (copy-marker (point-min)))
2139 (visible-end (copy-marker (point-max)))
2140 ;; When results exist outside of the current visible
2141 ;; region of the buffer, be sure to widen buffer to
2143 (outside-scope-p (and existing-result
2144 (or (> visible-beg existing-result
)
2145 (<= visible-end existing-result
))))
2147 (when (and (stringp result
) ; ensure results end in a newline
2149 (> (length result
) 0)
2150 (not (or (string-equal (substring result -
1) "\n")
2151 (string-equal (substring result -
1) "\r"))))
2152 (setq result
(concat result
"\n")))
2155 (when outside-scope-p
(widen))
2156 (if (not existing-result
)
2157 (setq beg
(or inlinep
(point)))
2158 (goto-char existing-result
)
2160 (re-search-forward "#" nil t
)
2161 (setq indent
(- (current-column) 1)))
2165 ((member "replace" result-params
)
2166 (delete-region (point) (org-babel-result-end)))
2167 ((member "append" result-params
)
2168 (goto-char (org-babel-result-end)) (setq beg
(point-marker)))
2169 ((member "prepend" result-params
)))) ; already there
2170 (setq results-switches
2171 (if results-switches
(concat " " results-switches
) ""))
2172 (let ((wrap (lambda (start finish
&optional no-escape no-newlines
)
2174 (insert (concat finish
(unless no-newlines
"\n")))
2176 (insert (concat start
(unless no-newlines
"\n")))
2178 (org-escape-code-in-region (min (point) end
) end
))
2180 (unless no-newlines
(goto-char (point-at-eol)))
2181 (setq end
(point-marker))))
2182 (proper-list-p (lambda (it) (and (listp it
) (null (cdr (last it
)))))))
2183 ;; insert results based on type
2185 ;; do nothing for an empty result
2187 ;; insert a list if preferred
2188 ((member "list" result-params
)
2191 (org-list-to-generic
2194 (lambda (el) (list nil
(if (stringp el
) el
(format "%S" el
))))
2195 (if (listp result
) result
(split-string result
"\n" t
))))
2196 '(:splicep nil
:istart
"- " :iend
"\n")))
2198 ;; assume the result is a table if it's not a string
2199 ((funcall proper-list-p result
)
2201 (insert (concat (orgtbl-to-orgtbl
2203 (lambda (el) (or (listp el
) (eq el
'hline
)))
2205 result
(list result
))
2206 '(:fmt
(lambda (cell) (format "%s" cell
)))) "\n"))
2207 (goto-char beg
) (when (org-at-table-p) (org-table-align)))
2208 ((and (listp result
) (not (funcall proper-list-p result
)))
2209 (insert (format "%s\n" result
)))
2210 ((member "file" result-params
)
2211 (when inlinep
(goto-char inlinep
))
2213 (t (goto-char beg
) (insert result
)))
2214 (when (funcall proper-list-p result
) (goto-char (org-table-end)))
2215 (setq end
(point-marker))
2216 ;; possibly wrap result
2218 ((assoc :wrap
(nth 2 info
))
2219 (let ((name (or (cdr (assoc :wrap
(nth 2 info
))) "RESULTS")))
2220 (funcall wrap
(concat "#+BEGIN_" name
)
2221 (concat "#+END_" (car (org-split-string name
))))))
2222 ((member "html" result-params
)
2223 (funcall wrap
"#+BEGIN_HTML" "#+END_HTML"))
2224 ((member "latex" result-params
)
2225 (funcall wrap
"#+BEGIN_LaTeX" "#+END_LaTeX"))
2226 ((member "org" result-params
)
2227 (goto-char beg
) (if (org-at-table-p) (org-cycle))
2229 (funcall wrap
"src_org{" "}" nil t
)
2230 (funcall wrap
"#+BEGIN_SRC org" "#+END_SRC")))
2231 ((member "code" result-params
)
2232 (let ((lang (or lang
"none")))
2234 (funcall wrap
(format "src_%s[%s]{" lang results-switches
)
2236 (funcall wrap
(format "#+BEGIN_SRC %s%s" lang results-switches
)
2238 ((member "raw" result-params
)
2239 (goto-char beg
) (if (org-at-table-p) (org-cycle)))
2240 ((or (member "drawer" result-params
)
2241 ;; Stay backward compatible with <7.9.2
2242 (member "wrap" result-params
))
2243 (goto-char beg
) (if (org-at-table-p) (org-cycle))
2244 (funcall wrap
":RESULTS:" ":END:" 'no-escape
))
2245 ((and (not (funcall proper-list-p result
))
2246 (not (member "file" result-params
)))
2247 (org-babel-examplify-region beg end results-switches
)
2248 (setq end
(point)))))
2249 ;; possibly indent the results to match the #+results line
2250 (when (and (not inlinep
) (numberp indent
) indent
(> indent
0)
2251 ;; in this case `table-align' does the work for us
2252 (not (and (listp result
)
2253 (member "append" result-params
))))
2254 (indent-rigidly beg end indent
))
2256 (if (member "value" result-params
)
2257 (message "Code block returned no value.")
2258 (message "Code block produced no output."))
2259 (message "Code block evaluation complete.")))
2260 (when outside-scope-p
(narrow-to-region visible-beg visible-end
))
2261 (set-marker visible-beg nil
)
2262 (set-marker visible-end nil
))))))
2264 (defun org-babel-remove-result (&optional info keep-keyword
)
2265 "Remove the result of the current source block."
2267 (let ((location (org-babel-where-is-src-block-result nil info
)))
2270 (goto-char location
)
2271 (when (looking-at (concat org-babel-result-regexp
".*$"))
2273 (if keep-keyword
(1+ (match-end 0)) (1- (match-beginning 0)))
2274 (progn (forward-line 1) (org-babel-result-end))))))))
2276 (defun org-babel-remove-result-one-or-many (x)
2277 "Remove the result of the current source block.
2278 If called with a prefix argument, remove all result blocks
2282 (org-babel-map-src-blocks nil
(org-babel-remove-result))
2283 (org-babel-remove-result)))
2285 (defun org-babel-result-end ()
2286 "Return the point at the end of the current set of results."
2289 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
2290 ((org-at-item-p) (let* ((struct (org-list-struct))
2291 (prvs (org-list-prevs-alist struct
)))
2292 (org-list-get-list-end (point-at-bol) struct prvs
)))
2293 ((let ((case-fold-search t
)) (looking-at "^\\([ \t]*\\):results:"))
2294 (progn (re-search-forward (concat "^" (match-string 1) ":END:"))
2295 (forward-char 1) (point)))
2297 (let ((case-fold-search t
))
2298 (if (looking-at (concat "[ \t]*#\\+begin_\\([^ \t\n\r]+\\)"))
2299 (progn (re-search-forward (concat "[ \t]*#\\+end_" (match-string 1))
2302 (while (looking-at "[ \t]*\\(: \\|:$\\|\\[\\[\\)")
2306 (defun org-babel-result-to-file (result &optional description
)
2307 "Convert RESULT into an `org-mode' link with optional DESCRIPTION.
2308 If the `default-directory' is different from the containing
2309 file's directory then expand relative links."
2310 (when (stringp result
)
2311 (format "[[file:%s]%s]"
2312 (if (and default-directory
2314 (not (string= (expand-file-name default-directory
)
2316 (file-name-directory buffer-file-name
)))))
2317 (expand-file-name result default-directory
)
2319 (if description
(concat "[" description
"]") ""))))
2321 (defvar org-babel-capitalize-example-region-markers nil
2322 "Make true to capitalize begin/end example markers inserted by code blocks.")
2324 (define-obsolete-function-alias
2325 'org-babel-examplize-region
2326 'org-babel-examplify-region
"25.1")
2328 (defun org-babel-examplify-region (beg end
&optional results-switches
)
2329 "Comment out region using the inline '==' or ': ' org example quote."
2331 (let ((chars-between (lambda (b e
)
2332 (not (string-match "^[\\s]*$"
2333 (buffer-substring b e
)))))
2334 (maybe-cap (lambda (str) (if org-babel-capitalize-example-region-markers
2336 (beg-bol (save-excursion (goto-char beg
) (point-at-bol)))
2337 (end-bol (save-excursion (goto-char end
) (point-at-bol)))
2338 (end-eol (save-excursion (goto-char end
) (point-at-eol))))
2339 (if (and (not (= end end-bol
))
2340 (or (funcall chars-between beg-bol beg
)
2341 (funcall chars-between end end-eol
)))
2344 (insert (format org-babel-inline-result-wrap
2345 (prog1 (buffer-substring beg end
)
2346 (delete-region beg end
)))))
2347 (let ((size (count-lines beg end
)))
2349 (cond ((= size
0)) ; do nothing for an empty result
2350 ((< size org-babel-min-lines-for-block-output
)
2353 (beginning-of-line 1) (insert ": ") (forward-line 1)))
2356 (insert (if results-switches
2358 (funcall maybe-cap
"#+begin_example")
2360 (funcall maybe-cap
"#+begin_example\n")))
2361 (if (markerp end
) (goto-char end
) (forward-char (- end beg
)))
2362 (insert (funcall maybe-cap
"#+end_example\n")))))))))
2364 (defun org-babel-update-block-body (new-body)
2365 "Update the body of the current code block to NEW-BODY."
2366 (if (not (org-babel-where-is-src-block-head))
2367 (error "Not in a source block")
2369 (replace-match (concat (org-babel-trim (org-remove-indentation new-body
))
2371 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
2373 (defun org-babel-merge-params (&rest plists
)
2374 "Combine all parameter association lists in PLISTS.
2375 Later elements of PLISTS override the values of previous elements.
2376 This takes into account some special considerations for certain
2377 parameters when merging lists."
2378 (let* ((results-exclusive-groups
2379 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2380 (cdr (assoc 'results org-babel-common-header-args-w-values
))))
2381 (exports-exclusive-groups
2382 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2383 (cdr (assoc 'exports org-babel-common-header-args-w-values
))))
2385 (e-merge (lambda (exclusive-groups &rest result-params
)
2386 ;; maintain exclusivity of mutually exclusive parameters
2388 (mapc (lambda (new-params)
2389 (mapc (lambda (new-param)
2390 (mapc (lambda (exclusive-group)
2391 (when (member new-param exclusive-group
)
2392 (mapcar (lambda (excluded-param)
2399 (setq output
(org-uniquify
2400 (cons new-param output
))))
2404 params results exports tangle noweb cache vars shebang comments padline
2413 (let ((name (if (listp (cdr pair
))
2415 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
2417 (intern (match-string 1 (cdr pair
)))))))
2421 (if (member name
(mapcar #'car vars
))
2423 (push name clearnames
)
2427 (unless (equal (car p
) name
) p
))
2430 (list (cons name pair
))))
2431 ;; if no name is given and we already have named variables
2432 ;; then assign to named variables in order
2433 (if (and vars
(nth variable-index vars
))
2434 (let ((name (car (nth variable-index vars
))))
2435 (push name clearnames
) ; clear out colnames
2438 (prog1 (setf (cddr (nth variable-index vars
))
2439 (concat (symbol-name name
) "=" (cdr pair
)))
2440 (incf variable-index
)))
2441 (error "Variable \"%s\" must be assigned a default value"
2444 (setq results
(funcall e-merge results-exclusive-groups
2447 (let ((r (cdr pair
)))
2448 (if (stringp r
) r
(eval r
)))))))
2451 (setq results
(funcall e-merge results-exclusive-groups
2453 (unless (or (member "both" exports
)
2454 (member "none" exports
)
2455 (member "code" exports
))
2456 (setq exports
(funcall e-merge exports-exclusive-groups
2457 exports
'("results"))))
2458 (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))
2461 (setq results
(funcall e-merge results-exclusive-groups
2463 (unless (or (member "both" exports
)
2464 (member "none" exports
)
2465 (member "code" exports
))
2466 (setq exports
(funcall e-merge exports-exclusive-groups
2467 exports
'("results"))))
2468 (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))
2470 (setq exports
(funcall e-merge exports-exclusive-groups
2471 exports
(split-string (cdr pair
)))))
2472 (:tangle
;; take the latest -- always overwrite
2473 (setq tangle
(or (list (cdr pair
)) tangle
)))
2475 (setq noweb
(funcall e-merge
2476 '(("yes" "no" "tangle" "no-export"
2477 "strip-export" "eval"))
2479 (split-string (or (cdr pair
) "")))))
2481 (setq cache
(funcall e-merge
'(("yes" "no")) cache
2482 (split-string (or (cdr pair
) "")))))
2484 (setq padline
(funcall e-merge
'(("yes" "no")) padline
2485 (split-string (or (cdr pair
) "")))))
2486 (:shebang
;; take the latest -- always overwrite
2487 (setq shebang
(or (list (cdr pair
)) shebang
)))
2489 (setq comments
(funcall e-merge
'(("yes" "no")) comments
2490 (split-string (or (cdr pair
) "")))))
2491 (t ;; replace: this covers e.g. :session
2492 (setq params
(cons pair
(assq-delete-all (car pair
) params
))))))
2495 (setq vars
(reverse vars
))
2496 (while vars
(setq params
(cons (cons :var
(cddr (pop vars
))) params
)))
2497 ;; clear out col-names and row-names for replaced variables
2502 (when (assoc param params
)
2503 (setf (cdr (assoc param params
))
2504 (org-remove-if (lambda (pair) (equal (car pair
) name
))
2505 (cdr (assoc param params
))))
2506 (setf params
(org-remove-if (lambda (pair) (and (equal (car pair
) param
)
2509 (list :colname-names
:rowname-names
)))
2513 (let ((key (intern (concat ":" (symbol-name hd
))))
2515 (setf params
(cons (cons key
(mapconcat 'identity val
" ")) params
))))
2516 '(results exports tangle noweb padline cache shebang comments
))
2519 (defvar org-babel-use-quick-and-dirty-noweb-expansion nil
2520 "Set to true to use regular expressions to expand noweb references.
2521 This results in much faster noweb reference expansion but does
2522 not properly allow code blocks to inherit the \":noweb-ref\"
2523 header argument from buffer or subtree wide properties.")
2525 (defun org-babel-noweb-p (params context
)
2526 "Check if PARAMS require expansion in CONTEXT.
2527 CONTEXT may be one of :tangle, :export or :eval."
2529 (intersect (lambda (as bs
)
2531 (if (member (car as
) bs
)
2533 (funcall intersect
(cdr as
) bs
))))))
2534 (funcall intersect
(case context
2535 (:tangle
'("yes" "tangle" "no-export" "strip-export"))
2536 (:eval
'("yes" "no-export" "strip-export" "eval"))
2538 (split-string (or (cdr (assoc :noweb params
)) "")))))
2540 (defun org-babel-expand-noweb-references (&optional info parent-buffer
)
2541 "Expand Noweb references in the body of the current source code block.
2543 For example the following reference would be replaced with the
2544 body of the source-code block named 'example-block'.
2548 Note that any text preceding the <<foo>> construct on a line will
2549 be interposed between the lines of the replacement text. So for
2550 example if <<foo>> is placed behind a comment, then the entire
2551 replacement text will also be commented.
2553 This function must be called from inside of the buffer containing
2554 the source-code block which holds BODY.
2556 In addition the following syntax can be used to insert the
2557 results of evaluating the source-code block named 'example-block'.
2561 Any optional arguments can be passed to example-block by placing
2562 the arguments inside the parenthesis following the convention
2563 defined by `org-babel-lob'. For example
2565 <<example-block(a=9)>>
2567 would set the value of argument \"a\" equal to \"9\". Note that
2568 these arguments are not evaluated in the current source-code
2569 block but are passed literally to the \"example-block\"."
2570 (let* ((parent-buffer (or parent-buffer
(current-buffer)))
2571 (info (or info
(org-babel-get-src-block-info 'light
)))
2574 (ob-nww-start org-babel-noweb-wrap-start
)
2575 (ob-nww-end org-babel-noweb-wrap-end
)
2576 (comment (string= "noweb" (cdr (assoc :comments
(nth 2 info
)))))
2577 (rx-prefix (concat "\\(" org-babel-src-name-regexp
"\\|"
2578 ":noweb-ref[ \t]+" "\\)"))
2580 (nb-add (lambda (text) (setq new-body
(concat new-body text
))))
2581 (c-wrap (lambda (text)
2583 (funcall (intern (concat lang
"-mode")))
2584 (comment-region (point) (progn (insert text
) (point)))
2585 (org-babel-trim (buffer-string)))))
2586 index source-name evaluate prefix
)
2588 (org-set-local 'org-babel-noweb-wrap-start ob-nww-start
)
2589 (org-set-local 'org-babel-noweb-wrap-end ob-nww-end
)
2590 (insert body
) (goto-char (point-min))
2591 (setq index
(point))
2592 (while (and (re-search-forward (org-babel-noweb-wrap) nil t
))
2593 (save-match-data (setf source-name
(match-string 1)))
2594 (save-match-data (setq evaluate
(string-match "\(.*\)" source-name
)))
2597 (buffer-substring (match-beginning 0)
2599 (beginning-of-line 1) (point)))))
2600 ;; add interval to new-body (removing noweb reference)
2601 (goto-char (match-beginning 0))
2602 (funcall nb-add
(buffer-substring index
(point)))
2603 (goto-char (match-end 0))
2604 (setq index
(point))
2607 (with-current-buffer parent-buffer
2610 (mapconcat ;; Interpose PREFIX between every line.
2614 (let ((raw (org-babel-ref-resolve source-name
)))
2615 (if (stringp raw
) raw
(format "%S" raw
)))
2617 ;; Retrieve from the library of babel.
2618 (nth 2 (assoc (intern source-name
)
2619 org-babel-library-of-babel
))
2620 ;; Return the contents of headlines literally.
2622 (when (org-babel-ref-goto-headline-id source-name
)
2623 (org-babel-ref-headline-body)))
2624 ;; Find the expansion of reference in this buffer.
2625 (let ((rx (concat rx-prefix source-name
"[ \t\n]"))
2628 (goto-char (point-min))
2629 (if org-babel-use-quick-and-dirty-noweb-expansion
2630 (while (re-search-forward rx nil t
)
2631 (let* ((i (org-babel-get-src-block-info 'light
))
2632 (body (org-babel-expand-noweb-references i
))
2633 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2636 (let ((cs (org-babel-tangle-comment-links i
)))
2637 (concat (funcall c-wrap
(car cs
)) "\n"
2639 (funcall c-wrap
(cadr cs
))))
2641 (setq expansion
(cons sep
(cons full expansion
)))))
2642 (org-babel-map-src-blocks nil
2643 (let ((i (org-babel-get-src-block-info 'light
)))
2644 (when (equal (or (cdr (assoc :noweb-ref
(nth 2 i
)))
2647 (let* ((body (org-babel-expand-noweb-references i
))
2648 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2651 (let ((cs (org-babel-tangle-comment-links i
)))
2652 (concat (funcall c-wrap
(car cs
)) "\n"
2654 (funcall c-wrap
(cadr cs
))))
2657 (cons sep
(cons full expansion
)))))))))
2659 (mapconcat #'identity
(nreverse (cdr expansion
)) "")))
2660 ;; Possibly raise an error if named block doesn't exist.
2661 (if (or org-babel-noweb-error-all-langs
2662 (member lang org-babel-noweb-error-langs
))
2664 (org-babel-noweb-wrap source-name
)
2665 "could not be resolved (see "
2666 "`org-babel-noweb-error-langs')"))
2668 "[\n\r]") (concat "\n" prefix
))))))
2669 (funcall nb-add
(buffer-substring index
(point-max))))
2672 (defun org-babel--script-escape-inner (str)
2673 (let (in-single in-double backslash out
)
2680 (setq backslash nil
)
2682 ((and in-single
(eq ch ?
'))
2683 ;; Escaped single quote inside single quoted string:
2684 ;; emit just a single quote, since we've changed the
2685 ;; outer quotes to double.
2688 ;; Escaped double quote
2690 ;; This should be interpreted as backslash+quote,
2691 ;; not an escape. Emit a three backslashes
2692 ;; followed by a quote (because one layer of
2693 ;; quoting will be stripped by `org-babel-read').
2694 (append (list ch ?
\\ ?
\\ ?
\\) out
)
2695 ;; Otherwise we are in a double-quoted string. Emit
2696 ;; a single escaped quote
2697 (append (list ch ?
\\) out
)))
2699 ;; Escaped backslash: emit a single escaped backslash
2700 (append (list ?
\\ ?
\\) out
))
2701 ;; Other: emit a quoted backslash followed by whatever
2702 ;; the character was (because one layer of quoting will
2703 ;; be stripped by `org-babel-read').
2704 (t (append (list ch ?
\\ ?
\\) out
))))
2706 (?\
[ (if (or in-double in-single
)
2709 (?\
] (if (or in-double in-single
)
2712 (?\
{ (if (or in-double in-single
)
2715 (?\
} (if (or in-double in-single
)
2718 (?
, (if (or in-double in-single
)
2719 (cons ?
, out
) (cons ?\s out
)))
2722 (setq in-single
(not in-single
)) (cons ?
\" out
)))
2724 (append (list ?
\" ?
\\) out
)
2725 (setq in-double
(not in-double
)) (cons ?
\" out
)))
2726 (?
\\ (unless (or in-single in-double
)
2727 (error "Can't handle backslash outside string in `org-babel-script-escape'"))
2730 (t (cons ch out
))))))
2731 (string-to-list str
))
2732 (when (or in-single in-double
)
2733 (error "Unterminated string in `org-babel-script-escape'"))
2734 (apply #'string
(reverse out
))))
2736 (defun org-babel-script-escape (str &optional force
)
2737 "Safely convert tables into elisp lists."
2738 (unless (stringp str
)
2739 (error "`org-babel-script-escape' expects a string"))
2742 ((and (> (length str
) 2)
2743 (or (and (string-equal "[" (substring str
0 1))
2744 (string-equal "]" (substring str -
1)))
2745 (and (string-equal "{" (substring str
0 1))
2746 (string-equal "}" (substring str -
1)))
2747 (and (string-equal "(" (substring str
0 1))
2748 (string-equal ")" (substring str -
1)))))
2750 (concat "'" (org-babel--script-escape-inner str
)))
2752 (and (> (length str
) 2)
2753 (or (and (string-equal "'" (substring str
0 1))
2754 (string-equal "'" (substring str -
1)))
2755 ;; We need to pass double-quoted strings
2756 ;; through the backslash-twiddling bits, even
2757 ;; though we don't need to change their
2759 (and (string-equal "\"" (substring str
0 1))
2760 (string-equal "\"" (substring str -
1))))))
2761 (org-babel--script-escape-inner str
))
2763 (condition-case nil
(org-babel-read escaped
) (error escaped
))))
2765 (defun org-babel-read (cell &optional inhibit-lisp-eval
)
2766 "Convert the string value of CELL to a number if appropriate.
2767 Otherwise if CELL looks like lisp (meaning it starts with a
2768 \"(\", \"'\", \"`\" or a \"[\") then read and evaluate it as
2769 lisp, otherwise return it unmodified as a string. Optional
2770 argument INHIBIT-LISP-EVAL inhibits lisp evaluation for
2771 situations in which is it not appropriate."
2772 (if (and (stringp cell
) (not (equal cell
"")))
2773 (or (org-babel-number-p cell
)
2774 (if (and (not inhibit-lisp-eval
)
2775 (or (member (substring cell
0 1) '("(" "'" "`" "["))
2776 (string= cell
"*this*")))
2778 (if (string= (substring cell
0 1) "\"")
2780 (progn (set-text-properties 0 (length cell
) nil cell
) cell
))))
2783 (defun org-babel-number-p (string)
2784 "If STRING represents a number return its value."
2785 (if (and (string-match "[0-9]+" string
)
2786 (string-match "^-?[0-9]*\\.?[0-9]*$" string
)
2787 (= (length (substring string
(match-beginning 0)
2790 (string-to-number string
)))
2792 (defun org-babel-import-elisp-from-file (file-name &optional separator
)
2793 "Read the results located at FILE-NAME into an elisp table.
2794 If the table is trivial, then return it as a scalar."
2796 (save-window-excursion
2800 (org-table-import file-name separator
)
2801 (delete-file file-name
)
2802 (setq result
(mapcar (lambda (row)
2803 (mapcar #'org-babel-string-read row
))
2804 (org-table-to-lisp))))
2805 (error (message "Error reading results: %s" err
) nil
)))
2806 (if (null (cdr result
)) ;; if result is trivial vector, then scalarize it
2807 (if (consp (car result
))
2808 (if (null (cdr (car result
)))
2814 (defun org-babel-string-read (cell)
2815 "Strip nested \"s from around strings."
2816 (org-babel-read (or (and (stringp cell
)
2817 (string-match "\\\"\\(.+\\)\\\"" cell
)
2818 (match-string 1 cell
))
2821 (defun org-babel-chomp (string &optional regexp
)
2822 "Strip a trailing space or carriage return from STRING.
2823 The default regexp used is \"[ \\f\\t\\n\\r\\v]\" but another one
2824 can be specified as the REGEXP argument."
2825 (let ((regexp (or regexp
"[ \f\t\n\r\v]")))
2826 (while (and (> (length string
) 0)
2827 (string-match regexp
(substring string -
1)))
2828 (setq string
(substring string
0 -
1)))
2831 (defun org-babel-trim (string &optional regexp
)
2832 "Strip a leading and trailing space or carriage return from STRING.
2833 Like `org-babel-chomp', but run on both the first and last
2834 character of the string."
2837 (org-babel-chomp (org-reverse-string string
) regexp
)) regexp
))
2839 (defun org-babel-tramp-handle-call-process-region
2840 (start end program
&optional delete buffer display
&rest args
)
2841 "Use Tramp to handle `call-process-region'.
2842 Fixes a bug in `tramp-handle-call-process-region'."
2843 (if (and (featurep 'tramp
) (file-remote-p default-directory
))
2844 (let ((tmpfile (tramp-compat-make-temp-file "")))
2845 (write-region start end tmpfile
)
2846 (when delete
(delete-region start end
))
2848 ;; (apply 'call-process program tmpfile buffer display args)
2850 (apply 'process-file program tmpfile buffer display args
)
2851 (delete-file tmpfile
)))
2852 ;; org-babel-call-process-region-original is the original emacs
2853 ;; definition. It is in scope from the let binding in
2854 ;; org-babel-execute-src-block
2855 (apply org-babel-call-process-region-original
2856 start end program delete buffer display args
)))
2858 (defun org-babel-local-file-name (file)
2859 "Return the local name component of FILE."
2860 (or (file-remote-p file
'localname
) file
))
2862 (defun org-babel-process-file-name (name &optional no-quote-p
)
2863 "Prepare NAME to be used in an external process.
2864 If NAME specifies a remote location, the remote portion of the
2865 name is removed, since in that case the process will be executing
2866 remotely. The file name is then processed by `expand-file-name'.
2867 Unless second argument NO-QUOTE-P is non-nil, the file name is
2868 additionally processed by `shell-quote-argument'"
2869 (let ((f (org-babel-local-file-name (expand-file-name name
))))
2870 (if no-quote-p f
(shell-quote-argument f
))))
2872 (defvar org-babel-temporary-directory
)
2873 (unless (or noninteractive
(boundp 'org-babel-temporary-directory
))
2874 (defvar org-babel-temporary-directory
2875 (or (and (boundp 'org-babel-temporary-directory
)
2876 (file-exists-p org-babel-temporary-directory
)
2877 org-babel-temporary-directory
)
2878 (make-temp-file "babel-" t
))
2879 "Directory to hold temporary files created to execute code blocks.
2880 Used by `org-babel-temp-file'. This directory will be removed on
2883 (defcustom org-babel-remote-temporary-directory
"/tmp/"
2884 "Directory to hold temporary files on remote hosts."
2888 (defmacro org-babel-result-cond
(result-params scalar-form
&rest table-forms
)
2889 "Call the code to parse raw string results according to RESULT-PARAMS."
2891 (debug (form form
&rest form
)))
2892 (org-with-gensyms (params)
2893 `(let ((,params
,result-params
))
2894 (unless (member "none" ,params
)
2895 (if (or (member "scalar" ,params
)
2896 (member "verbatim" ,params
)
2897 (member "html" ,params
)
2898 (member "code" ,params
)
2899 (member "pp" ,params
)
2900 (and (or (member "output" ,params
)
2901 (member "raw" ,params
)
2902 (member "org" ,params
)
2903 (member "drawer" ,params
))
2904 (not (member "table" ,params
))))
2907 (def-edebug-spec org-babel-result-cond
(form form body
))
2909 (defun org-babel-temp-file (prefix &optional suffix
)
2910 "Create a temporary file in the `org-babel-temporary-directory'.
2911 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2912 value of `temporary-file-directory' temporarily set to the value
2913 of `org-babel-temporary-directory'."
2914 (if (file-remote-p default-directory
)
2916 (concat (file-remote-p default-directory
)
2918 prefix org-babel-remote-temporary-directory
))))
2919 (make-temp-file prefix nil suffix
))
2920 (let ((temporary-file-directory
2921 (or (and (boundp 'org-babel-temporary-directory
)
2922 (file-exists-p org-babel-temporary-directory
)
2923 org-babel-temporary-directory
)
2924 temporary-file-directory
)))
2925 (make-temp-file prefix nil suffix
))))
2927 (defun org-babel-remove-temporary-directory ()
2928 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2929 (when (and (boundp 'org-babel-temporary-directory
)
2930 (file-exists-p org-babel-temporary-directory
))
2931 ;; taken from `delete-directory' in files.el
2934 (mapc (lambda (file)
2935 ;; This test is equivalent to
2936 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2937 ;; but more efficient
2938 (if (eq t
(car (file-attributes file
)))
2939 (delete-directory file
)
2940 (delete-file file
)))
2941 ;; We do not want to delete "." and "..".
2942 (directory-files org-babel-temporary-directory
'full
2943 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2944 (delete-directory org-babel-temporary-directory
))
2946 (message "Failed to remove temporary Org-babel directory %s"
2947 (if (boundp 'org-babel-temporary-directory
)
2948 org-babel-temporary-directory
2949 "[directory not defined]"))))))
2951 (add-hook 'kill-emacs-hook
'org-babel-remove-temporary-directory
)
2953 (defun org-babel-one-header-arg-safe-p (pair safe-list
)
2954 "Determine if the PAIR is a safe babel header arg according to SAFE-LIST.
2956 For the format of SAFE-LIST, see `org-babel-safe-header-args'."
2958 (keywordp (car pair
))
2959 (stringp (cdr pair
))
2961 (memq (car pair
) safe-list
)
2962 (let ((entry (assq (car pair
) safe-list
)))
2965 (cond ((functionp (cdr entry
))
2966 (funcall (cdr entry
) (cdr pair
)))
2967 ((listp (cdr entry
))
2968 (member (cdr pair
) (cdr entry
)))
2971 (defun org-babel-generate-file-param (src-name params
)
2972 "Calculate the filename for source block results.
2974 The directory is calculated from the :output-dir property of the
2975 source block; if not specified, use the current directory.
2977 If the source block has a #+NAME and the :file parameter does not
2978 contain any period characters, then the :file parameter is
2979 treated as an extension, and the output file name is the
2980 concatenation of the directory (as calculated above), the block
2981 name, a period, and the parameter value as a file extension.
2982 Otherwise, the :file parameter is treated as a full file name,
2983 and the output file name is the directory (as calculated above)
2984 plus the parameter value."
2985 (let* ((file-cons (assq :file params
))
2986 (file-ext-cons (assq :file-ext params
))
2987 (file-ext (cdr-safe file-ext-cons
))
2988 (dir (cdr-safe (assq :output-dir params
)))
2990 ;; create the output-dir if it does not exist
2992 (make-directory dir t
))
2994 ;; :file given; add :output-dir if given
2996 (setcdr file-cons
(concat (file-name-as-directory dir
) (cdr file-cons
))))
2997 ;; :file not given; compute from name and :file-ext if possible
2998 (when (and src-name file-ext
)
3000 (setq fname
(concat (file-name-as-directory (or dir
""))
3001 src-name
"." file-ext
))
3002 (setq fname
(concat src-name
"." file-ext
)))
3003 (setq params
(cons (cons :file fname
) params
))))
3006 ;;; Used by backends: R, Maxima, Octave.
3007 (defun org-babel-graphical-output-file (params)
3008 "File where a babel block should send graphical output, per PARAMS."
3009 (unless (assq :file params
)
3010 (if (assq :file-ext params
)
3011 (user-error ":file-ext given but no :file generated; did you forget to give a block a #+NAME?")
3012 (user-error "No :file header argument given; cannot create graphical result.")))
3013 (and (member "graphics" (cdr (assq :result-params params
)))
3014 (cdr (assq :file params
))))
3019 ;; generated-autoload-file: "org-loaddefs.el"
3022 ;;; ob-core.el ends here