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-remove-indentation
"org" (code &optional n
))
42 (declare-function org-reduce
"org" (CL-FUNC CL-SEQ
&rest CL-KEYS
))
43 (declare-function org-mark-ring-push
"org" (&optional pos buffer
))
44 (declare-function tramp-compat-make-temp-file
"tramp-compat"
45 (filename &optional dir-flag
))
46 (declare-function tramp-dissect-file-name
"tramp" (name &optional nodefault
))
47 (declare-function tramp-file-name-user
"tramp" (vec))
48 (declare-function tramp-file-name-host
"tramp" (vec))
49 (declare-function with-parsed-tramp-file-name
"tramp" (filename var
&rest body
))
50 (declare-function org-icompleting-read
"org" (&rest args
))
51 (declare-function org-edit-src-code
"org-src"
52 (&optional context code edit-buffer-name quietp
))
53 (declare-function org-edit-src-exit
"org-src" (&optional context
))
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-every
"org" (pred seq
))
102 (defgroup org-babel nil
103 "Code block evaluation and management in `org-mode' documents."
107 (defcustom org-confirm-babel-evaluate t
108 "Confirm before evaluation.
109 Require confirmation before interactively evaluating code
110 blocks in Org-mode buffers. The default value of this variable
111 is t, meaning confirmation is required for any code block
112 evaluation. This variable can be set to nil to inhibit any
113 future confirmation requests. This variable can also be set to a
114 function which takes two arguments the language of the code block
115 and the body of the code block. Such a function should then
116 return a non-nil value if the user should be prompted for
117 execution or nil if no prompt is required.
119 Warning: Disabling confirmation may result in accidental
120 evaluation of potentially harmful code. It may be advisable
121 remove code block execution from C-c C-c as further protection
122 against accidental code block evaluation. The
123 `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
124 remove code block execution from the C-c C-c keybinding."
127 :type
'(choice boolean function
))
128 ;; don't allow this variable to be changed through file settings
129 (put 'org-confirm-babel-evaluate
'safe-local-variable
(lambda (x) (eq x t
)))
131 (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
132 "Remove code block evaluation from the C-c C-c key binding."
137 (defcustom org-babel-results-keyword
"RESULTS"
138 "Keyword used to name results generated by code blocks.
139 Should be either RESULTS or NAME however any capitalization may
143 :package-version
'(Org .
"8.0")
146 (defcustom org-babel-noweb-wrap-start
"<<"
147 "String used to begin a noweb reference in a code block.
148 See also `org-babel-noweb-wrap-end'."
152 (defcustom org-babel-noweb-wrap-end
">>"
153 "String used to end a noweb reference in a code block.
154 See also `org-babel-noweb-wrap-start'."
158 (defcustom org-babel-inline-result-wrap
"=%s="
159 "Format string used to wrap inline results.
160 This string must include a \"%s\" which will be replaced by the results."
163 (put 'org-babel-inline-result-wrap
167 (string-match-p "%s" value
))))
169 (defun org-babel-noweb-wrap (&optional regexp
)
170 (concat org-babel-noweb-wrap-start
171 (or regexp
"\\([^ \t\n].+?[^ \t]\\|[^ \t\n]\\)")
172 org-babel-noweb-wrap-end
))
174 (defvar org-babel-src-name-regexp
175 "^[ \t]*#\\+name:[ \t]*"
176 "Regular expression used to match a source name line.")
178 (defvar org-babel-multi-line-header-regexp
179 "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
180 "Regular expression used to match multi-line header arguments.")
182 (defvar org-babel-src-name-w-name-regexp
183 (concat org-babel-src-name-regexp
185 org-babel-multi-line-header-regexp
187 "\\([^ ()\f\t\n\r\v]+\\)")
188 "Regular expression matching source name lines with a name.")
190 (defvar org-babel-src-block-regexp
192 ;; (1) indentation (2) lang
193 "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
195 "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
196 ;; (4) header arguments
199 "\\([^\000]*?\n\\)??[ \t]*#\\+end_src")
200 "Regexp used to identify code blocks.")
202 (defvar org-babel-inline-src-block-regexp
204 ;; (1) replacement target (2) lang
205 "\\(?:^\\|[^-[:alnum:]]\\)\\(src_\\([^ \f\t\n\r\v]+\\)"
206 ;; (3,4) (unused, headers)
207 "\\(\\|\\[\\(.*?\\)\\]\\)"
209 "{\\([^\f\n\r\v]+?\\)}\\)")
210 "Regexp used to identify inline src-blocks.")
212 (defun org-babel-get-header (params key
&optional others
)
213 "Select only header argument of type KEY from a list.
214 Optional argument OTHERS indicates that only the header that do
215 not match KEY should be returned."
218 (lambda (p) (when (funcall (if others
#'not
#'identity
) (eq (car p
) key
)) p
))
221 (defun org-babel-get-inline-src-block-matches ()
222 "Set match data if within body of an inline source block.
223 Returns non-nil if match-data set"
224 (let ((src-at-0-p (save-excursion
225 (beginning-of-line 1)
226 (string= "src" (thing-at-point 'word
))))
227 (first-line-p (= (line-beginning-position) (point-min)))
229 (let ((search-for (cond ((and src-at-0-p first-line-p
"src_"))
230 (first-line-p "[[:punct:] \t]src_")
231 (t "[[:punct:] \f\t\n\r\v]src_")))
232 (lower-limit (if first-line-p
234 (- (point-at-bol) 1))))
236 (when (or (and src-at-0-p
(bobp))
237 (and (re-search-forward "}" (point-at-eol) t
)
238 (re-search-backward search-for lower-limit t
)
240 (when (looking-at org-babel-inline-src-block-regexp
)
243 (defvar org-babel-inline-lob-one-liner-regexp
)
244 (defun org-babel-get-lob-one-liner-matches ()
245 "Set match data if on line of an lob one liner.
246 Returns non-nil if match-data set"
248 (unless (= (point) (point-at-bol)) ;; move before inline block
249 (re-search-backward "[ \f\t\n\r\v]" nil t
))
250 (if (looking-at org-babel-inline-lob-one-liner-regexp
)
254 (defun org-babel-get-src-block-info (&optional light
)
255 "Get information on the current source block.
257 Optional argument LIGHT does not resolve remote variable
258 references; a process which could likely result in the execution
259 of other code blocks.
262 (language body header-arguments-alist switches name indent block-head)."
263 (let ((case-fold-search t
) head info name indent
)
265 (if (setq head
(org-babel-where-is-src-block-head))
268 (setq info
(org-babel-parse-src-block-match))
269 (setq indent
(car (last info
)))
270 (setq info
(butlast info
))
271 (while (and (forward-line -
1)
272 (looking-at org-babel-multi-line-header-regexp
))
274 (org-babel-merge-params
276 (org-babel-parse-header-arguments (match-string 1)))))
277 (when (looking-at org-babel-src-name-w-name-regexp
)
278 (setq name
(org-no-properties (match-string 3)))))
279 ;; inline source block
280 (when (org-babel-get-inline-src-block-matches)
281 (setq head
(match-beginning 0))
282 (setq info
(org-babel-parse-inline-src-block-match))))
283 ;; resolve variable references and add summary parameters
284 (when (and info
(not light
))
285 (setf (nth 2 info
) (org-babel-process-params (nth 2 info
))))
286 (when info
(append info
(list name indent head
)))))
288 (defvar org-current-export-file
) ; dynamically bound
289 (defmacro org-babel-check-confirm-evaluate
(info &rest body
)
290 "Evaluate BODY with special execution confirmation variables set.
292 Specifically; NOEVAL will indicate if evaluation is allowed,
293 QUERY will indicate if a user query is required, CODE-BLOCK will
294 hold the language of the code block, and BLOCK-NAME will hold the
295 name of the code block."
296 (declare (indent defun
))
298 (lang block-body headers name head eval eval-no export eval-no-export
)
299 `(let* ((,lang
(nth 0 ,info
))
300 (,block-body
(nth 1 ,info
))
301 (,headers
(nth 2 ,info
))
302 (,name
(nth 4 ,info
))
303 (,head
(nth 6 ,info
))
304 (,eval
(or (cdr (assoc :eval
,headers
))
305 (when (assoc :noeval
,headers
) "no")))
306 (,eval-no
(or (equal ,eval
"no")
307 (equal ,eval
"never")))
308 (,export
(org-bound-and-true-p org-current-export-file
))
309 (,eval-no-export
(and ,export
(or (equal ,eval
"no-export")
310 (equal ,eval
"never-export"))))
311 (noeval (or ,eval-no
,eval-no-export
))
312 (query (or (equal ,eval
"query")
313 (and ,export
(equal ,eval
"query-export"))
314 (if (functionp org-confirm-babel-evaluate
)
317 (funcall org-confirm-babel-evaluate
319 org-confirm-babel-evaluate
)))
320 (code-block (if ,info
(format " %s " ,lang
) " "))
321 (block-name (if ,name
(format " (%s) " ,name
) " ")))
324 (defsubst org-babel-check-evaluate
(info)
325 "Check if code block INFO should be evaluated.
326 Do not query the user."
327 (org-babel-check-confirm-evaluate info
329 (message (format "Evaluation of this%scode-block%sis disabled."
330 code-block block-name
))))))
332 ;; dynamically scoped for asynchronous export
333 (defvar org-babel-confirm-evaluate-answer-no
)
335 (defsubst org-babel-confirm-evaluate
(info)
336 "Confirm evaluation of the code block INFO.
338 If the variable `org-babel-confirm-evaluate-answer-no' is bound
339 to a non-nil value, auto-answer with \"no\".
341 This query can also be suppressed by setting the value of
342 `org-confirm-babel-evaluate' to nil, in which case all future
343 interactive code block evaluations will proceed without any
344 confirmation from the user.
346 Note disabling confirmation may result in accidental evaluation
347 of potentially harmful code."
348 (org-babel-check-confirm-evaluate info
351 (and (not (org-bound-and-true-p
352 org-babel-confirm-evaluate-answer-no
))
354 (format "Evaluate this%scode block%son your system? "
355 code-block block-name
)))
356 (message (format "Evaluation of this%scode-block%sis aborted."
357 code-block block-name
)))))))
360 (defun org-babel-execute-safely-maybe ()
361 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
362 (org-babel-execute-maybe)))
364 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-execute-safely-maybe
)
367 (defun org-babel-execute-maybe ()
369 (or (org-babel-execute-src-block-maybe)
370 (org-babel-lob-execute-maybe)))
372 (defmacro org-babel-when-in-src-block
(&rest body
)
373 "Execute BODY if point is in a source block and return t.
375 Otherwise do nothing and return nil."
376 `(if (or (org-babel-where-is-src-block-head)
377 (org-babel-get-inline-src-block-matches))
383 (defun org-babel-execute-src-block-maybe ()
384 "Conditionally execute a source block.
385 Detect if this is context for a Babel src-block and if so
386 then run `org-babel-execute-src-block'."
388 (org-babel-when-in-src-block
389 (org-babel-eval-wipe-error-buffer)
390 (org-babel-execute-src-block current-prefix-arg
)))
393 (defun org-babel-view-src-block-info ()
394 "Display information on the current source block.
395 This includes header arguments, language and name, and is largely
396 a window into the `org-babel-get-src-block-info' function."
398 (let ((info (org-babel-get-src-block-info 'light
))
399 (full (lambda (it) (> (length it
) 0)))
400 (printf (lambda (fmt &rest args
) (princ (apply #'format fmt args
)))))
402 (with-help-window (help-buffer)
403 (let ((name (nth 4 info
))
405 (switches (nth 3 info
))
406 (header-args (nth 2 info
)))
407 (when name
(funcall printf
"Name: %s\n" name
))
408 (when lang
(funcall printf
"Lang: %s\n" lang
))
409 (when (funcall full switches
) (funcall printf
"Switches: %s\n" switches
))
410 (funcall printf
"Header Arguments:\n")
411 (dolist (pair (sort header-args
412 (lambda (a b
) (string< (symbol-name (car a
))
413 (symbol-name (car b
))))))
414 (when (funcall full
(cdr pair
))
415 (funcall printf
"\t%S%s\t%s\n"
417 (if (> (length (format "%S" (car pair
))) 7) "" "\t")
421 (defun org-babel-expand-src-block-maybe ()
422 "Conditionally expand a source block.
423 Detect if this is context for a org-babel src-block and if so
424 then run `org-babel-expand-src-block'."
426 (org-babel-when-in-src-block
427 (org-babel-expand-src-block current-prefix-arg
)))
430 (defun org-babel-load-in-session-maybe ()
431 "Conditionally load a source block in a session.
432 Detect if this is context for a org-babel src-block and if so
433 then run `org-babel-load-in-session'."
435 (org-babel-when-in-src-block
436 (org-babel-load-in-session current-prefix-arg
)))
438 (add-hook 'org-metaup-hook
'org-babel-load-in-session-maybe
)
441 (defun org-babel-pop-to-session-maybe ()
442 "Conditionally pop to a session.
443 Detect if this is context for a org-babel src-block and if so
444 then run `org-babel-switch-to-session'."
446 (org-babel-when-in-src-block
447 (org-babel-switch-to-session current-prefix-arg
)))
449 (add-hook 'org-metadown-hook
'org-babel-pop-to-session-maybe
)
451 (defconst org-babel-common-header-args-w-values
452 '((cache .
((no yes
)))
454 (colnames .
((nil no yes
)))
455 (comments .
((no link yes org both noweb
)))
457 (eval .
((never query
)))
458 (exports .
((code results both none
)))
462 (hlines .
((no yes
)))
463 (mkdirp .
((yes no
)))
466 (noweb .
((yes no tangle no-export strip-export
)))
469 (padline .
((yes no
)))
472 (results .
((file list vector table scalar verbatim
)
473 (raw html latex org code pp drawer
)
474 (replace silent none append prepend
)
476 (rownames .
((no yes
)))
480 (tangle .
((tangle yes no
:any
)))
481 (tangle-mode .
((#o755
#o555
#o444
:any
)))
485 (defconst org-babel-header-arg-names
486 (mapcar #'car org-babel-common-header-args-w-values
)
487 "Common header arguments used by org-babel.
488 Note that individual languages may define their own language
489 specific header arguments as well.")
491 (defconst org-babel-safe-header-args
492 '(:cache
:colnames
:comments
:exports
:epilogue
:hlines
:noeval
493 :noweb
:noweb-ref
:noweb-sep
:padline
:prologue
:rownames
494 :sep
:session
:tangle
:wrap
495 (:eval .
("never" "query"))
496 (:results .
(lambda (str) (not (string-match "file" str
)))))
497 "A list of safe header arguments for babel source blocks.
499 The list can have entries of the following forms:
500 - :ARG -> :ARG is always a safe header arg
501 - (:ARG . (VAL1 VAL2 ...)) -> :ARG is safe as a header arg if it is
502 `equal' to one of the VALs.
503 - (:ARG . FN) -> :ARG is safe as a header arg if the function FN
504 returns non-nil. FN is passed one
505 argument, the value of the header arg
508 (defmacro org-babel-header-args-safe-fn
(safe-list)
509 "Return a function that determines whether a list of header args are safe.
512 \(put 'org-babel-default-header-args 'safe-local-variable
513 (org-babel-header-args-safe-p org-babel-safe-header-args)
515 This allows org-babel languages to extend the list of safe values for
516 their `org-babel-default-header-args:foo' variable.
518 For the format of SAFE-LIST, see `org-babel-safe-header-args'."
524 (org-babel-one-header-arg-safe-p pair
,safe-list
)))
527 (defvar org-babel-default-header-args
528 '((:session .
"none") (:results .
"replace") (:exports .
"code")
529 (:cache .
"no") (:noweb .
"no") (:hlines .
"no") (:tangle .
"no"))
530 "Default arguments to use when evaluating a source block.")
531 (put 'org-babel-default-header-args
'safe-local-variable
532 (org-babel-header-args-safe-fn org-babel-safe-header-args
))
534 (defvar org-babel-default-inline-header-args
535 '((:session .
"none") (:results .
"replace")
536 (:exports .
"results") (:hlines .
"yes"))
537 "Default arguments to use when evaluating an inline source block.")
538 (put 'org-babel-default-inline-header-args
'safe-local-variable
539 (org-babel-header-args-safe-fn org-babel-safe-header-args
))
541 (defvar org-babel-data-names
'("tblname" "results" "name"))
543 (defvar org-babel-result-regexp
544 (concat "^[ \t]*#\\+"
545 (regexp-opt org-babel-data-names t
)
547 ;; FIXME The string below is `org-ts-regexp'
548 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
549 " \\)?\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*")
550 "Regular expression used to match result lines.
551 If the results are associated with a hash key then the hash will
552 be saved in the second match data.")
554 (defvar org-babel-result-w-name-regexp
555 (concat org-babel-result-regexp
556 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
558 (defvar org-babel-min-lines-for-block-output
10
559 "The minimum number of lines for block output.
560 If number of lines of output is equal to or exceeds this
561 value, the output is placed in a #+begin_example...#+end_example
562 block. Otherwise the output is marked as literal by inserting
563 colons at the starts of the lines. This variable only takes
564 effect if the :results output option is in effect.")
566 (defvar org-babel-noweb-error-langs nil
567 "Languages for which Babel will raise literate programming errors.
568 List of languages for which errors should be raised when the
569 source code block satisfying a noweb reference in this language
570 can not be resolved.")
572 (defvar org-babel-hash-show
4
573 "Number of initial characters to show of a hidden results hash.")
575 (defvar org-babel-hash-show-time nil
576 "Non-nil means show the time the code block was evaluated in the result hash.")
578 (defvar org-babel-after-execute-hook nil
579 "Hook for functions to be called after `org-babel-execute-src-block'")
581 (defun org-babel-named-src-block-regexp-for-name (name)
582 "This generates a regexp used to match a src block named NAME."
583 (concat org-babel-src-name-regexp
(regexp-quote name
)
584 "[ \t(]*[\r\n]\\(?:^#.*[\r\n]\\)*"
585 (substring org-babel-src-block-regexp
1)))
587 (defun org-babel-named-data-regexp-for-name (name)
588 "This generates a regexp used to match data named NAME."
589 (concat org-babel-result-regexp
(regexp-quote name
) "\\([ \t]\\|$\\)"))
592 (defvar call-process-region
)
593 (defvar org-babel-current-src-block-location nil
594 "Marker pointing to the src block currently being executed.
595 This may also point to a call line or an inline code block. If
596 multiple blocks are being executed (e.g., in chained execution
597 through use of the :var header argument) this marker points to
598 the outer-most code block.")
601 (defun org-babel-execute-src-block (&optional arg info params
)
602 "Execute the current source code block.
603 Insert the results of execution into the buffer. Source code
604 execution and the collection and formatting of results can be
605 controlled through a variety of header arguments.
607 With prefix argument ARG, force re-execution even if an existing
608 result cached in the buffer would otherwise have been returned.
610 Optionally supply a value for INFO in the form returned by
611 `org-babel-get-src-block-info'.
613 Optionally supply a value for PARAMS which will be merged with
614 the header arguments specified at the front of the source code
617 (let* ((org-babel-current-src-block-location
618 (or org-babel-current-src-block-location
620 (org-babel-where-is-src-block-head)
622 (and (org-babel-get-inline-src-block-matches)
623 (match-beginning 0))))
626 (org-babel-get-src-block-info)))
627 (merged-params (org-babel-merge-params (nth 2 info
) params
)))
628 (when (org-babel-check-evaluate
629 (let ((i info
)) (setf (nth 2 i
) merged-params
) i
))
630 (let* ((params (if params
631 (org-babel-process-params merged-params
)
633 (cachep (and (not arg
) (cdr (assoc :cache params
))
634 (string= "yes" (cdr (assoc :cache params
)))))
635 (new-hash (when cachep
(org-babel-sha1-hash info
)))
636 (old-hash (when cachep
(org-babel-current-result-hash)))
637 (cache-current-p (and (not arg
) new-hash
638 (equal new-hash old-hash
))))
641 (save-excursion ;; return cached result
642 (goto-char (org-babel-where-is-src-block-result nil info
))
643 (end-of-line 1) (forward-char 1)
644 (let ((result (org-babel-read-result)))
645 (message (replace-regexp-in-string
646 "%" "%%" (format "%S" result
))) result
)))
647 ((org-babel-confirm-evaluate
648 (let ((i info
)) (setf (nth 2 i
) merged-params
) i
))
649 (let* ((lang (nth 0 info
))
650 (result-params (cdr (assoc :result-params params
)))
651 (body (setf (nth 1 info
)
652 (if (org-babel-noweb-p params
:eval
)
653 (org-babel-expand-noweb-references info
)
655 (dir (cdr (assoc :dir params
)))
657 (or (and dir
(file-name-as-directory (expand-file-name dir
)))
659 (org-babel-call-process-region-original ;; for tramp handler
660 (or (org-bound-and-true-p
661 org-babel-call-process-region-original
)
662 (symbol-function 'call-process-region
)))
663 (indent (nth 5 info
))
666 (let ((call-process-region
668 (apply 'org-babel-tramp-handle-call-process-region
672 (let ((f (intern (concat "org-babel-execute:" f
))))
673 (when (fboundp f
) f
)))))
675 (or (funcall lang-check lang
)
678 (cdr (assoc lang org-src-lang-modes
))))
679 (error "No org-babel-execute function for %s!"
681 (message "executing %s code block%s..."
683 (if (nth 4 info
) (format " (%s)" (nth 4 info
)) ""))
684 (if (member "none" result-params
)
686 (funcall cmd body params
)
687 (message "result silenced")
690 (let ((result (funcall cmd body params
)))
691 (if (and (eq (cdr (assoc :result-type params
))
693 (or (member "vector" result-params
)
694 (member "table" result-params
))
695 (not (listp result
)))
696 (list (list result
)) result
)))
697 ;; If non-empty result and :file then write to :file.
698 (when (cdr (assoc :file params
))
700 (with-temp-file (cdr (assoc :file params
))
702 (org-babel-format-result
703 result
(cdr (assoc :sep
(nth 2 info
)))))))
704 (setq result
(cdr (assoc :file params
))))
705 ;; Possibly perform post process provided its appropriate.
706 (when (cdr (assoc :post params
))
707 (let ((*this
* (if (cdr (assoc :file params
))
708 (org-babel-result-to-file
709 (cdr (assoc :file params
))
710 (when (assoc :file-desc params
)
711 (or (cdr (assoc :file-desc params
))
714 (setq result
(org-babel-ref-resolve
715 (cdr (assoc :post params
))))
716 (when (cdr (assoc :file params
))
718 (remove "file" result-params
)))))
719 (org-babel-insert-result
720 result result-params info new-hash indent lang
))
721 (run-hooks 'org-babel-after-execute-hook
)
723 (setq call-process-region
724 'org-babel-call-process-region-original
)))))))))
726 (defun org-babel-expand-body:generic
(body params
&optional var-lines
)
727 "Expand BODY with PARAMS.
728 Expand a block of code with org-babel according to its header
729 arguments. This generic implementation of body expansion is
730 called for languages which have not defined their own specific
731 org-babel-expand-body:lang function."
732 (let ((pro (cdr (assoc :prologue params
)))
733 (epi (cdr (assoc :epilogue params
))))
734 (mapconcat #'identity
735 (append (when pro
(list pro
))
738 (when epi
(list epi
)))
742 (defun org-babel-expand-src-block (&optional arg info params
)
743 "Expand the current source code block.
744 Expand according to the source code block's header
745 arguments and pop open the results in a preview buffer."
747 (let* ((info (or info
(org-babel-get-src-block-info)))
749 (params (setf (nth 2 info
)
750 (sort (org-babel-merge-params (nth 2 info
) params
)
751 (lambda (el1 el2
) (string< (symbol-name (car el1
))
752 (symbol-name (car el2
)))))))
753 (body (setf (nth 1 info
)
754 (if (org-babel-noweb-p params
:eval
)
755 (org-babel-expand-noweb-references info
) (nth 1 info
))))
756 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
757 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
760 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
761 (org-babel-expand-body:generic
762 body params
(and (fboundp assignments-cmd
)
763 (funcall assignments-cmd params
))))))
764 (if (org-called-interactively-p 'any
)
767 (concat "*Org-Babel Preview " (buffer-name) "[ " lang
" ]*"))
770 (defun org-babel-edit-distance (s1 s2
)
771 "Return the edit (levenshtein) distance between strings S1 S2."
772 (let* ((l1 (length s1
))
774 (dist (vconcat (mapcar (lambda (_) (make-vector (1+ l2
) nil
))
775 (number-sequence 1 (1+ l1
)))))
776 (in (lambda (i j
) (aref (aref dist i
) j
))))
777 (setf (aref (aref dist
0) 0) 0)
778 (dolist (j (number-sequence 1 l2
))
779 (setf (aref (aref dist
0) j
) j
))
780 (dolist (i (number-sequence 1 l1
))
781 (setf (aref (aref dist i
) 0) i
)
782 (dolist (j (number-sequence 1 l2
))
783 (setf (aref (aref dist i
) j
)
785 (1+ (funcall in
(1- i
) j
))
786 (1+ (funcall in i
(1- j
)))
787 (+ (if (equal (aref s1
(1- i
)) (aref s2
(1- j
))) 0 1)
788 (funcall in
(1- i
) (1- j
)))))))
791 (defun org-babel-combine-header-arg-lists (original &rest others
)
792 "Combine a number of lists of header argument names and arguments."
793 (let ((results (copy-sequence original
)))
794 (dolist (new-list others
)
795 (dolist (arg-pair new-list
)
796 (let ((header (car arg-pair
))
797 (args (cdr arg-pair
)))
799 (cons arg-pair
(org-remove-if
800 (lambda (pair) (equal header
(car pair
)))
805 (defun org-babel-check-src-block ()
806 "Check for misspelled header arguments in the current code block."
808 ;; TODO: report malformed code block
809 ;; TODO: report incompatible combinations of header arguments
810 ;; TODO: report uninitialized variables
811 (let ((too-close 2) ;; <- control closeness to report potential match
812 (names (mapcar #'symbol-name org-babel-header-arg-names
)))
813 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg
)) 1))
814 (and (org-babel-where-is-src-block-head)
815 (org-babel-parse-header-arguments
817 (match-string 4))))))
819 (when (and (not (string= header name
))
820 (<= (org-babel-edit-distance header name
) too-close
)
821 (not (member header names
)))
822 (error "Supplied header \"%S\" is suspiciously close to \"%S\""
824 (message "No suspicious header arguments found.")))
827 (defun org-babel-insert-header-arg (&optional header-arg value
)
828 "Insert a header argument selecting from lists of common args and values."
830 (let* ((info (org-babel-get-src-block-info 'light
))
833 (lang-headers (intern (concat "org-babel-header-args:" lang
)))
834 (headers (org-babel-combine-header-arg-lists
835 org-babel-common-header-args-w-values
836 (when (boundp lang-headers
) (eval lang-headers
))))
837 (header-arg (or header-arg
838 (org-icompleting-read
841 (lambda (header-spec) (symbol-name (car header-spec
)))
843 (vals (cdr (assoc (intern header-arg
) headers
)))
847 (read-from-minibuffer "value: "))
851 (let ((arg (org-icompleting-read
854 (mapcar #'symbol-name group
)))))
855 (if (and arg
(not (string= "default" arg
)))
861 (goto-char (point-at-eol))
862 (unless (= (char-before (point)) ?\
) (insert " "))
863 (insert ":" header-arg
) (when value
(insert " " value
)))))
865 ;; Add support for completing-read insertion of header arguments after ":"
866 (defun org-babel-header-arg-expand ()
867 "Call `org-babel-enter-header-arg-w-completion' in appropriate contexts."
868 (when (and (equal (char-before) ?\
:) (org-babel-where-is-src-block-head))
869 (org-babel-enter-header-arg-w-completion (match-string 2))))
871 (defun org-babel-enter-header-arg-w-completion (&optional lang
)
872 "Insert header argument appropriate for LANG with completion."
873 (let* ((lang-headers-var (intern (concat "org-babel-header-args:" lang
)))
874 (lang-headers (when (boundp lang-headers-var
) (eval lang-headers-var
)))
875 (headers-w-values (org-babel-combine-header-arg-lists
876 org-babel-common-header-args-w-values lang-headers
))
877 (headers (mapcar #'symbol-name
(mapcar #'car headers-w-values
)))
878 (header (org-completing-read "Header Arg: " headers
))
879 (args (cdr (assoc (intern header
) headers-w-values
)))
880 (arg (when (and args
(listp args
))
882 (format "%s: " header
)
883 (mapcar #'symbol-name
(apply #'append args
))))))
884 (insert (concat header
" " (or arg
"")))
887 (add-hook 'org-tab-first-hook
'org-babel-header-arg-expand
)
890 (defun org-babel-load-in-session (&optional arg info
)
891 "Load the body of the current source-code block.
892 Evaluate the header arguments for the source block before
893 entering the session. After loading the body this pops open the
896 (let* ((info (or info
(org-babel-get-src-block-info)))
898 (params (nth 2 info
))
900 (user-error "No src code block at point")
902 (if (org-babel-noweb-p params
:eval
)
903 (org-babel-expand-noweb-references info
)
905 (session (cdr (assoc :session params
)))
906 (dir (cdr (assoc :dir params
)))
908 (or (and dir
(file-name-as-directory dir
)) default-directory
))
909 (cmd (intern (concat "org-babel-load-session:" lang
))))
910 (unless (fboundp cmd
)
911 (error "No org-babel-load-session function for %s!" lang
))
912 (pop-to-buffer (funcall cmd session body params
))
916 (defun org-babel-initiate-session (&optional arg info
)
917 "Initiate session for current code block.
918 If called with a prefix argument then resolve any variable
919 references in the header arguments and assign these variables in
920 the session. Copy the body of the code block to the kill ring."
922 (let* ((info (or info
(org-babel-get-src-block-info (not arg
))))
925 (params (nth 2 info
))
926 (session (cdr (assoc :session params
)))
927 (dir (cdr (assoc :dir params
)))
929 (or (and dir
(file-name-as-directory dir
)) default-directory
))
930 (init-cmd (intern (format "org-babel-%s-initiate-session" lang
)))
931 (prep-cmd (intern (concat "org-babel-prep-session:" lang
))))
932 (if (and (stringp session
) (string= session
"none"))
933 (error "This block is not using a session!"))
934 (unless (fboundp init-cmd
)
935 (error "No org-babel-initiate-session function for %s!" lang
))
936 (with-temp-buffer (insert (org-babel-trim body
))
937 (copy-region-as-kill (point-min) (point-max)))
939 (unless (fboundp prep-cmd
)
940 (error "No org-babel-prep-session function for %s!" lang
))
941 (funcall prep-cmd session params
))
942 (funcall init-cmd session params
)))
945 (defun org-babel-switch-to-session (&optional arg info
)
946 "Switch to the session of the current code block.
947 Uses `org-babel-initiate-session' to start the session. If called
948 with a prefix argument then this is passed on to
949 `org-babel-initiate-session'."
951 (pop-to-buffer (org-babel-initiate-session arg info
))
954 (defalias 'org-babel-pop-to-session
'org-babel-switch-to-session
)
956 (defvar org-src-window-setup
)
959 (defun org-babel-switch-to-session-with-code (&optional arg info
)
960 "Switch to code buffer and display session."
964 (let ((other-window-buffer (window-buffer (next-window))))
965 (set-window-buffer (next-window) (current-buffer))
966 (set-window-buffer (selected-window) other-window-buffer
))
968 (info (org-babel-get-src-block-info))
969 (org-src-window-setup 'reorganize-frame
))
971 (org-babel-switch-to-session arg info
))
973 (funcall swap-windows
)))
976 (defmacro org-babel-do-in-edit-buffer
(&rest body
)
977 "Evaluate BODY in edit buffer if there is a code block at point.
978 Return t if a code block was found at point, nil otherwise."
979 `(let ((org-src-window-setup 'switch-invisibly
))
980 (when (and (org-babel-where-is-src-block-head)
981 (org-edit-src-code nil nil nil
))
982 (unwind-protect (progn ,@body
)
983 (if (org-bound-and-true-p org-edit-src-from-org-mode
)
984 (org-edit-src-exit)))
986 (def-edebug-spec org-babel-do-in-edit-buffer
(body))
988 (defun org-babel-do-key-sequence-in-edit-buffer (key)
989 "Read key sequence and execute the command in edit buffer.
990 Enter a key sequence to be executed in the language major-mode
991 edit buffer. For example, TAB will alter the contents of the
992 Org-mode code block according to the effect of TAB in the
993 language major-mode buffer. For languages that support
994 interactive sessions, this can be used to send code from the Org
995 buffer to the session for evaluation using the native major-mode
996 evaluation mechanisms."
997 (interactive "kEnter key-sequence to execute in edit buffer: ")
998 (org-babel-do-in-edit-buffer
1000 (key-binding (or key
(read-key-sequence nil
))))))
1002 (defvar org-bracket-link-regexp
)
1004 (defun org-babel-active-location-p ()
1005 (memq (car (save-match-data (org-element-context)))
1006 '(babel-call inline-babel-call inline-src-block src-block
)))
1009 (defun org-babel-open-src-block-result (&optional re-run
)
1010 "If `point' is on a src block then open the results of the
1011 source code block, otherwise return nil. With optional prefix
1012 argument RE-RUN the source-code block is evaluated even if
1013 results already exist."
1015 (let ((info (org-babel-get-src-block-info 'light
)))
1018 ;; go to the results, if there aren't any then run the block
1019 (goto-char (or (and (not re-run
) (org-babel-where-is-src-block-result))
1020 (progn (org-babel-execute-src-block)
1021 (org-babel-where-is-src-block-result))))
1023 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
1025 (if (looking-at org-bracket-link-regexp
)
1028 (let ((r (org-babel-format-result
1029 (org-babel-read-result) (cdr (assoc :sep
(nth 2 info
))))))
1030 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
1031 (delete-region (point-min) (point-max))
1036 (defmacro org-babel-map-src-blocks
(file &rest body
)
1037 "Evaluate BODY forms on each source-block in FILE.
1038 If FILE is nil evaluate BODY forms on source blocks in current
1039 buffer. During evaluation of BODY the following local variables
1040 are set relative to the currently matched code block.
1042 full-block ------- string holding the entirety of the code block
1043 beg-block -------- point at the beginning of the code block
1044 end-block -------- point at the end of the matched code block
1045 lang ------------- string holding the language of the code block
1046 beg-lang --------- point at the beginning of the lang
1047 end-lang --------- point at the end of the lang
1048 switches --------- string holding the switches
1049 beg-switches ----- point at the beginning of the switches
1050 end-switches ----- point at the end of the switches
1051 header-args ------ string holding the header-args
1052 beg-header-args -- point at the beginning of the header-args
1053 end-header-args -- point at the end of the header-args
1054 body ------------- string holding the body of the code block
1055 beg-body --------- point at the beginning of the body
1056 end-body --------- point at the end of the body"
1057 (declare (indent 1))
1058 (let ((tempvar (make-symbol "file")))
1059 `(let* ((,tempvar
,file
)
1060 (visited-p (or (null ,tempvar
)
1061 (get-file-buffer (expand-file-name ,tempvar
))))
1062 (point (point)) to-be-removed
)
1063 (save-window-excursion
1064 (when ,tempvar
(find-file ,tempvar
))
1065 (setq to-be-removed
(current-buffer))
1066 (goto-char (point-min))
1067 (while (re-search-forward org-babel-src-block-regexp nil t
)
1068 (when (org-babel-active-location-p)
1069 (goto-char (match-beginning 0))
1070 (let ((full-block (match-string 0))
1071 (beg-block (match-beginning 0))
1072 (end-block (match-end 0))
1073 (lang (match-string 2))
1074 (beg-lang (match-beginning 2))
1075 (end-lang (match-end 2))
1076 (switches (match-string 3))
1077 (beg-switches (match-beginning 3))
1078 (end-switches (match-end 3))
1079 (header-args (match-string 4))
1080 (beg-header-args (match-beginning 4))
1081 (end-header-args (match-end 4))
1082 (body (match-string 5))
1083 (beg-body (match-beginning 5))
1084 (end-body (match-end 5)))
1086 (goto-char end-block
)))))
1087 (unless visited-p
(kill-buffer to-be-removed
))
1088 (goto-char point
))))
1089 (def-edebug-spec org-babel-map-src-blocks
(form body
))
1092 (defmacro org-babel-map-inline-src-blocks
(file &rest body
)
1093 "Evaluate BODY forms on each inline source-block in FILE.
1094 If FILE is nil evaluate BODY forms on source blocks in current
1096 (declare (indent 1))
1097 (let ((tempvar (make-symbol "file")))
1098 `(let* ((,tempvar
,file
)
1099 (visited-p (or (null ,tempvar
)
1100 (get-file-buffer (expand-file-name ,tempvar
))))
1101 (point (point)) to-be-removed
)
1102 (save-window-excursion
1103 (when ,tempvar
(find-file ,tempvar
))
1104 (setq to-be-removed
(current-buffer))
1105 (goto-char (point-min))
1106 (while (re-search-forward org-babel-inline-src-block-regexp nil t
)
1107 (when (org-babel-active-location-p)
1108 (goto-char (match-beginning 1))
1109 (save-match-data ,@body
))
1110 (goto-char (match-end 0))))
1111 (unless visited-p
(kill-buffer to-be-removed
))
1112 (goto-char point
))))
1113 (def-edebug-spec org-babel-map-inline-src-blocks
(form body
))
1115 (defvar org-babel-lob-one-liner-regexp
)
1118 (defmacro org-babel-map-call-lines
(file &rest body
)
1119 "Evaluate BODY forms on each call line in FILE.
1120 If FILE is nil evaluate BODY forms on source blocks in current
1122 (declare (indent 1))
1123 (let ((tempvar (make-symbol "file")))
1124 `(let* ((,tempvar
,file
)
1125 (visited-p (or (null ,tempvar
)
1126 (get-file-buffer (expand-file-name ,tempvar
))))
1127 (point (point)) to-be-removed
)
1128 (save-window-excursion
1129 (when ,tempvar
(find-file ,tempvar
))
1130 (setq to-be-removed
(current-buffer))
1131 (goto-char (point-min))
1132 (while (re-search-forward org-babel-lob-one-liner-regexp nil t
)
1133 (when (org-babel-active-location-p)
1134 (goto-char (match-beginning 1))
1135 (save-match-data ,@body
))
1136 (goto-char (match-end 0))))
1137 (unless visited-p
(kill-buffer to-be-removed
))
1138 (goto-char point
))))
1139 (def-edebug-spec org-babel-map-call-lines
(form body
))
1142 (defmacro org-babel-map-executables
(file &rest body
)
1143 (declare (indent 1))
1144 (let ((tempvar (make-symbol "file"))
1145 (rx (make-symbol "rx")))
1146 `(let* ((,tempvar
,file
)
1147 (,rx
(concat "\\(" org-babel-src-block-regexp
1148 "\\|" org-babel-inline-src-block-regexp
1149 "\\|" org-babel-lob-one-liner-regexp
"\\)"))
1150 (visited-p (or (null ,tempvar
)
1151 (get-file-buffer (expand-file-name ,tempvar
))))
1152 (point (point)) to-be-removed
)
1153 (save-window-excursion
1154 (when ,tempvar
(find-file ,tempvar
))
1155 (setq to-be-removed
(current-buffer))
1156 (goto-char (point-min))
1157 (while (re-search-forward ,rx nil t
)
1158 (when (org-babel-active-location-p)
1159 (goto-char (match-beginning 1))
1160 (when (looking-at org-babel-inline-src-block-regexp
)
1162 (save-match-data ,@body
))
1163 (goto-char (match-end 0))))
1164 (unless visited-p
(kill-buffer to-be-removed
))
1165 (goto-char point
))))
1166 (def-edebug-spec org-babel-map-executables
(form body
))
1169 (defun org-babel-execute-buffer (&optional arg
)
1170 "Execute source code blocks in a buffer.
1171 Call `org-babel-execute-src-block' on every source block in
1172 the current buffer."
1174 (org-babel-eval-wipe-error-buffer)
1175 (org-save-outline-visibility t
1176 (org-babel-map-executables nil
1177 (if (looking-at org-babel-lob-one-liner-regexp
)
1178 (org-babel-lob-execute-maybe)
1179 (org-babel-execute-src-block arg
)))))
1182 (defun org-babel-execute-subtree (&optional arg
)
1183 "Execute source code blocks in a subtree.
1184 Call `org-babel-execute-src-block' on every source block in
1185 the current subtree."
1189 (org-narrow-to-subtree)
1190 (org-babel-execute-buffer arg
)
1194 (defun org-babel-sha1-hash (&optional info
)
1195 "Generate an sha1 hash based on the value of info."
1197 (let ((print-level nil
)
1198 (info (or info
(org-babel-get-src-block-info))))
1200 (sort (copy-sequence (nth 2 info
))
1201 (lambda (a b
) (string< (car a
) (car b
)))))
1202 (let* ((rm (lambda (lst)
1203 (dolist (p '("replace" "silent" "none"
1204 "append" "prepend"))
1205 (setq lst
(remove p lst
)))
1208 (let ((v (if (and (listp (cdr arg
)) (null (cddr arg
)))
1209 (copy-sequence (cdr arg
))
1211 (when (and v
(not (and (sequencep v
)
1215 ((and (listp v
) ; lists are sorted
1216 (member (car arg
) '(:result-params
)))
1217 (sort (funcall rm v
) #'string
<))
1218 ((and (stringp v
) ; strings are sorted
1219 (member (car arg
) '(:results
:exports
)))
1220 (mapconcat #'identity
(sort (funcall rm
(split-string v
))
1225 (params (nth 2 info
))
1226 (body (if (org-babel-noweb-p params
:eval
)
1227 (org-babel-expand-noweb-references info
) (nth 1 info
)))
1228 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
1229 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
1232 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
1233 (org-babel-expand-body:generic
1234 body params
(and (fboundp assignments-cmd
)
1235 (funcall assignments-cmd params
))))))
1236 (let* ((it (format "%s-%s"
1239 (delq nil
(mapcar (lambda (arg)
1240 (let ((normalized (funcall norm arg
)))
1242 (format "%S" normalized
))))
1246 (when (org-called-interactively-p 'interactive
) (message hash
))
1249 (defun org-babel-current-result-hash (&optional info
)
1250 "Return the current in-buffer hash."
1251 (org-babel-where-is-src-block-result nil info
)
1252 (org-no-properties (match-string 5)))
1254 (defun org-babel-set-current-result-hash (hash info
)
1255 "Set the current in-buffer hash to HASH."
1256 (org-babel-where-is-src-block-result nil info
)
1257 (save-excursion (goto-char (match-beginning 5))
1258 (mapc #'delete-overlay
(overlays-at (point)))
1259 (forward-char org-babel-hash-show
)
1260 (mapc #'delete-overlay
(overlays-at (point)))
1261 (replace-match hash nil nil nil
5)
1262 (goto-char (point-at-bol))
1263 (org-babel-hide-hash)))
1265 (defun org-babel-hide-hash ()
1266 "Hide the hash in the current results line.
1267 Only the initial `org-babel-hash-show' characters of the hash
1268 will remain visible."
1269 (add-to-invisibility-spec '(org-babel-hide-hash . t
))
1271 (when (and (re-search-forward org-babel-result-regexp nil t
)
1273 (let* ((start (match-beginning 5))
1274 (hide-start (+ org-babel-hash-show start
))
1276 (hash (match-string 5))
1278 (setq ov1
(make-overlay start hide-start
))
1279 (setq ov2
(make-overlay hide-start end
))
1280 (overlay-put ov2
'invisible
'org-babel-hide-hash
)
1281 (overlay-put ov1
'babel-hash hash
)))))
1283 (defun org-babel-hide-all-hashes ()
1284 "Hide the hash in the current buffer.
1285 Only the initial `org-babel-hash-show' characters of each hash
1286 will remain visible. This function should be called as part of
1287 the `org-mode-hook'."
1289 (while (and (not org-babel-hash-show-time
)
1290 (re-search-forward org-babel-result-regexp nil t
))
1291 (goto-char (match-beginning 0))
1292 (org-babel-hide-hash)
1293 (goto-char (match-end 0)))))
1294 (add-hook 'org-mode-hook
'org-babel-hide-all-hashes
)
1296 (defun org-babel-hash-at-point (&optional point
)
1297 "Return the value of the hash at POINT.
1298 The hash is also added as the last element of the kill ring.
1299 This can be called with C-c C-c."
1301 (let ((hash (car (delq nil
(mapcar
1302 (lambda (ol) (overlay-get ol
'babel-hash
))
1303 (overlays-at (or point
(point))))))))
1304 (when hash
(kill-new hash
) (message hash
))))
1305 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-hash-at-point
)
1307 (defun org-babel-result-hide-spec ()
1308 "Hide portions of results lines.
1309 Add `org-babel-hide-result' as an invisibility spec for hiding
1310 portions of results lines."
1311 (add-to-invisibility-spec '(org-babel-hide-result . t
)))
1312 (add-hook 'org-mode-hook
'org-babel-result-hide-spec
)
1314 (defvar org-babel-hide-result-overlays nil
1315 "Overlays hiding results.")
1317 (defun org-babel-result-hide-all ()
1318 "Fold all results in the current buffer."
1320 (org-babel-show-result-all)
1322 (while (re-search-forward org-babel-result-regexp nil t
)
1323 (save-excursion (goto-char (match-beginning 0))
1324 (org-babel-hide-result-toggle-maybe)))))
1326 (defun org-babel-show-result-all ()
1327 "Unfold all results in the current buffer."
1328 (mapc 'delete-overlay org-babel-hide-result-overlays
)
1329 (setq org-babel-hide-result-overlays nil
))
1332 (defun org-babel-hide-result-toggle-maybe ()
1333 "Toggle visibility of result at point."
1335 (let ((case-fold-search t
))
1337 (beginning-of-line 1)
1338 (looking-at org-babel-result-regexp
))
1339 (progn (org-babel-hide-result-toggle)
1340 t
) ;; to signal that we took action
1341 nil
))) ;; to signal that we did not
1343 (defun org-babel-hide-result-toggle (&optional force
)
1344 "Toggle the visibility of the current result."
1348 (if (re-search-forward org-babel-result-regexp nil t
)
1349 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
1351 (while (looking-at org-babel-multi-line-header-regexp
)
1353 (goto-char (- (org-babel-result-end) 1)) (point)))
1355 (if (memq t
(mapcar (lambda (overlay)
1356 (eq (overlay-get overlay
'invisible
)
1357 'org-babel-hide-result
))
1358 (overlays-at start
)))
1359 (if (or (not force
) (eq force
'off
))
1361 (when (member ov org-babel-hide-result-overlays
)
1362 (setq org-babel-hide-result-overlays
1363 (delq ov org-babel-hide-result-overlays
)))
1364 (when (eq (overlay-get ov
'invisible
)
1365 'org-babel-hide-result
)
1366 (delete-overlay ov
)))
1367 (overlays-at start
)))
1368 (setq ov
(make-overlay start end
))
1369 (overlay-put ov
'invisible
'org-babel-hide-result
)
1370 ;; make the block accessible to isearch
1372 ov
'isearch-open-invisible
1374 (when (member ov org-babel-hide-result-overlays
)
1375 (setq org-babel-hide-result-overlays
1376 (delq ov org-babel-hide-result-overlays
)))
1377 (when (eq (overlay-get ov
'invisible
)
1378 'org-babel-hide-result
)
1379 (delete-overlay ov
))))
1380 (push ov org-babel-hide-result-overlays
)))
1381 (error "Not looking at a result line"))))
1383 ;; org-tab-after-check-for-cycling-hook
1384 (add-hook 'org-tab-first-hook
'org-babel-hide-result-toggle-maybe
)
1385 ;; Remove overlays when changing major mode
1386 (add-hook 'org-mode-hook
1387 (lambda () (org-add-hook 'change-major-mode-hook
1388 'org-babel-show-result-all
'append
'local
)))
1390 (defvar org-file-properties
)
1391 (defun org-babel-params-from-properties (&optional lang
)
1392 "Retrieve parameters specified as properties.
1393 Return a list of association lists of source block params
1394 specified in the properties of the current outline entry."
1397 ;; DEPRECATED header arguments specified as separate property at
1398 ;; point of definition
1400 (org-babel-parse-multiple-vars
1403 (lambda (header-arg)
1404 (and (setq val
(org-entry-get (point) header-arg t
))
1405 (cons (intern (concat ":" header-arg
))
1406 (org-babel-read val
))))
1411 (org-babel-combine-header-arg-lists
1412 org-babel-common-header-args-w-values
1414 (setq sym
(intern (concat "org-babel-header-args:" lang
)))
1415 (and (boundp sym
) (eval sym
))))))))))
1416 ;; header arguments specified with the header-args property at
1418 (org-babel-parse-header-arguments
1419 (org-entry-get org-babel-current-src-block-location
1420 "header-args" 'inherit
))
1421 (when lang
;; language-specific header arguments at point of call
1422 (org-babel-parse-header-arguments
1423 (org-entry-get org-babel-current-src-block-location
1424 (concat "header-args:" lang
) 'inherit
))))))
1426 (defvar org-src-preserve-indentation
)
1427 (defun org-babel-parse-src-block-match ()
1428 "Parse the results from a match of the `org-babel-src-block-regexp'."
1429 (let* ((block-indentation (length (match-string 1)))
1430 (lang (org-no-properties (match-string 2)))
1431 (lang-headers (intern (concat "org-babel-default-header-args:" lang
)))
1432 (switches (match-string 3))
1433 (body (org-no-properties
1434 (let* ((body (match-string 5))
1435 (sub-length (- (length body
) 1)))
1436 (if (and (> sub-length
0)
1437 (string= "\n" (substring body sub-length
)))
1438 (substring body
0 sub-length
)
1440 (preserve-indentation (or org-src-preserve-indentation
1442 (string-match "-i\\>" switches
)))))
1444 ;; get block body less properties, protective commas, and indentation
1447 (insert (org-unescape-code-in-string body
))
1448 (unless preserve-indentation
(org-do-remove-indentation))
1450 (apply #'org-babel-merge-params
1451 org-babel-default-header-args
1452 (when (boundp lang-headers
) (eval lang-headers
))
1454 (org-babel-params-from-properties lang
)
1455 (list (org-babel-parse-header-arguments
1456 (org-no-properties (or (match-string 4) ""))))))
1458 block-indentation
)))
1460 (defun org-babel-parse-inline-src-block-match ()
1461 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
1462 (let* ((lang (org-no-properties (match-string 2)))
1463 (lang-headers (intern (concat "org-babel-default-header-args:" lang
))))
1465 (org-unescape-code-in-string (org-no-properties (match-string 5)))
1466 (apply #'org-babel-merge-params
1467 org-babel-default-inline-header-args
1468 (if (boundp lang-headers
) (eval lang-headers
) nil
)
1470 (org-babel-params-from-properties lang
)
1471 (list (org-babel-parse-header-arguments
1472 (org-no-properties (or (match-string 4) ""))))))
1475 (defun org-babel-balanced-split (string alts
)
1476 "Split STRING on instances of ALTS.
1477 ALTS is a cons of two character options where each option may be
1478 either the numeric code of a single character or a list of
1479 character alternatives. For example to split on balanced
1480 instances of \"[ \t]:\" set ALTS to '((32 9) . 58)."
1481 (let* ((matches (lambda (ch spec
) (if (listp spec
) (member ch spec
) (equal spec ch
))))
1482 (matched (lambda (ch last
)
1484 (and (funcall matches ch
(cdr alts
))
1485 (funcall matches last
(car alts
)))
1486 (funcall matches ch alts
))))
1487 (balance 0) (last 0)
1489 (mapc (lambda (ch) ; split on [], (), "" balanced instances of [ \t]:
1490 (setq balance
(+ balance
1491 (cond ((or (equal 91 ch
) (equal 40 ch
)) 1)
1492 ((or (equal 93 ch
) (equal 41 ch
)) -
1)
1494 (when (and (equal 34 ch
) (not (equal 92 last
)))
1495 (setq quote
(not quote
)))
1496 (setq partial
(cons ch partial
))
1497 (when (and (= balance
0) (not quote
) (funcall matched ch last
))
1498 (setq lst
(cons (apply #'string
(nreverse
1505 (string-to-list string
))
1506 (nreverse (cons (apply #'string
(nreverse partial
)) lst
))))
1508 (defun org-babel-join-splits-near-ch (ch list
)
1509 "Join splits where \"=\" is on either end of the split."
1510 (let ((last= (lambda (str) (= ch
(aref str
(1- (length str
))))))
1511 (first= (lambda (str) (= ch
(aref str
0)))))
1513 (org-reduce (lambda (acc el
)
1514 (let ((head (car acc
)))
1515 (if (and head
(or (funcall last
= head
) (funcall first
= el
)))
1516 (cons (concat head el
) (cdr acc
))
1518 list
:initial-value nil
))))
1520 (defun org-babel-parse-header-arguments (arg-string)
1521 "Parse a string of header arguments returning an alist."
1522 (when (> (length arg-string
) 0)
1523 (org-babel-parse-multiple-vars
1528 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1530 (cons (intern (match-string 1 arg
))
1531 (org-babel-read (org-babel-chomp (match-string 2 arg
))))
1532 (cons (intern (org-babel-chomp arg
)) nil
)))
1533 (let ((raw (org-babel-balanced-split arg-string
'((32 9) .
58))))
1534 (cons (car raw
) (mapcar (lambda (r) (concat ":" r
)) (cdr raw
)))))))))
1536 (defun org-babel-parse-multiple-vars (header-arguments)
1537 "Expand multiple variable assignments behind a single :var keyword.
1539 This allows expression of multiple variables with one :var as
1542 #+PROPERTY: var foo=1, bar=2"
1544 (mapc (lambda (pair)
1545 (if (eq (car pair
) :var
)
1546 (mapcar (lambda (v) (push (cons :var
(org-babel-trim v
)) results
))
1547 (org-babel-join-splits-near-ch
1548 61 (org-babel-balanced-split (cdr pair
) 32)))
1549 (push pair results
)))
1551 (nreverse results
)))
1553 (defun org-babel-process-params (params)
1554 "Expand variables in PARAMS and add summary parameters."
1555 (let* ((processed-vars (mapcar (lambda (el)
1556 (if (consp (cdr el
))
1558 (org-babel-ref-parse (cdr el
))))
1559 (org-babel-get-header params
:var
)))
1560 (vars-and-names (if (and (assoc :colname-names params
)
1561 (assoc :rowname-names params
))
1562 (list processed-vars
)
1563 (org-babel-disassemble-tables
1565 (cdr (assoc :hlines params
))
1566 (cdr (assoc :colnames params
))
1567 (cdr (assoc :rownames params
)))))
1568 (raw-result (or (cdr (assoc :results params
)) ""))
1569 (result-params (append
1570 (split-string (if (stringp raw-result
)
1573 (cdr (assoc :result-params params
)))))
1575 (mapcar (lambda (var) (cons :var var
)) (car vars-and-names
))
1577 (cons :colname-names
(or (cdr (assoc :colname-names params
))
1578 (cadr vars-and-names
)))
1579 (cons :rowname-names
(or (cdr (assoc :rowname-names params
))
1580 (caddr vars-and-names
)))
1581 (cons :result-params result-params
)
1582 (cons :result-type
(cond ((member "output" result-params
) 'output
)
1583 ((member "value" result-params
) 'value
)
1585 (org-babel-get-header params
:var
'other
))))
1587 ;; row and column names
1588 (defun org-babel-del-hlines (table)
1589 "Remove all 'hlines from TABLE."
1590 (remove 'hline table
))
1592 (defun org-babel-get-colnames (table)
1593 "Return the column names of TABLE.
1594 Return a cons cell, the `car' of which contains the TABLE less
1595 colnames, and the `cdr' of which contains a list of the column
1597 (if (equal 'hline
(nth 1 table
))
1598 (cons (cddr table
) (car table
))
1599 (cons (cdr table
) (car table
))))
1601 (defun org-babel-get-rownames (table)
1602 "Return the row names of TABLE.
1603 Return a cons cell, the `car' of which contains the TABLE less
1604 rownames, and the `cdr' of which contains a list of the rownames.
1605 Note: this function removes any hlines in TABLE."
1606 (let* ((table (org-babel-del-hlines table
))
1607 (rownames (funcall (lambda ()
1613 (setq tp
(cdr tp
))))
1615 (cons table rownames
)))
1617 (defun org-babel-put-colnames (table colnames
)
1618 "Add COLNAMES to TABLE if they exist."
1619 (if colnames
(apply 'list colnames
'hline table
) table
))
1621 (defun org-babel-put-rownames (table rownames
)
1622 "Add ROWNAMES to TABLE if they exist."
1624 (mapcar (lambda (row)
1626 (cons (or (pop rownames
) "") row
)
1630 (defun org-babel-pick-name (names selector
)
1631 "Select one out of an alist of row or column names.
1632 SELECTOR can be either a list of names in which case those names
1633 will be returned directly, or an index into the list NAMES in
1634 which case the indexed names will be return."
1635 (if (listp selector
)
1638 (if (and selector
(symbolp selector
) (not (equal t selector
)))
1639 (cdr (assoc selector names
))
1640 (if (integerp selector
)
1641 (nth (- selector
1) names
)
1642 (cdr (car (last names
))))))))
1644 (defun org-babel-disassemble-tables (vars hlines colnames rownames
)
1645 "Parse tables for further processing.
1646 Process the variables in VARS according to the HLINES,
1647 ROWNAMES and COLNAMES header arguments. Return a list consisting
1648 of the vars, cnames and rnames."
1649 (let (cnames rnames
)
1653 (when (listp (cdr var
))
1654 (when (and (not (equal colnames
"no"))
1655 (or colnames
(and (equal (nth 1 (cdr var
)) 'hline
)
1656 (not (member 'hline
(cddr (cdr var
)))))))
1657 (let ((both (org-babel-get-colnames (cdr var
))))
1658 (setq cnames
(cons (cons (car var
) (cdr both
))
1660 (setq var
(cons (car var
) (car both
)))))
1661 (when (and rownames
(not (equal rownames
"no")))
1662 (let ((both (org-babel-get-rownames (cdr var
))))
1663 (setq rnames
(cons (cons (car var
) (cdr both
))
1665 (setq var
(cons (car var
) (car both
)))))
1666 (when (and hlines
(not (equal hlines
"yes")))
1667 (setq var
(cons (car var
) (org-babel-del-hlines (cdr var
))))))
1670 (reverse cnames
) (reverse rnames
))))
1672 (defun org-babel-reassemble-table (table colnames rownames
)
1673 "Add column and row names to a table.
1674 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1675 to the table for reinsertion to org-mode."
1677 (let ((table (if (and rownames
(= (length table
) (length rownames
)))
1678 (org-babel-put-rownames table rownames
) table
)))
1679 (if (and colnames
(listp (car table
)) (= (length (car table
))
1681 (org-babel-put-colnames table colnames
) table
))
1684 (defun org-babel-where-is-src-block-head ()
1685 "Find where the current source block begins.
1686 Return the point at the beginning of the current source
1687 block. Specifically at the beginning of the #+BEGIN_SRC line.
1688 If the point is not on a source block then return nil."
1689 (let ((initial (point)) (case-fold-search t
) top bottom
)
1691 (save-excursion ;; on a source name line or a #+header line
1692 (beginning-of-line 1)
1693 (and (or (looking-at org-babel-src-name-regexp
)
1694 (looking-at org-babel-multi-line-header-regexp
))
1696 (while (and (forward-line 1)
1697 (or (looking-at org-babel-src-name-regexp
)
1698 (looking-at org-babel-multi-line-header-regexp
))))
1699 (looking-at org-babel-src-block-regexp
))
1701 (save-excursion ;; on a #+begin_src line
1702 (beginning-of-line 1)
1703 (and (looking-at org-babel-src-block-regexp
)
1705 (save-excursion ;; inside a src block
1707 (re-search-backward "^[ \t]*#\\+begin_src" nil t
) (setq top
(point))
1708 (re-search-forward "^[ \t]*#\\+end_src" nil t
) (setq bottom
(point))
1709 (< top initial
) (< initial bottom
)
1710 (progn (goto-char top
) (beginning-of-line 1)
1711 (looking-at org-babel-src-block-regexp
))
1715 (defun org-babel-goto-src-block-head ()
1716 "Go to the beginning of the current code block."
1718 (let ((head (org-babel-where-is-src-block-head)))
1719 (if head
(goto-char head
) (error "Not currently in a code block"))))
1722 (defun org-babel-goto-named-src-block (name)
1723 "Go to a named source-code block."
1725 (let ((completion-ignore-case t
)
1726 (case-fold-search t
)
1727 (under-point (thing-at-point 'line
)))
1728 (list (org-icompleting-read
1729 "source-block name: " (org-babel-src-block-names) nil t
1732 ((string-match (org-babel-noweb-wrap) under-point
)
1733 (let ((block-name (match-string 1 under-point
)))
1734 (string-match "[^(]*" block-name
)
1735 (match-string 0 block-name
)))
1737 ((string-match org-babel-lob-one-liner-regexp under-point
)
1738 (let ((source-info (car (org-babel-lob-get-info))))
1739 (if (string-match "^\\([^\\[]+?\\)\\(\\[.*\\]\\)?(" source-info
)
1740 (let ((source-name (match-string 1 source-info
)))
1743 ((string-match (concat "#\\+" org-babel-results-keyword
1744 "\\:\s+\\([^\\(]*\\)") under-point
)
1745 (match-string 1 under-point
))
1747 ((and (thing-at-point 'symbol
))
1748 (org-babel-find-named-block (thing-at-point 'symbol
))
1749 (thing-at-point 'symbol
))
1751 (let ((point (org-babel-find-named-block name
)))
1753 ;; taken from `org-open-at-point'
1754 (progn (org-mark-ring-push) (goto-char point
) (org-show-context))
1755 (message "source-code block '%s' not found in this buffer" name
))))
1757 (defun org-babel-find-named-block (name)
1758 "Find a named source-code block.
1759 Return the location of the source block identified by source
1760 NAME, or nil if no such block exists. Set match data according to
1761 org-babel-named-src-block-regexp."
1763 (let ((case-fold-search t
)
1764 (regexp (org-babel-named-src-block-regexp-for-name name
)) msg
)
1765 (goto-char (point-min))
1766 (when (or (re-search-forward regexp nil t
)
1767 (re-search-backward regexp nil t
))
1768 (match-beginning 0)))))
1770 (defun org-babel-src-block-names (&optional file
)
1771 "Returns the names of source blocks in FILE or the current buffer."
1773 (when file
(find-file file
)) (goto-char (point-min))
1774 (let ((case-fold-search t
) names
)
1775 (while (re-search-forward org-babel-src-name-w-name-regexp nil t
)
1776 (setq names
(cons (match-string 3) names
)))
1780 (defun org-babel-goto-named-result (name)
1781 "Go to a named result."
1783 (let ((completion-ignore-case t
))
1784 (list (org-icompleting-read "source-block name: "
1785 (org-babel-result-names) nil t
))))
1786 (let ((point (org-babel-find-named-result name
)))
1788 ;; taken from `org-open-at-point'
1789 (progn (goto-char point
) (org-show-context))
1790 (message "result '%s' not found in this buffer" name
))))
1792 (defun org-babel-find-named-result (name &optional point
)
1793 "Find a named result.
1794 Return the location of the result named NAME in the current
1795 buffer or nil if no such result exists."
1797 (let ((case-fold-search t
))
1798 (goto-char (or point
(point-min)))
1799 (catch 'is-a-code-block
1800 (when (re-search-forward
1801 (concat org-babel-result-regexp
1802 "[ \t]" (regexp-quote name
) "[ \t]*[\n\f\v\r]") nil t
)
1803 (when (and (string= "name" (downcase (match-string 1)))
1804 (or (beginning-of-line 1)
1805 (looking-at org-babel-src-block-regexp
)
1806 (looking-at org-babel-multi-line-header-regexp
)
1807 (looking-at org-babel-lob-one-liner-regexp
)))
1808 (throw 'is-a-code-block
(org-babel-find-named-result name
(point))))
1809 (beginning-of-line 0) (point))))))
1811 (defun org-babel-result-names (&optional file
)
1812 "Returns the names of results in FILE or the current buffer."
1814 (when file
(find-file file
)) (goto-char (point-min))
1815 (let ((case-fold-search t
) names
)
1816 (while (re-search-forward org-babel-result-w-name-regexp nil t
)
1817 (setq names
(cons (match-string 4) names
)))
1821 (defun org-babel-next-src-block (&optional arg
)
1822 "Jump to the next source block.
1823 With optional prefix argument ARG, jump forward ARG many source blocks."
1825 (org-next-block arg nil org-babel-src-block-regexp
))
1828 (defun org-babel-previous-src-block (&optional arg
)
1829 "Jump to the previous source block.
1830 With optional prefix argument ARG, jump backward ARG many source blocks."
1832 (org-previous-block arg org-babel-src-block-regexp
))
1834 (defvar org-babel-load-languages
)
1837 (defun org-babel-mark-block ()
1838 "Mark current src block."
1840 (let ((head (org-babel-where-is-src-block-head)))
1844 (looking-at org-babel-src-block-regexp
))
1845 (push-mark (match-end 5) nil t
)
1846 (goto-char (match-beginning 5)))))
1848 (defun org-babel-demarcate-block (&optional arg
)
1849 "Wrap or split the code in the region or on the point.
1850 When called from inside of a code block the current block is
1851 split. When called from outside of a code block a new code block
1852 is created. In both cases if the region is demarcated and if the
1853 region is not active then the point is demarcated."
1855 (let ((info (org-babel-get-src-block-info 'light
))
1856 (headers (progn (org-babel-where-is-src-block-head)
1858 (stars (concat (make-string (or (org-current-level) 1) ?
*) " ")))
1864 (let ((lang (nth 0 info
))
1865 (indent (make-string (nth 5 info
) ?
)))
1866 (when (string-match "^[[:space:]]*$"
1867 (buffer-substring (point-at-bol)
1869 (delete-region (point-at-bol) (point-at-eol)))
1871 (if (looking-at "^") "" "\n")
1872 indent
"#+end_src\n"
1873 (if arg stars indent
) "\n"
1874 indent
"#+begin_src " lang
1875 (if (> (length headers
) 1)
1876 (concat " " headers
) headers
)
1877 (if (looking-at "[\n\r]")
1879 (concat "\n" (make-string (current-column) ?
)))))))
1880 (move-end-of-line 2))
1881 (sort (if (org-region-active-p) (list (mark) (point)) (list (point))) #'>))
1882 (let ((start (point))
1883 (lang (org-icompleting-read
1885 (mapcar #'symbol-name
1887 (append (mapcar #'car org-babel-load-languages
)
1888 (mapcar (lambda (el) (intern (car el
)))
1889 org-src-lang-modes
))))))
1890 (body (delete-and-extract-region
1891 (if (org-region-active-p) (mark) (point)) (point))))
1892 (insert (concat (if (looking-at "^") "" "\n")
1893 (if arg
(concat stars
"\n") "")
1894 "#+begin_src " lang
"\n"
1896 (if (or (= (length body
) 0)
1897 (string-match "[\r\n]$" body
)) "" "\n")
1899 (goto-char start
) (move-end-of-line 1)))))
1901 (defvar org-babel-lob-one-liner-regexp
)
1902 (defun org-babel-where-is-src-block-result (&optional insert info hash indent
)
1903 "Find where the current source block results begin.
1904 Return the point at the beginning of the result of the current
1905 source block. Specifically at the beginning of the results line.
1906 If no result exists for this block then create a results line
1907 following the source block."
1909 (let* ((case-fold-search t
)
1910 (on-lob-line (save-excursion
1911 (beginning-of-line 1)
1912 (looking-at org-babel-lob-one-liner-regexp
)))
1913 (inlinep (when (org-babel-get-inline-src-block-matches)
1915 (name (nth 4 (or info
(org-babel-get-src-block-info 'light
))))
1916 (head (unless on-lob-line
(org-babel-where-is-src-block-head)))
1918 (when head
(goto-char head
))
1919 (org-with-wide-buffer
1921 found
;; was there a result (before we potentially insert one)
1926 ;; - return t if it is found, else return nil
1927 ;; - if it does not need to be rebuilt, then don't set end
1928 ;; - if it does need to be rebuilt then do set end
1929 name
(setq beg
(org-babel-find-named-result name
))
1931 (when (and hash
(not (string= hash
(match-string 5))))
1932 (goto-char beg
) (setq end beg
) ;; beginning of result
1934 (delete-region end
(org-babel-result-end)) nil
)))
1937 ;; - return t if it is found, else return nil
1938 ;; - if it is found, and the hash doesn't match, delete and set end
1939 (or on-lob-line
(re-search-forward "^[ \t]*#\\+end_src" nil t
))
1940 (progn (end-of-line 1)
1941 (if (eobp) (insert "\n") (forward-char 1))
1945 (progn ;; unnamed results line already exists
1947 (while (re-search-forward "[^ \f\t\n\r\v]" nil t
)
1948 (beginning-of-line 1)
1950 ((looking-at (concat org-babel-result-regexp
"\n"))
1951 (throw 'non-comment t
))
1952 ((and (looking-at "^[ \t]*#")
1954 org-babel-lob-one-liner-regexp
)))
1956 (t (throw 'non-comment nil
))))))
1957 (let ((this-hash (match-string 5)))
1959 ;; must remove and rebuild if hash!=old-hash
1960 (if (and hash
(not (string= hash this-hash
)))
1962 (setq end
(point-at-bol))
1964 (delete-region end
(org-babel-result-end))
1966 (setq end nil
))))))))))
1967 (if (not (and insert end
)) found
1970 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1972 (when (wholenump indent
) (make-string indent ?
))
1973 "#+" org-babel-results-keyword
1975 (if org-babel-hash-show-time
1977 "["(format-time-string "<%Y-%m-%d %H:%M:%S>")" "hash
"]")
1978 (concat "["hash
"]")))
1980 (when name
(concat " " name
)) "\n"))
1981 (unless beg
(insert "\n") (backward-char))
1982 (beginning-of-line 0)
1983 (if hash
(org-babel-hide-hash))
1986 (defvar org-block-regexp
)
1987 (defun org-babel-read-result ()
1988 "Read the result at `point' into emacs-lisp."
1989 (let ((case-fold-search t
) result-string
)
1991 ((org-at-table-p) (org-babel-read-table))
1992 ((org-at-item-p) (org-babel-read-list))
1993 ((looking-at org-bracket-link-regexp
) (org-babel-read-link))
1994 ((looking-at org-block-regexp
) (org-remove-indentation (match-string 4)))
1995 ((or (looking-at "^[ \t]*: ") (looking-at "^[ \t]*:$"))
1998 (mapconcat (lambda (line)
1999 (or (and (> (length line
) 1)
2000 (string-match "^[ \t]*: ?\\(.+\\)" line
)
2001 (match-string 1 line
))
2005 (point) (org-babel-result-end)) "[\r\n]+")
2007 (or (org-babel-number-p result-string
) result-string
))
2008 ((looking-at org-babel-result-regexp
)
2009 (save-excursion (forward-line 1) (org-babel-read-result))))))
2011 (defun org-babel-read-table ()
2012 "Read the table at `point' into emacs-lisp."
2013 (mapcar (lambda (row)
2014 (if (and (symbolp row
) (equal row
'hline
)) row
2015 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
)) row
)))
2016 (org-table-to-lisp)))
2018 (defun org-babel-read-list ()
2019 "Read the list at `point' into emacs-lisp."
2020 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
))
2021 (mapcar #'cadr
(cdr (org-list-parse-list)))))
2023 (defvar org-link-types-re
)
2024 (defun org-babel-read-link ()
2025 "Read the link at `point' into emacs-lisp.
2026 If the path of the link is a file path it is expanded using
2027 `expand-file-name'."
2028 (let* ((case-fold-search t
)
2029 (raw (and (looking-at org-bracket-link-regexp
)
2030 (org-no-properties (match-string 1))))
2031 (type (and (string-match org-link-types-re raw
)
2032 (match-string 1 raw
))))
2034 ((not type
) (expand-file-name raw
))
2035 ((string= type
"file")
2036 (and (string-match "file\\(.*\\):\\(.+\\)" raw
)
2037 (expand-file-name (match-string 2 raw
))))
2040 (defun org-babel-format-result (result &optional sep
)
2041 "Format RESULT for writing to file."
2042 (let ((echo-res (lambda (r) (if (stringp r
) r
(format "%S" r
)))))
2046 result
(list :sep
(or sep
"\t") :fmt echo-res
))
2048 (funcall echo-res result
))))
2050 (defun org-babel-insert-result
2051 (result &optional result-params info hash indent lang
)
2052 "Insert RESULT into the current buffer.
2053 By default RESULT is inserted after the end of the
2054 current source block. With optional argument RESULT-PARAMS
2055 controls insertion of results in the org-mode file.
2056 RESULT-PARAMS can take the following values:
2058 replace - (default option) insert results after the source block
2059 replacing any previously inserted results
2061 silent -- no results are inserted into the Org-mode buffer but
2062 the results are echoed to the minibuffer and are
2063 ingested by Emacs (a potentially time consuming
2066 file ---- the results are interpreted as a file path, and are
2067 inserted into the buffer using the Org-mode file syntax
2069 list ---- the results are interpreted as an Org-mode list.
2071 raw ----- results are added directly to the Org-mode file. This
2072 is a good option if you code block will output org-mode
2075 drawer -- results are added directly to the Org-mode file as with
2076 \"raw\", but are wrapped in a RESULTS drawer, allowing
2077 them to later be replaced or removed automatically.
2079 org ----- results are added inside of a \"#+BEGIN_SRC org\" block.
2080 They are not comma-escaped when inserted, but Org syntax
2081 here will be discarded when exporting the file.
2083 html ---- results are added inside of a #+BEGIN_HTML block. This
2084 is a good option if you code block will output html
2087 latex --- results are added inside of a #+BEGIN_LATEX block.
2088 This is a good option if you code block will output
2089 latex formatted text.
2091 code ---- the results are extracted in the syntax of the source
2092 code of the language being evaluated and are added
2093 inside of a #+BEGIN_SRC block with the source-code
2094 language set appropriately. Note this relies on the
2095 optional LANG argument."
2096 (if (stringp result
)
2098 (setq result
(org-no-properties result
))
2099 (when (member "file" result-params
)
2100 (setq result
(org-babel-result-to-file
2101 result
(when (assoc :file-desc
(nth 2 info
))
2102 (or (cdr (assoc :file-desc
(nth 2 info
)))
2104 (unless (listp result
) (setq result
(format "%S" result
))))
2105 (if (and result-params
(member "silent" result-params
))
2107 (message (replace-regexp-in-string "%" "%%" (format "%S" result
)))
2112 (when (or (org-babel-get-inline-src-block-matches)
2113 (org-babel-get-lob-one-liner-matches))
2114 (goto-char (match-end 0))
2115 (insert (if (listp result
) "\n" " "))
2117 (existing-result (unless inlinep
2118 (org-babel-where-is-src-block-result
2119 t info hash indent
)))
2121 (cdr (assoc :results_switches
(nth 2 info
))))
2122 (visible-beg (copy-marker (point-min)))
2123 (visible-end (copy-marker (point-max)))
2124 ;; When results exist outside of the current visible
2125 ;; region of the buffer, be sure to widen buffer to
2127 (outside-scope-p (and existing-result
2128 (or (> visible-beg existing-result
)
2129 (<= visible-end existing-result
))))
2131 (when (and (stringp result
) ; ensure results end in a newline
2133 (> (length result
) 0)
2134 (not (or (string-equal (substring result -
1) "\n")
2135 (string-equal (substring result -
1) "\r"))))
2136 (setq result
(concat result
"\n")))
2139 (when outside-scope-p
(widen))
2140 (if (not existing-result
)
2141 (setq beg
(or inlinep
(point)))
2142 (goto-char existing-result
)
2144 (re-search-forward "#" nil t
)
2145 (setq indent
(- (current-column) 1)))
2149 ((member "replace" result-params
)
2150 (delete-region (point) (org-babel-result-end)))
2151 ((member "append" result-params
)
2152 (goto-char (org-babel-result-end)) (setq beg
(point-marker)))
2153 ((member "prepend" result-params
)))) ; already there
2154 (setq results-switches
2155 (if results-switches
(concat " " results-switches
) ""))
2156 (let ((wrap (lambda (start finish
&optional no-escape
)
2157 (goto-char end
) (insert (concat finish
"\n"))
2158 (goto-char beg
) (insert (concat start
"\n"))
2160 (org-escape-code-in-region (min (point) end
) end
))
2161 (goto-char end
) (goto-char (point-at-eol))
2162 (setq end
(point-marker))))
2163 (proper-list-p (lambda (it) (and (listp it
) (null (cdr (last it
)))))))
2164 ;; insert results based on type
2166 ;; do nothing for an empty result
2168 ;; insert a list if preferred
2169 ((member "list" result-params
)
2172 (org-list-to-generic
2175 (lambda (el) (list nil
(if (stringp el
) el
(format "%S" el
))))
2176 (if (listp result
) result
(split-string result
"\n" t
))))
2177 '(:splicep nil
:istart
"- " :iend
"\n")))
2179 ;; assume the result is a table if it's not a string
2180 ((funcall proper-list-p result
)
2182 (insert (concat (orgtbl-to-orgtbl
2183 (if (or (eq 'hline
(car result
))
2184 (and (listp (car result
))
2185 (listp (cdr (car result
)))))
2186 result
(list result
))
2187 '(:fmt
(lambda (cell) (format "%s" cell
)))) "\n"))
2188 (goto-char beg
) (when (org-at-table-p) (org-table-align)))
2189 ((and (listp result
) (not (funcall proper-list-p result
)))
2190 (insert (format "%s\n" result
)))
2191 ((member "file" result-params
)
2192 (when inlinep
(goto-char inlinep
))
2194 (t (goto-char beg
) (insert result
)))
2195 (when (funcall proper-list-p result
) (goto-char (org-table-end)))
2196 (setq end
(point-marker))
2197 ;; possibly wrap result
2199 ((assoc :wrap
(nth 2 info
))
2200 (let ((name (or (cdr (assoc :wrap
(nth 2 info
))) "RESULTS")))
2201 (funcall wrap
(concat "#+BEGIN_" name
)
2202 (concat "#+END_" (car (org-split-string name
))))))
2203 ((member "html" result-params
)
2204 (funcall wrap
"#+BEGIN_HTML" "#+END_HTML"))
2205 ((member "latex" result-params
)
2206 (funcall wrap
"#+BEGIN_LaTeX" "#+END_LaTeX"))
2207 ((member "org" result-params
)
2208 (goto-char beg
) (if (org-at-table-p) (org-cycle))
2209 (funcall wrap
"#+BEGIN_SRC org" "#+END_SRC"))
2210 ((member "code" result-params
)
2211 (funcall wrap
(format "#+BEGIN_SRC %s%s" (or lang
"none") results-switches
)
2213 ((member "raw" result-params
)
2214 (goto-char beg
) (if (org-at-table-p) (org-cycle)))
2215 ((or (member "drawer" result-params
)
2216 ;; Stay backward compatible with <7.9.2
2217 (member "wrap" result-params
))
2218 (goto-char beg
) (if (org-at-table-p) (org-cycle))
2219 (funcall wrap
":RESULTS:" ":END:" 'no-escape
))
2220 ((and (not (funcall proper-list-p result
))
2221 (not (member "file" result-params
)))
2222 (org-babel-examplify-region beg end results-switches
)
2223 (setq end
(point)))))
2224 ;; possibly indent the results to match the #+results line
2225 (when (and (not inlinep
) (numberp indent
) indent
(> indent
0)
2226 ;; in this case `table-align' does the work for us
2227 (not (and (listp result
)
2228 (member "append" result-params
))))
2229 (indent-rigidly beg end indent
))
2231 (if (member "value" result-params
)
2232 (message "Code block returned no value.")
2233 (message "Code block produced no output."))
2234 (message "Code block evaluation complete.")))
2235 (when outside-scope-p
(narrow-to-region visible-beg visible-end
))
2236 (set-marker visible-beg nil
)
2237 (set-marker visible-end nil
))))))
2239 (defun org-babel-remove-result (&optional info keep-keyword
)
2240 "Remove the result of the current source block."
2242 (let ((location (org-babel-where-is-src-block-result nil info
)))
2245 (goto-char location
)
2246 (when (looking-at (concat org-babel-result-regexp
".*$"))
2248 (if keep-keyword
(1+ (match-end 0)) (1- (match-beginning 0)))
2249 (progn (forward-line 1) (org-babel-result-end))))))))
2251 (defun org-babel-result-end ()
2252 "Return the point at the end of the current set of results."
2255 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
2256 ((org-at-item-p) (let* ((struct (org-list-struct))
2257 (prvs (org-list-prevs-alist struct
)))
2258 (org-list-get-list-end (point-at-bol) struct prvs
)))
2259 ((let ((case-fold-search t
)) (looking-at "^\\([ \t]*\\):results:"))
2260 (progn (re-search-forward (concat "^" (match-string 1) ":END:"))
2261 (forward-char 1) (point)))
2263 (let ((case-fold-search t
))
2264 (if (looking-at (concat "[ \t]*#\\+begin_\\([^ \t\n\r]+\\)"))
2265 (progn (re-search-forward (concat "[ \t]*#\\+end_" (match-string 1))
2268 (while (looking-at "[ \t]*\\(: \\|:$\\|\\[\\[\\)")
2272 (defun org-babel-result-to-file (result &optional description
)
2273 "Convert RESULT into an `org-mode' link with optional DESCRIPTION.
2274 If the `default-directory' is different from the containing
2275 file's directory then expand relative links."
2276 (when (stringp result
)
2277 (format "[[file:%s]%s]"
2278 (if (and default-directory
2280 (not (string= (expand-file-name default-directory
)
2282 (file-name-directory buffer-file-name
)))))
2283 (expand-file-name result default-directory
)
2285 (if description
(concat "[" description
"]") ""))))
2287 (defvar org-babel-capitalize-example-region-markers nil
2288 "Make true to capitalize begin/end example markers inserted by code blocks.")
2290 (define-obsolete-function-alias
2291 'org-babel-examplize-region
2292 'org-babel-examplify-region
"24.5")
2294 (defun org-babel-examplify-region (beg end
&optional results-switches
)
2295 "Comment out region using the inline '==' or ': ' org example quote."
2297 (let ((chars-between (lambda (b e
)
2298 (not (string-match "^[\\s]*$"
2299 (buffer-substring b e
)))))
2300 (maybe-cap (lambda (str) (if org-babel-capitalize-example-region-markers
2302 (beg-bol (save-excursion (goto-char beg
) (point-at-bol)))
2303 (end-bol (save-excursion (goto-char end
) (point-at-bol)))
2304 (end-eol (save-excursion (goto-char end
) (point-at-eol))))
2305 (if (and (not (= end end-bol
))
2306 (or (funcall chars-between beg-bol beg
)
2307 (funcall chars-between end end-eol
)))
2310 (insert (format org-babel-inline-result-wrap
2311 (prog1 (buffer-substring beg end
)
2312 (delete-region beg end
)))))
2313 (let ((size (count-lines beg end
)))
2315 (cond ((= size
0)) ; do nothing for an empty result
2316 ((< size org-babel-min-lines-for-block-output
)
2319 (beginning-of-line 1) (insert ": ") (forward-line 1)))
2322 (insert (if results-switches
2324 (funcall maybe-cap
"#+begin_example")
2326 (funcall maybe-cap
"#+begin_example\n")))
2327 (if (markerp end
) (goto-char end
) (forward-char (- end beg
)))
2328 (insert (funcall maybe-cap
"#+end_example\n")))))))))
2330 (defun org-babel-update-block-body (new-body)
2331 "Update the body of the current code block to NEW-BODY."
2332 (if (not (org-babel-where-is-src-block-head))
2333 (error "Not in a source block")
2335 (replace-match (concat (org-babel-trim (org-remove-indentation new-body
))
2337 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
2339 (defun org-babel-merge-params (&rest plists
)
2340 "Combine all parameter association lists in PLISTS.
2341 Later elements of PLISTS override the values of previous elements.
2342 This takes into account some special considerations for certain
2343 parameters when merging lists."
2344 (let* ((results-exclusive-groups
2345 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2346 (cdr (assoc 'results org-babel-common-header-args-w-values
))))
2347 (exports-exclusive-groups
2348 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2349 (cdr (assoc 'exports org-babel-common-header-args-w-values
))))
2351 (e-merge (lambda (exclusive-groups &rest result-params
)
2352 ;; maintain exclusivity of mutually exclusive parameters
2354 (mapc (lambda (new-params)
2355 (mapc (lambda (new-param)
2356 (mapc (lambda (exclusive-group)
2357 (when (member new-param exclusive-group
)
2358 (mapcar (lambda (excluded-param)
2365 (setq output
(org-uniquify
2366 (cons new-param output
))))
2370 params results exports tangle noweb cache vars shebang comments padline
2379 (let ((name (if (listp (cdr pair
))
2381 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
2383 (intern (match-string 1 (cdr pair
)))))))
2387 (if (member name
(mapcar #'car vars
))
2389 (push name clearnames
)
2393 (unless (equal (car p
) name
) p
))
2396 (list (cons name pair
))))
2397 ;; if no name is given and we already have named variables
2398 ;; then assign to named variables in order
2399 (if (and vars
(nth variable-index vars
))
2400 (let ((name (car (nth variable-index vars
))))
2401 (push name clearnames
) ; clear out colnames
2404 (prog1 (setf (cddr (nth variable-index vars
))
2405 (concat (symbol-name name
) "=" (cdr pair
)))
2406 (incf variable-index
)))
2407 (error "Variable \"%s\" must be assigned a default value"
2410 (setq results
(funcall e-merge results-exclusive-groups
2413 (let ((r (cdr pair
)))
2414 (if (stringp r
) r
(eval r
)))))))
2417 (setq results
(funcall e-merge results-exclusive-groups
2419 (unless (or (member "both" exports
)
2420 (member "none" exports
)
2421 (member "code" exports
))
2422 (setq exports
(funcall e-merge exports-exclusive-groups
2423 exports
'("results"))))
2424 (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))
2426 (setq exports
(funcall e-merge exports-exclusive-groups
2427 exports
(split-string (cdr pair
)))))
2428 (:tangle
;; take the latest -- always overwrite
2429 (setq tangle
(or (list (cdr pair
)) tangle
)))
2431 (setq noweb
(funcall e-merge
2432 '(("yes" "no" "tangle" "no-export"
2433 "strip-export" "eval"))
2435 (split-string (or (cdr pair
) "")))))
2437 (setq cache
(funcall e-merge
'(("yes" "no")) cache
2438 (split-string (or (cdr pair
) "")))))
2440 (setq padline
(funcall e-merge
'(("yes" "no")) padline
2441 (split-string (or (cdr pair
) "")))))
2442 (:shebang
;; take the latest -- always overwrite
2443 (setq shebang
(or (list (cdr pair
)) shebang
)))
2445 (setq comments
(funcall e-merge
'(("yes" "no")) comments
2446 (split-string (or (cdr pair
) "")))))
2447 (t ;; replace: this covers e.g. :session
2448 (setq params
(cons pair
(assq-delete-all (car pair
) params
))))))
2451 (setq vars
(reverse vars
))
2452 (while vars
(setq params
(cons (cons :var
(cddr (pop vars
))) params
)))
2453 ;; clear out col-names and row-names for replaced variables
2458 (when (assoc param params
)
2459 (setf (cdr (assoc param params
))
2460 (org-remove-if (lambda (pair) (equal (car pair
) name
))
2461 (cdr (assoc param params
))))
2462 (setf params
(org-remove-if (lambda (pair) (and (equal (car pair
) param
)
2465 (list :colname-names
:rowname-names
)))
2469 (let ((key (intern (concat ":" (symbol-name hd
))))
2471 (setf params
(cons (cons key
(mapconcat 'identity val
" ")) params
))))
2472 '(results exports tangle noweb padline cache shebang comments
))
2475 (defvar org-babel-use-quick-and-dirty-noweb-expansion nil
2476 "Set to true to use regular expressions to expand noweb references.
2477 This results in much faster noweb reference expansion but does
2478 not properly allow code blocks to inherit the \":noweb-ref\"
2479 header argument from buffer or subtree wide properties.")
2481 (defun org-babel-noweb-p (params context
)
2482 "Check if PARAMS require expansion in CONTEXT.
2483 CONTEXT may be one of :tangle, :export or :eval."
2485 (intersect (lambda (as bs
)
2487 (if (member (car as
) bs
)
2489 (funcall intersect
(cdr as
) bs
))))))
2490 (funcall intersect
(case context
2491 (:tangle
'("yes" "tangle" "no-export" "strip-export"))
2492 (:eval
'("yes" "no-export" "strip-export" "eval"))
2494 (split-string (or (cdr (assoc :noweb params
)) "")))))
2496 (defun org-babel-expand-noweb-references (&optional info parent-buffer
)
2497 "Expand Noweb references in the body of the current source code block.
2499 For example the following reference would be replaced with the
2500 body of the source-code block named 'example-block'.
2504 Note that any text preceding the <<foo>> construct on a line will
2505 be interposed between the lines of the replacement text. So for
2506 example if <<foo>> is placed behind a comment, then the entire
2507 replacement text will also be commented.
2509 This function must be called from inside of the buffer containing
2510 the source-code block which holds BODY.
2512 In addition the following syntax can be used to insert the
2513 results of evaluating the source-code block named 'example-block'.
2517 Any optional arguments can be passed to example-block by placing
2518 the arguments inside the parenthesis following the convention
2519 defined by `org-babel-lob'. For example
2521 <<example-block(a=9)>>
2523 would set the value of argument \"a\" equal to \"9\". Note that
2524 these arguments are not evaluated in the current source-code
2525 block but are passed literally to the \"example-block\"."
2526 (let* ((parent-buffer (or parent-buffer
(current-buffer)))
2527 (info (or info
(org-babel-get-src-block-info 'light
)))
2530 (ob-nww-start org-babel-noweb-wrap-start
)
2531 (ob-nww-end org-babel-noweb-wrap-end
)
2532 (comment (string= "noweb" (cdr (assoc :comments
(nth 2 info
)))))
2533 (rx-prefix (concat "\\(" org-babel-src-name-regexp
"\\|"
2534 ":noweb-ref[ \t]+" "\\)"))
2536 (nb-add (lambda (text) (setq new-body
(concat new-body text
))))
2537 (c-wrap (lambda (text)
2539 (funcall (intern (concat lang
"-mode")))
2540 (comment-region (point) (progn (insert text
) (point)))
2541 (org-babel-trim (buffer-string)))))
2542 index source-name evaluate prefix
)
2544 (org-set-local 'org-babel-noweb-wrap-start ob-nww-start
)
2545 (org-set-local 'org-babel-noweb-wrap-end ob-nww-end
)
2546 (insert body
) (goto-char (point-min))
2547 (setq index
(point))
2548 (while (and (re-search-forward (org-babel-noweb-wrap) nil t
))
2549 (save-match-data (setf source-name
(match-string 1)))
2550 (save-match-data (setq evaluate
(string-match "\(.*\)" source-name
)))
2553 (buffer-substring (match-beginning 0)
2555 (beginning-of-line 1) (point)))))
2556 ;; add interval to new-body (removing noweb reference)
2557 (goto-char (match-beginning 0))
2558 (funcall nb-add
(buffer-substring index
(point)))
2559 (goto-char (match-end 0))
2560 (setq index
(point))
2563 (with-current-buffer parent-buffer
2566 (mapconcat ;; Interpose PREFIX between every line.
2570 (let ((raw (org-babel-ref-resolve source-name
)))
2571 (if (stringp raw
) raw
(format "%S" raw
)))
2573 ;; Retrieve from the library of babel.
2574 (nth 2 (assoc (intern source-name
)
2575 org-babel-library-of-babel
))
2576 ;; Return the contents of headlines literally.
2578 (when (org-babel-ref-goto-headline-id source-name
)
2579 (org-babel-ref-headline-body)))
2580 ;; Find the expansion of reference in this buffer.
2581 (let ((rx (concat rx-prefix source-name
"[ \t\n]"))
2584 (goto-char (point-min))
2585 (if org-babel-use-quick-and-dirty-noweb-expansion
2586 (while (re-search-forward rx nil t
)
2587 (let* ((i (org-babel-get-src-block-info 'light
))
2588 (body (org-babel-expand-noweb-references i
))
2589 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2592 (let ((cs (org-babel-tangle-comment-links i
)))
2593 (concat (funcall c-wrap
(car cs
)) "\n"
2595 (funcall c-wrap
(cadr cs
))))
2597 (setq expansion
(cons sep
(cons full expansion
)))))
2598 (org-babel-map-src-blocks nil
2599 (let ((i (org-babel-get-src-block-info 'light
)))
2600 (when (equal (or (cdr (assoc :noweb-ref
(nth 2 i
)))
2603 (let* ((body (org-babel-expand-noweb-references i
))
2604 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2607 (let ((cs (org-babel-tangle-comment-links i
)))
2608 (concat (funcall c-wrap
(car cs
)) "\n"
2610 (funcall c-wrap
(cadr cs
))))
2613 (cons sep
(cons full expansion
)))))))))
2615 (mapconcat #'identity
(nreverse (cdr expansion
)) "")))
2616 ;; Possibly raise an error if named block doesn't exist.
2617 (if (member lang org-babel-noweb-error-langs
)
2619 (org-babel-noweb-wrap source-name
)
2620 "could not be resolved (see "
2621 "`org-babel-noweb-error-langs')"))
2623 "[\n\r]") (concat "\n" prefix
))))))
2624 (funcall nb-add
(buffer-substring index
(point-max))))
2627 (defun org-babel-script-escape (str &optional force
)
2628 "Safely convert tables into elisp lists."
2633 (or (and (string-equal "[" (substring str
0 1))
2634 (string-equal "]" (substring str -
1)))
2635 (and (string-equal "{" (substring str
0 1))
2636 (string-equal "}" (substring str -
1)))
2637 (and (string-equal "(" (substring str
0 1))
2638 (string-equal ")" (substring str -
1))))))
2642 (let (in-single in-double out
)
2648 (91 (if (or in-double in-single
) ; [
2651 (93 (if (or in-double in-single
) ; ]
2654 (123 (if (or in-double in-single
) ; {
2657 (125 (if (or in-double in-single
) ; }
2660 (44 (if (or in-double in-single
) ; ,
2661 (cons 44 out
) (cons 32 out
)))
2662 (39 (if in-double
; '
2664 (setq in-single
(not in-single
)) (cons 34 out
)))
2665 (34 (if in-single
; "
2666 (append (list 34 32) out
)
2667 (setq in-double
(not in-double
)) (cons 34 out
)))
2668 (t (cons ch out
)))))
2669 (string-to-list str
))
2670 (apply #'string
(reverse out
)))))
2672 (condition-case nil
(org-babel-read escaped
) (error escaped
))))
2674 (defun org-babel-read (cell &optional inhibit-lisp-eval
)
2675 "Convert the string value of CELL to a number if appropriate.
2676 Otherwise if cell looks like lisp (meaning it starts with a
2677 \"(\", \"'\", \"`\" or a \"[\") then read it as lisp,
2678 otherwise return it unmodified as a string. Optional argument
2679 NO-LISP-EVAL inhibits lisp evaluation for situations in which is
2680 it not appropriate."
2681 (if (and (stringp cell
) (not (equal cell
"")))
2682 (or (org-babel-number-p cell
)
2683 (if (and (not inhibit-lisp-eval
)
2684 (or (member (substring cell
0 1) '("(" "'" "`" "["))
2685 (string= cell
"*this*")))
2687 (if (string= (substring cell
0 1) "\"")
2689 (progn (set-text-properties 0 (length cell
) nil cell
) cell
))))
2692 (defun org-babel-number-p (string)
2693 "If STRING represents a number return its value."
2694 (if (and (string-match "[0-9]+" string
)
2695 (string-match "^-?[0-9]*\\.?[0-9]*$" string
)
2696 (= (length (substring string
(match-beginning 0)
2699 (string-to-number string
)))
2701 (defun org-babel-import-elisp-from-file (file-name &optional separator
)
2702 "Read the results located at FILE-NAME into an elisp table.
2703 If the table is trivial, then return it as a scalar."
2705 (save-window-excursion
2709 (org-table-import file-name separator
)
2710 (delete-file file-name
)
2711 (setq result
(mapcar (lambda (row)
2712 (mapcar #'org-babel-string-read row
))
2713 (org-table-to-lisp))))
2714 (error (message "Error reading results: %s" err
) nil
)))
2715 (if (null (cdr result
)) ;; if result is trivial vector, then scalarize it
2716 (if (consp (car result
))
2717 (if (null (cdr (car result
)))
2723 (defun org-babel-string-read (cell)
2724 "Strip nested \"s from around strings."
2725 (org-babel-read (or (and (stringp cell
)
2726 (string-match "\\\"\\(.+\\)\\\"" cell
)
2727 (match-string 1 cell
))
2730 (defun org-babel-chomp (string &optional regexp
)
2731 "Strip trailing spaces and carriage returns from STRING.
2732 Default regexp used is \"[ \f\t\n\r\v]\" but can be
2733 overwritten by specifying a regexp as a second argument."
2734 (let ((regexp (or regexp
"[ \f\t\n\r\v]")))
2735 (while (and (> (length string
) 0)
2736 (string-match regexp
(substring string -
1)))
2737 (setq string
(substring string
0 -
1)))
2740 (defun org-babel-trim (string &optional regexp
)
2741 "Strip leading and trailing spaces and carriage returns from STRING.
2742 Like `org-babel-chomp' only it runs on both the front and back
2744 (org-babel-chomp (org-reverse-string
2745 (org-babel-chomp (org-reverse-string string
) regexp
))
2748 (defun org-babel-tramp-handle-call-process-region
2749 (start end program
&optional delete buffer display
&rest args
)
2750 "Use Tramp to handle `call-process-region'.
2751 Fixes a bug in `tramp-handle-call-process-region'."
2752 (if (and (featurep 'tramp
) (file-remote-p default-directory
))
2753 (let ((tmpfile (tramp-compat-make-temp-file "")))
2754 (write-region start end tmpfile
)
2755 (when delete
(delete-region start end
))
2757 ;; (apply 'call-process program tmpfile buffer display args)
2759 (apply 'process-file program tmpfile buffer display args
)
2760 (delete-file tmpfile
)))
2761 ;; org-babel-call-process-region-original is the original emacs
2762 ;; definition. It is in scope from the let binding in
2763 ;; org-babel-execute-src-block
2764 (apply org-babel-call-process-region-original
2765 start end program delete buffer display args
)))
2767 (defun org-babel-local-file-name (file)
2768 "Return the local name component of FILE."
2769 (or (file-remote-p file
'localname
) file
))
2771 (defun org-babel-process-file-name (name &optional no-quote-p
)
2772 "Prepare NAME to be used in an external process.
2773 If NAME specifies a remote location, the remote portion of the
2774 name is removed, since in that case the process will be executing
2775 remotely. The file name is then processed by `expand-file-name'.
2776 Unless second argument NO-QUOTE-P is non-nil, the file name is
2777 additionally processed by `shell-quote-argument'"
2778 (let ((f (org-babel-local-file-name (expand-file-name name
))))
2779 (if no-quote-p f
(shell-quote-argument f
))))
2781 (defvar org-babel-temporary-directory
)
2782 (unless (or noninteractive
(boundp 'org-babel-temporary-directory
))
2783 (defvar org-babel-temporary-directory
2784 (or (and (boundp 'org-babel-temporary-directory
)
2785 (file-exists-p org-babel-temporary-directory
)
2786 org-babel-temporary-directory
)
2787 (make-temp-file "babel-" t
))
2788 "Directory to hold temporary files created to execute code blocks.
2789 Used by `org-babel-temp-file'. This directory will be removed on
2792 (defcustom org-babel-remote-temporary-directory
"/tmp/"
2793 "Directory to hold temporary files on remote hosts."
2797 (defmacro org-babel-result-cond
(result-params scalar-form
&rest table-forms
)
2798 "Call the code to parse raw string results according to RESULT-PARAMS."
2800 (debug (form form
&rest form
)))
2801 (org-with-gensyms (params)
2802 `(let ((,params
,result-params
))
2803 (unless (member "none" ,params
)
2804 (if (or (member "scalar" ,params
)
2805 (member "verbatim" ,params
)
2806 (member "html" ,params
)
2807 (member "code" ,params
)
2808 (member "pp" ,params
)
2809 (and (or (member "output" ,params
)
2810 (member "raw" ,params
)
2811 (member "org" ,params
)
2812 (member "drawer" ,params
))
2813 (not (member "table" ,params
))))
2816 (def-edebug-spec org-babel-result-cond
(form form body
))
2818 (defun org-babel-temp-file (prefix &optional suffix
)
2819 "Create a temporary file in the `org-babel-temporary-directory'.
2820 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2821 value of `temporary-file-directory' temporarily set to the value
2822 of `org-babel-temporary-directory'."
2823 (if (file-remote-p default-directory
)
2825 (concat (file-remote-p default-directory
)
2827 prefix org-babel-remote-temporary-directory
))))
2828 (make-temp-file prefix nil suffix
))
2829 (let ((temporary-file-directory
2830 (or (and (boundp 'org-babel-temporary-directory
)
2831 (file-exists-p org-babel-temporary-directory
)
2832 org-babel-temporary-directory
)
2833 temporary-file-directory
)))
2834 (make-temp-file prefix nil suffix
))))
2836 (defun org-babel-remove-temporary-directory ()
2837 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2838 (when (and (boundp 'org-babel-temporary-directory
)
2839 (file-exists-p org-babel-temporary-directory
))
2840 ;; taken from `delete-directory' in files.el
2843 (mapc (lambda (file)
2844 ;; This test is equivalent to
2845 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2846 ;; but more efficient
2847 (if (eq t
(car (file-attributes file
)))
2848 (delete-directory file
)
2849 (delete-file file
)))
2850 ;; We do not want to delete "." and "..".
2851 (directory-files org-babel-temporary-directory
'full
2852 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2853 (delete-directory org-babel-temporary-directory
))
2855 (message "Failed to remove temporary Org-babel directory %s"
2856 (if (boundp 'org-babel-temporary-directory
)
2857 org-babel-temporary-directory
2858 "[directory not defined]"))))))
2860 (add-hook 'kill-emacs-hook
'org-babel-remove-temporary-directory
)
2862 (defun org-babel-one-header-arg-safe-p (pair safe-list
)
2863 "Determine if the PAIR is a safe babel header arg according to SAFE-LIST.
2865 For the format of SAFE-LIST, see `org-babel-safe-header-args'."
2867 (keywordp (car pair
))
2868 (stringp (cdr pair
))
2870 (memq (car pair
) safe-list
)
2871 (let ((entry (assq (car pair
) safe-list
)))
2874 (cond ((functionp (cdr entry
))
2875 (funcall (cdr entry
) (cdr pair
)))
2876 ((listp (cdr entry
))
2877 (member (cdr pair
) (cdr entry
)))
2883 ;; generated-autoload-file: "org-loaddefs.el"
2886 ;;; ob-core.el ends here