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-babel-exp-reference-buffer nil
289 "Buffer containing original contents of the exported buffer.
290 This is used by Babel to resolve references in source blocks.
291 Its value is dynamically bound during export.")
293 (defmacro org-babel-check-confirm-evaluate
(info &rest body
)
294 "Evaluate BODY with special execution confirmation variables set.
296 Specifically; NOEVAL will indicate if evaluation is allowed,
297 QUERY will indicate if a user query is required, CODE-BLOCK will
298 hold the language of the code block, and BLOCK-NAME will hold the
299 name of the code block."
300 (declare (indent defun
))
302 (lang block-body headers name head eval eval-no export eval-no-export
)
303 `(let* ((,lang
(nth 0 ,info
))
304 (,block-body
(nth 1 ,info
))
305 (,headers
(nth 2 ,info
))
306 (,name
(nth 4 ,info
))
307 (,head
(nth 6 ,info
))
308 (,eval
(or (cdr (assoc :eval
,headers
))
309 (when (assoc :noeval
,headers
) "no")))
310 (,eval-no
(or (equal ,eval
"no")
311 (equal ,eval
"never")))
312 (,export org-babel-exp-reference-buffer
)
313 (,eval-no-export
(and ,export
(or (equal ,eval
"no-export")
314 (equal ,eval
"never-export"))))
315 (noeval (or ,eval-no
,eval-no-export
))
316 (query (or (equal ,eval
"query")
317 (and ,export
(equal ,eval
"query-export"))
318 (if (functionp org-confirm-babel-evaluate
)
321 (funcall org-confirm-babel-evaluate
323 org-confirm-babel-evaluate
)))
324 (code-block (if ,info
(format " %s " ,lang
) " "))
325 (block-name (if ,name
(format " (%s) " ,name
) " ")))
328 (defsubst org-babel-check-evaluate
(info)
329 "Check if code block INFO should be evaluated.
330 Do not query the user."
331 (org-babel-check-confirm-evaluate info
333 (message (format "Evaluation of this%scode-block%sis disabled."
334 code-block block-name
))))))
336 ;; dynamically scoped for asynchronous export
337 (defvar org-babel-confirm-evaluate-answer-no
)
339 (defsubst org-babel-confirm-evaluate
(info)
340 "Confirm evaluation of the code block INFO.
342 If the variable `org-babel-confirm-evaluate-answer-no' is bound
343 to a non-nil value, auto-answer with \"no\".
345 This query can also be suppressed by setting the value of
346 `org-confirm-babel-evaluate' to nil, in which case all future
347 interactive code block evaluations will proceed without any
348 confirmation from the user.
350 Note disabling confirmation may result in accidental evaluation
351 of potentially harmful code."
352 (org-babel-check-confirm-evaluate info
355 (and (not (org-bound-and-true-p
356 org-babel-confirm-evaluate-answer-no
))
358 (format "Evaluate this%scode block%son your system? "
359 code-block block-name
)))
360 (message (format "Evaluation of this%scode-block%sis aborted."
361 code-block block-name
)))))))
364 (defun org-babel-execute-safely-maybe ()
365 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
366 (org-babel-execute-maybe)))
368 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-execute-safely-maybe
)
371 (defun org-babel-execute-maybe ()
373 (or (org-babel-execute-src-block-maybe)
374 (org-babel-lob-execute-maybe)))
376 (defmacro org-babel-when-in-src-block
(&rest body
)
377 "Execute BODY if point is in a source block and return t.
379 Otherwise do nothing and return nil."
380 `(if (or (org-babel-where-is-src-block-head)
381 (org-babel-get-inline-src-block-matches))
387 (defun org-babel-execute-src-block-maybe ()
388 "Conditionally execute a source block.
389 Detect if this is context for a Babel src-block and if so
390 then run `org-babel-execute-src-block'."
392 (org-babel-when-in-src-block
393 (org-babel-eval-wipe-error-buffer)
394 (org-babel-execute-src-block current-prefix-arg
)))
397 (defun org-babel-view-src-block-info ()
398 "Display information on the current source block.
399 This includes header arguments, language and name, and is largely
400 a window into the `org-babel-get-src-block-info' function."
402 (let ((info (org-babel-get-src-block-info 'light
))
403 (full (lambda (it) (> (length it
) 0)))
404 (printf (lambda (fmt &rest args
) (princ (apply #'format fmt args
)))))
406 (with-help-window (help-buffer)
407 (let ((name (nth 4 info
))
409 (switches (nth 3 info
))
410 (header-args (nth 2 info
)))
411 (when name
(funcall printf
"Name: %s\n" name
))
412 (when lang
(funcall printf
"Lang: %s\n" lang
))
413 (when (funcall full switches
) (funcall printf
"Switches: %s\n" switches
))
414 (funcall printf
"Header Arguments:\n")
415 (dolist (pair (sort header-args
416 (lambda (a b
) (string< (symbol-name (car a
))
417 (symbol-name (car b
))))))
418 (when (funcall full
(cdr pair
))
419 (funcall printf
"\t%S%s\t%s\n"
421 (if (> (length (format "%S" (car pair
))) 7) "" "\t")
425 (defun org-babel-expand-src-block-maybe ()
426 "Conditionally expand a source block.
427 Detect if this is context for a org-babel src-block and if so
428 then run `org-babel-expand-src-block'."
430 (org-babel-when-in-src-block
431 (org-babel-expand-src-block current-prefix-arg
)))
434 (defun org-babel-load-in-session-maybe ()
435 "Conditionally load a source block in a session.
436 Detect if this is context for a org-babel src-block and if so
437 then run `org-babel-load-in-session'."
439 (org-babel-when-in-src-block
440 (org-babel-load-in-session current-prefix-arg
)))
442 (add-hook 'org-metaup-hook
'org-babel-load-in-session-maybe
)
445 (defun org-babel-pop-to-session-maybe ()
446 "Conditionally pop to a session.
447 Detect if this is context for a org-babel src-block and if so
448 then run `org-babel-switch-to-session'."
450 (org-babel-when-in-src-block
451 (org-babel-switch-to-session current-prefix-arg
)))
453 (add-hook 'org-metadown-hook
'org-babel-pop-to-session-maybe
)
455 (defconst org-babel-common-header-args-w-values
456 '((cache .
((no yes
)))
458 (colnames .
((nil no yes
)))
459 (comments .
((no link yes org both noweb
)))
461 (eval .
((never query
)))
462 (exports .
((code results both none
)))
466 (hlines .
((no yes
)))
467 (mkdirp .
((yes no
)))
470 (noweb .
((yes no tangle no-export strip-export
)))
473 (padline .
((yes no
)))
476 (results .
((file list vector table scalar verbatim
)
477 (raw html latex org code pp drawer
)
478 (replace silent none append prepend
)
480 (rownames .
((no yes
)))
484 (tangle .
((tangle yes no
:any
)))
485 (tangle-mode .
((#o755
#o555
#o444
:any
)))
489 (defconst org-babel-header-arg-names
490 (mapcar #'car org-babel-common-header-args-w-values
)
491 "Common header arguments used by org-babel.
492 Note that individual languages may define their own language
493 specific header arguments as well.")
495 (defconst org-babel-safe-header-args
496 '(:cache
:colnames
:comments
:exports
:epilogue
:hlines
:noeval
497 :noweb
:noweb-ref
:noweb-sep
:padline
:prologue
:rownames
498 :sep
:session
:tangle
:wrap
499 (:eval .
("never" "query"))
500 (:results .
(lambda (str) (not (string-match "file" str
)))))
501 "A list of safe header arguments for babel source blocks.
503 The list can have entries of the following forms:
504 - :ARG -> :ARG is always a safe header arg
505 - (:ARG . (VAL1 VAL2 ...)) -> :ARG is safe as a header arg if it is
506 `equal' to one of the VALs.
507 - (:ARG . FN) -> :ARG is safe as a header arg if the function FN
508 returns non-nil. FN is passed one
509 argument, the value of the header arg
512 (defmacro org-babel-header-args-safe-fn
(safe-list)
513 "Return a function that determines whether a list of header args are safe.
516 \(put 'org-babel-default-header-args 'safe-local-variable
517 (org-babel-header-args-safe-p org-babel-safe-header-args)
519 This allows org-babel languages to extend the list of safe values for
520 their `org-babel-default-header-args:foo' variable.
522 For the format of SAFE-LIST, see `org-babel-safe-header-args'."
528 (org-babel-one-header-arg-safe-p pair
,safe-list
)))
531 (defvar org-babel-default-header-args
532 '((:session .
"none") (:results .
"replace") (:exports .
"code")
533 (:cache .
"no") (:noweb .
"no") (:hlines .
"no") (:tangle .
"no"))
534 "Default arguments to use when evaluating a source block.")
535 (put 'org-babel-default-header-args
'safe-local-variable
536 (org-babel-header-args-safe-fn org-babel-safe-header-args
))
538 (defvar org-babel-default-inline-header-args
539 '((:session .
"none") (:results .
"replace")
540 (:exports .
"results") (:hlines .
"yes"))
541 "Default arguments to use when evaluating an inline source block.")
542 (put 'org-babel-default-inline-header-args
'safe-local-variable
543 (org-babel-header-args-safe-fn org-babel-safe-header-args
))
545 (defvar org-babel-data-names
'("tblname" "results" "name"))
547 (defvar org-babel-result-regexp
548 (concat "^[ \t]*#\\+"
549 (regexp-opt org-babel-data-names t
)
551 ;; FIXME The string below is `org-ts-regexp'
552 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
553 " \\)?\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*")
554 "Regular expression used to match result lines.
555 If the results are associated with a hash key then the hash will
556 be saved in the second match data.")
558 (defvar org-babel-result-w-name-regexp
559 (concat org-babel-result-regexp
560 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
562 (defvar org-babel-min-lines-for-block-output
10
563 "The minimum number of lines for block output.
564 If number of lines of output is equal to or exceeds this
565 value, the output is placed in a #+begin_example...#+end_example
566 block. Otherwise the output is marked as literal by inserting
567 colons at the starts of the lines. This variable only takes
568 effect if the :results output option is in effect.")
570 (defvar org-babel-noweb-error-langs nil
571 "Languages for which Babel will raise literate programming errors.
572 List of languages for which errors should be raised when the
573 source code block satisfying a noweb reference in this language
574 can not be resolved.")
576 (defvar org-babel-hash-show
4
577 "Number of initial characters to show of a hidden results hash.")
579 (defvar org-babel-hash-show-time nil
580 "Non-nil means show the time the code block was evaluated in the result hash.")
582 (defvar org-babel-after-execute-hook nil
583 "Hook for functions to be called after `org-babel-execute-src-block'")
585 (defun org-babel-named-src-block-regexp-for-name (name)
586 "This generates a regexp used to match a src block named NAME."
587 (concat org-babel-src-name-regexp
(regexp-quote name
)
588 "[ \t(]*[\r\n]\\(?:^[[:space:]]*#.*[\r\n]\\)*"
589 (substring org-babel-src-block-regexp
1)))
591 (defun org-babel-named-data-regexp-for-name (name)
592 "This generates a regexp used to match data named NAME."
593 (concat org-babel-result-regexp
(regexp-quote name
) "\\([ \t]\\|$\\)"))
596 (defvar call-process-region
)
597 (defvar org-babel-current-src-block-location nil
598 "Marker pointing to the src block currently being executed.
599 This may also point to a call line or an inline code block. If
600 multiple blocks are being executed (e.g., in chained execution
601 through use of the :var header argument) this marker points to
602 the outer-most code block.")
605 (defun org-babel-execute-src-block (&optional arg info params
)
606 "Execute the current source code block.
607 Insert the results of execution into the buffer. Source code
608 execution and the collection and formatting of results can be
609 controlled through a variety of header arguments.
611 With prefix argument ARG, force re-execution even if an existing
612 result cached in the buffer would otherwise have been returned.
614 Optionally supply a value for INFO in the form returned by
615 `org-babel-get-src-block-info'.
617 Optionally supply a value for PARAMS which will be merged with
618 the header arguments specified at the front of the source code
621 (let* ((org-babel-current-src-block-location
622 (or org-babel-current-src-block-location
624 (org-babel-where-is-src-block-head)
626 (and (org-babel-get-inline-src-block-matches)
627 (match-beginning 0))))
630 (org-babel-get-src-block-info)))
631 (merged-params (org-babel-merge-params (nth 2 info
) params
)))
632 (when (org-babel-check-evaluate
633 (let ((i info
)) (setf (nth 2 i
) merged-params
) i
))
634 (let* ((params (if params
635 (org-babel-process-params merged-params
)
637 (cachep (and (not arg
) (cdr (assoc :cache params
))
638 (string= "yes" (cdr (assoc :cache params
)))))
639 (new-hash (when cachep
(org-babel-sha1-hash info
)))
640 (old-hash (when cachep
(org-babel-current-result-hash)))
641 (cache-current-p (and (not arg
) new-hash
642 (equal new-hash old-hash
))))
645 (save-excursion ;; return cached result
646 (goto-char (org-babel-where-is-src-block-result nil info
))
647 (end-of-line 1) (forward-char 1)
648 (let ((result (org-babel-read-result)))
649 (message (replace-regexp-in-string
650 "%" "%%" (format "%S" result
))) result
)))
651 ((org-babel-confirm-evaluate
652 (let ((i info
)) (setf (nth 2 i
) merged-params
) i
))
653 (let* ((lang (nth 0 info
))
654 (result-params (cdr (assoc :result-params params
)))
655 (body (setf (nth 1 info
)
656 (if (org-babel-noweb-p params
:eval
)
657 (org-babel-expand-noweb-references info
)
659 (dir (cdr (assoc :dir params
)))
661 (or (and dir
(file-name-as-directory (expand-file-name dir
)))
663 (org-babel-call-process-region-original ;; for tramp handler
664 (or (org-bound-and-true-p
665 org-babel-call-process-region-original
)
666 (symbol-function 'call-process-region
)))
667 (indent (nth 5 info
))
670 (let ((call-process-region
672 (apply 'org-babel-tramp-handle-call-process-region
676 (let ((f (intern (concat "org-babel-execute:" f
))))
677 (when (fboundp f
) f
)))))
679 (or (funcall lang-check lang
)
682 (cdr (assoc lang org-src-lang-modes
))))
683 (error "No org-babel-execute function for %s!"
685 (message "executing %s code block%s..."
687 (if (nth 4 info
) (format " (%s)" (nth 4 info
)) ""))
688 (if (member "none" result-params
)
690 (funcall cmd body params
)
691 (message "result silenced")
694 (let ((result (funcall cmd body params
)))
695 (if (and (eq (cdr (assoc :result-type params
))
697 (or (member "vector" result-params
)
698 (member "table" result-params
))
699 (not (listp result
)))
700 (list (list result
)) result
)))
701 ;; If non-empty result and :file then write to :file.
702 (when (cdr (assoc :file params
))
704 (with-temp-file (cdr (assoc :file params
))
706 (org-babel-format-result
707 result
(cdr (assoc :sep
(nth 2 info
)))))))
708 (setq result
(cdr (assoc :file params
))))
709 ;; Possibly perform post process provided its appropriate.
710 (when (cdr (assoc :post params
))
711 (let ((*this
* (if (cdr (assoc :file params
))
712 (org-babel-result-to-file
713 (cdr (assoc :file params
))
714 (when (assoc :file-desc params
)
715 (or (cdr (assoc :file-desc params
))
718 (setq result
(org-babel-ref-resolve
719 (cdr (assoc :post params
))))
720 (when (cdr (assoc :file params
))
722 (remove "file" result-params
)))))
723 (org-babel-insert-result
724 result result-params info new-hash indent lang
))
725 (run-hooks 'org-babel-after-execute-hook
)
727 (setq call-process-region
728 'org-babel-call-process-region-original
)))))))))
730 (defun org-babel-expand-body:generic
(body params
&optional var-lines
)
731 "Expand BODY with PARAMS.
732 Expand a block of code with org-babel according to its header
733 arguments. This generic implementation of body expansion is
734 called for languages which have not defined their own specific
735 org-babel-expand-body:lang function."
736 (let ((pro (cdr (assoc :prologue params
)))
737 (epi (cdr (assoc :epilogue params
))))
738 (mapconcat #'identity
739 (append (when pro
(list pro
))
742 (when epi
(list epi
)))
746 (defun org-babel-expand-src-block (&optional arg info params
)
747 "Expand the current source code block.
748 Expand according to the source code block's header
749 arguments and pop open the results in a preview buffer."
751 (let* ((info (or info
(org-babel-get-src-block-info)))
753 (params (setf (nth 2 info
)
754 (sort (org-babel-merge-params (nth 2 info
) params
)
755 (lambda (el1 el2
) (string< (symbol-name (car el1
))
756 (symbol-name (car el2
)))))))
757 (body (setf (nth 1 info
)
758 (if (org-babel-noweb-p params
:eval
)
759 (org-babel-expand-noweb-references info
) (nth 1 info
))))
760 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
761 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
764 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
765 (org-babel-expand-body:generic
766 body params
(and (fboundp assignments-cmd
)
767 (funcall assignments-cmd params
))))))
768 (if (org-called-interactively-p 'any
)
771 (concat "*Org-Babel Preview " (buffer-name) "[ " lang
" ]*"))
774 (defun org-babel-edit-distance (s1 s2
)
775 "Return the edit (levenshtein) distance between strings S1 S2."
776 (let* ((l1 (length s1
))
778 (dist (vconcat (mapcar (lambda (_) (make-vector (1+ l2
) nil
))
779 (number-sequence 1 (1+ l1
)))))
780 (in (lambda (i j
) (aref (aref dist i
) j
))))
781 (setf (aref (aref dist
0) 0) 0)
782 (dolist (j (number-sequence 1 l2
))
783 (setf (aref (aref dist
0) j
) j
))
784 (dolist (i (number-sequence 1 l1
))
785 (setf (aref (aref dist i
) 0) i
)
786 (dolist (j (number-sequence 1 l2
))
787 (setf (aref (aref dist i
) j
)
789 (1+ (funcall in
(1- i
) j
))
790 (1+ (funcall in i
(1- j
)))
791 (+ (if (equal (aref s1
(1- i
)) (aref s2
(1- j
))) 0 1)
792 (funcall in
(1- i
) (1- j
)))))))
795 (defun org-babel-combine-header-arg-lists (original &rest others
)
796 "Combine a number of lists of header argument names and arguments."
797 (let ((results (copy-sequence original
)))
798 (dolist (new-list others
)
799 (dolist (arg-pair new-list
)
800 (let ((header (car arg-pair
))
801 (args (cdr arg-pair
)))
803 (cons arg-pair
(org-remove-if
804 (lambda (pair) (equal header
(car pair
)))
809 (defun org-babel-check-src-block ()
810 "Check for misspelled header arguments in the current code block."
812 ;; TODO: report malformed code block
813 ;; TODO: report incompatible combinations of header arguments
814 ;; TODO: report uninitialized variables
815 (let ((too-close 2) ;; <- control closeness to report potential match
816 (names (mapcar #'symbol-name org-babel-header-arg-names
)))
817 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg
)) 1))
818 (and (org-babel-where-is-src-block-head)
819 (org-babel-parse-header-arguments
821 (match-string 4))))))
823 (when (and (not (string= header name
))
824 (<= (org-babel-edit-distance header name
) too-close
)
825 (not (member header names
)))
826 (error "Supplied header \"%S\" is suspiciously close to \"%S\""
828 (message "No suspicious header arguments found.")))
831 (defun org-babel-insert-header-arg (&optional header-arg value
)
832 "Insert a header argument selecting from lists of common args and values."
834 (let* ((info (org-babel-get-src-block-info 'light
))
837 (lang-headers (intern (concat "org-babel-header-args:" lang
)))
838 (headers (org-babel-combine-header-arg-lists
839 org-babel-common-header-args-w-values
840 (when (boundp lang-headers
) (eval lang-headers
))))
841 (header-arg (or header-arg
842 (org-icompleting-read
845 (lambda (header-spec) (symbol-name (car header-spec
)))
847 (vals (cdr (assoc (intern header-arg
) headers
)))
851 (read-from-minibuffer "value: "))
855 (let ((arg (org-icompleting-read
858 (mapcar #'symbol-name group
)))))
859 (if (and arg
(not (string= "default" arg
)))
865 (goto-char (point-at-eol))
866 (unless (= (char-before (point)) ?\
) (insert " "))
867 (insert ":" header-arg
) (when value
(insert " " value
)))))
869 ;; Add support for completing-read insertion of header arguments after ":"
870 (defun org-babel-header-arg-expand ()
871 "Call `org-babel-enter-header-arg-w-completion' in appropriate contexts."
872 (when (and (equal (char-before) ?\
:) (org-babel-where-is-src-block-head))
873 (org-babel-enter-header-arg-w-completion (match-string 2))))
875 (defun org-babel-enter-header-arg-w-completion (&optional lang
)
876 "Insert header argument appropriate for LANG with completion."
877 (let* ((lang-headers-var (intern (concat "org-babel-header-args:" lang
)))
878 (lang-headers (when (boundp lang-headers-var
) (eval lang-headers-var
)))
879 (headers-w-values (org-babel-combine-header-arg-lists
880 org-babel-common-header-args-w-values lang-headers
))
881 (headers (mapcar #'symbol-name
(mapcar #'car headers-w-values
)))
882 (header (org-completing-read "Header Arg: " headers
))
883 (args (cdr (assoc (intern header
) headers-w-values
)))
884 (arg (when (and args
(listp args
))
886 (format "%s: " header
)
887 (mapcar #'symbol-name
(apply #'append args
))))))
888 (insert (concat header
" " (or arg
"")))
891 (add-hook 'org-tab-first-hook
'org-babel-header-arg-expand
)
894 (defun org-babel-load-in-session (&optional arg info
)
895 "Load the body of the current source-code block.
896 Evaluate the header arguments for the source block before
897 entering the session. After loading the body this pops open the
900 (let* ((info (or info
(org-babel-get-src-block-info)))
902 (params (nth 2 info
))
904 (user-error "No src code block at point")
906 (if (org-babel-noweb-p params
:eval
)
907 (org-babel-expand-noweb-references info
)
909 (session (cdr (assoc :session params
)))
910 (dir (cdr (assoc :dir params
)))
912 (or (and dir
(file-name-as-directory dir
)) default-directory
))
913 (cmd (intern (concat "org-babel-load-session:" lang
))))
914 (unless (fboundp cmd
)
915 (error "No org-babel-load-session function for %s!" lang
))
916 (pop-to-buffer (funcall cmd session body params
))
920 (defun org-babel-initiate-session (&optional arg info
)
921 "Initiate session for current code block.
922 If called with a prefix argument then resolve any variable
923 references in the header arguments and assign these variables in
924 the session. Copy the body of the code block to the kill ring."
926 (let* ((info (or info
(org-babel-get-src-block-info (not arg
))))
929 (params (nth 2 info
))
930 (session (cdr (assoc :session params
)))
931 (dir (cdr (assoc :dir params
)))
933 (or (and dir
(file-name-as-directory dir
)) default-directory
))
934 (init-cmd (intern (format "org-babel-%s-initiate-session" lang
)))
935 (prep-cmd (intern (concat "org-babel-prep-session:" lang
))))
936 (if (and (stringp session
) (string= session
"none"))
937 (error "This block is not using a session!"))
938 (unless (fboundp init-cmd
)
939 (error "No org-babel-initiate-session function for %s!" lang
))
940 (with-temp-buffer (insert (org-babel-trim body
))
941 (copy-region-as-kill (point-min) (point-max)))
943 (unless (fboundp prep-cmd
)
944 (error "No org-babel-prep-session function for %s!" lang
))
945 (funcall prep-cmd session params
))
946 (funcall init-cmd session params
)))
949 (defun org-babel-switch-to-session (&optional arg info
)
950 "Switch to the session of the current code block.
951 Uses `org-babel-initiate-session' to start the session. If called
952 with a prefix argument then this is passed on to
953 `org-babel-initiate-session'."
955 (pop-to-buffer (org-babel-initiate-session arg info
))
958 (defalias 'org-babel-pop-to-session
'org-babel-switch-to-session
)
960 (defvar org-src-window-setup
)
963 (defun org-babel-switch-to-session-with-code (&optional arg info
)
964 "Switch to code buffer and display session."
968 (let ((other-window-buffer (window-buffer (next-window))))
969 (set-window-buffer (next-window) (current-buffer))
970 (set-window-buffer (selected-window) other-window-buffer
))
972 (info (org-babel-get-src-block-info))
973 (org-src-window-setup 'reorganize-frame
))
975 (org-babel-switch-to-session arg info
))
977 (funcall swap-windows
)))
980 (defmacro org-babel-do-in-edit-buffer
(&rest body
)
981 "Evaluate BODY in edit buffer if there is a code block at point.
982 Return t if a code block was found at point, nil otherwise."
983 `(let ((org-src-window-setup 'switch-invisibly
))
984 (when (and (org-babel-where-is-src-block-head)
985 (org-edit-src-code nil nil nil
))
986 (unwind-protect (progn ,@body
)
987 (if (org-bound-and-true-p org-edit-src-from-org-mode
)
988 (org-edit-src-exit)))
990 (def-edebug-spec org-babel-do-in-edit-buffer
(body))
992 (defun org-babel-do-key-sequence-in-edit-buffer (key)
993 "Read key sequence and execute the command in edit buffer.
994 Enter a key sequence to be executed in the language major-mode
995 edit buffer. For example, TAB will alter the contents of the
996 Org-mode code block according to the effect of TAB in the
997 language major-mode buffer. For languages that support
998 interactive sessions, this can be used to send code from the Org
999 buffer to the session for evaluation using the native major-mode
1000 evaluation mechanisms."
1001 (interactive "kEnter key-sequence to execute in edit buffer: ")
1002 (org-babel-do-in-edit-buffer
1004 (key-binding (or key
(read-key-sequence nil
))))))
1006 (defvar org-bracket-link-regexp
)
1008 (defun org-babel-active-location-p ()
1009 (memq (car (save-match-data (org-element-context)))
1010 '(babel-call inline-babel-call inline-src-block src-block
)))
1013 (defun org-babel-open-src-block-result (&optional re-run
)
1014 "If `point' is on a src block then open the results of the
1015 source code block, otherwise return nil. With optional prefix
1016 argument RE-RUN the source-code block is evaluated even if
1017 results already exist."
1019 (let ((info (org-babel-get-src-block-info 'light
)))
1022 ;; go to the results, if there aren't any then run the block
1023 (goto-char (or (and (not re-run
) (org-babel-where-is-src-block-result))
1024 (progn (org-babel-execute-src-block)
1025 (org-babel-where-is-src-block-result))))
1027 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
1029 (if (looking-at org-bracket-link-regexp
)
1032 (let ((r (org-babel-format-result
1033 (org-babel-read-result) (cdr (assoc :sep
(nth 2 info
))))))
1034 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
1035 (delete-region (point-min) (point-max))
1040 (defmacro org-babel-map-src-blocks
(file &rest body
)
1041 "Evaluate BODY forms on each source-block in FILE.
1042 If FILE is nil evaluate BODY forms on source blocks in current
1043 buffer. During evaluation of BODY the following local variables
1044 are set relative to the currently matched code block.
1046 full-block ------- string holding the entirety of the code block
1047 beg-block -------- point at the beginning of the code block
1048 end-block -------- point at the end of the matched code block
1049 lang ------------- string holding the language of the code block
1050 beg-lang --------- point at the beginning of the lang
1051 end-lang --------- point at the end of the lang
1052 switches --------- string holding the switches
1053 beg-switches ----- point at the beginning of the switches
1054 end-switches ----- point at the end of the switches
1055 header-args ------ string holding the header-args
1056 beg-header-args -- point at the beginning of the header-args
1057 end-header-args -- point at the end of the header-args
1058 body ------------- string holding the body of the code block
1059 beg-body --------- point at the beginning of the body
1060 end-body --------- point at the end of the body"
1061 (declare (indent 1))
1062 (let ((tempvar (make-symbol "file")))
1063 `(let* ((,tempvar
,file
)
1064 (visited-p (or (null ,tempvar
)
1065 (get-file-buffer (expand-file-name ,tempvar
))))
1066 (point (point)) to-be-removed
)
1067 (save-window-excursion
1068 (when ,tempvar
(find-file ,tempvar
))
1069 (setq to-be-removed
(current-buffer))
1070 (goto-char (point-min))
1071 (while (re-search-forward org-babel-src-block-regexp nil t
)
1072 (when (org-babel-active-location-p)
1073 (goto-char (match-beginning 0))
1074 (let ((full-block (match-string 0))
1075 (beg-block (match-beginning 0))
1076 (end-block (match-end 0))
1077 (lang (match-string 2))
1078 (beg-lang (match-beginning 2))
1079 (end-lang (match-end 2))
1080 (switches (match-string 3))
1081 (beg-switches (match-beginning 3))
1082 (end-switches (match-end 3))
1083 (header-args (match-string 4))
1084 (beg-header-args (match-beginning 4))
1085 (end-header-args (match-end 4))
1086 (body (match-string 5))
1087 (beg-body (match-beginning 5))
1088 (end-body (match-end 5)))
1090 (goto-char end-block
)))))
1091 (unless visited-p
(kill-buffer to-be-removed
))
1092 (goto-char point
))))
1093 (def-edebug-spec org-babel-map-src-blocks
(form body
))
1096 (defmacro org-babel-map-inline-src-blocks
(file &rest body
)
1097 "Evaluate BODY forms on each inline source-block in FILE.
1098 If FILE is nil evaluate BODY forms on source blocks in current
1100 (declare (indent 1))
1101 (let ((tempvar (make-symbol "file")))
1102 `(let* ((,tempvar
,file
)
1103 (visited-p (or (null ,tempvar
)
1104 (get-file-buffer (expand-file-name ,tempvar
))))
1105 (point (point)) to-be-removed
)
1106 (save-window-excursion
1107 (when ,tempvar
(find-file ,tempvar
))
1108 (setq to-be-removed
(current-buffer))
1109 (goto-char (point-min))
1110 (while (re-search-forward org-babel-inline-src-block-regexp nil t
)
1111 (when (org-babel-active-location-p)
1112 (goto-char (match-beginning 1))
1113 (save-match-data ,@body
))
1114 (goto-char (match-end 0))))
1115 (unless visited-p
(kill-buffer to-be-removed
))
1116 (goto-char point
))))
1117 (def-edebug-spec org-babel-map-inline-src-blocks
(form body
))
1119 (defvar org-babel-lob-one-liner-regexp
)
1122 (defmacro org-babel-map-call-lines
(file &rest body
)
1123 "Evaluate BODY forms on each call line in FILE.
1124 If FILE is nil evaluate BODY forms on source blocks in current
1126 (declare (indent 1))
1127 (let ((tempvar (make-symbol "file")))
1128 `(let* ((,tempvar
,file
)
1129 (visited-p (or (null ,tempvar
)
1130 (get-file-buffer (expand-file-name ,tempvar
))))
1131 (point (point)) to-be-removed
)
1132 (save-window-excursion
1133 (when ,tempvar
(find-file ,tempvar
))
1134 (setq to-be-removed
(current-buffer))
1135 (goto-char (point-min))
1136 (while (re-search-forward org-babel-lob-one-liner-regexp nil t
)
1137 (when (org-babel-active-location-p)
1138 (goto-char (match-beginning 1))
1139 (save-match-data ,@body
))
1140 (goto-char (match-end 0))))
1141 (unless visited-p
(kill-buffer to-be-removed
))
1142 (goto-char point
))))
1143 (def-edebug-spec org-babel-map-call-lines
(form body
))
1146 (defmacro org-babel-map-executables
(file &rest body
)
1147 (declare (indent 1))
1148 (let ((tempvar (make-symbol "file"))
1149 (rx (make-symbol "rx")))
1150 `(let* ((,tempvar
,file
)
1151 (,rx
(concat "\\(" org-babel-src-block-regexp
1152 "\\|" org-babel-inline-src-block-regexp
1153 "\\|" org-babel-lob-one-liner-regexp
"\\)"))
1154 (visited-p (or (null ,tempvar
)
1155 (get-file-buffer (expand-file-name ,tempvar
))))
1156 (point (point)) to-be-removed
)
1157 (save-window-excursion
1158 (when ,tempvar
(find-file ,tempvar
))
1159 (setq to-be-removed
(current-buffer))
1160 (goto-char (point-min))
1161 (while (re-search-forward ,rx nil t
)
1162 (when (org-babel-active-location-p)
1163 (goto-char (match-beginning 1))
1164 (when (looking-at org-babel-inline-src-block-regexp
)
1166 (save-match-data ,@body
))
1167 (goto-char (match-end 0))))
1168 (unless visited-p
(kill-buffer to-be-removed
))
1169 (goto-char point
))))
1170 (def-edebug-spec org-babel-map-executables
(form body
))
1173 (defun org-babel-execute-buffer (&optional arg
)
1174 "Execute source code blocks in a buffer.
1175 Call `org-babel-execute-src-block' on every source block in
1176 the current buffer."
1178 (org-babel-eval-wipe-error-buffer)
1179 (org-save-outline-visibility t
1180 (org-babel-map-executables nil
1181 (if (looking-at org-babel-lob-one-liner-regexp
)
1182 (org-babel-lob-execute-maybe)
1183 (org-babel-execute-src-block arg
)))))
1186 (defun org-babel-execute-subtree (&optional arg
)
1187 "Execute source code blocks in a subtree.
1188 Call `org-babel-execute-src-block' on every source block in
1189 the current subtree."
1193 (org-narrow-to-subtree)
1194 (org-babel-execute-buffer arg
)
1198 (defun org-babel-sha1-hash (&optional info
)
1199 "Generate an sha1 hash based on the value of info."
1201 (let ((print-level nil
)
1202 (info (or info
(org-babel-get-src-block-info))))
1204 (sort (copy-sequence (nth 2 info
))
1205 (lambda (a b
) (string< (car a
) (car b
)))))
1206 (let* ((rm (lambda (lst)
1207 (dolist (p '("replace" "silent" "none"
1208 "append" "prepend"))
1209 (setq lst
(remove p lst
)))
1212 (let ((v (if (and (listp (cdr arg
)) (null (cddr arg
)))
1213 (copy-sequence (cdr arg
))
1215 (when (and v
(not (and (sequencep v
)
1219 ((and (listp v
) ; lists are sorted
1220 (member (car arg
) '(:result-params
)))
1221 (sort (funcall rm v
) #'string
<))
1222 ((and (stringp v
) ; strings are sorted
1223 (member (car arg
) '(:results
:exports
)))
1224 (mapconcat #'identity
(sort (funcall rm
(split-string v
))
1229 (params (nth 2 info
))
1230 (body (if (org-babel-noweb-p params
:eval
)
1231 (org-babel-expand-noweb-references info
) (nth 1 info
)))
1232 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
1233 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
1236 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
1237 (org-babel-expand-body:generic
1238 body params
(and (fboundp assignments-cmd
)
1239 (funcall assignments-cmd params
))))))
1240 (let* ((it (format "%s-%s"
1243 (delq nil
(mapcar (lambda (arg)
1244 (let ((normalized (funcall norm arg
)))
1246 (format "%S" normalized
))))
1250 (when (org-called-interactively-p 'interactive
) (message hash
))
1253 (defun org-babel-current-result-hash (&optional info
)
1254 "Return the current in-buffer hash."
1255 (org-babel-where-is-src-block-result nil info
)
1256 (org-no-properties (match-string 5)))
1258 (defun org-babel-set-current-result-hash (hash info
)
1259 "Set the current in-buffer hash to HASH."
1260 (org-babel-where-is-src-block-result nil info
)
1261 (save-excursion (goto-char (match-beginning 5))
1262 (mapc #'delete-overlay
(overlays-at (point)))
1263 (forward-char org-babel-hash-show
)
1264 (mapc #'delete-overlay
(overlays-at (point)))
1265 (replace-match hash nil nil nil
5)
1266 (goto-char (point-at-bol))
1267 (org-babel-hide-hash)))
1269 (defun org-babel-hide-hash ()
1270 "Hide the hash in the current results line.
1271 Only the initial `org-babel-hash-show' characters of the hash
1272 will remain visible."
1273 (add-to-invisibility-spec '(org-babel-hide-hash . t
))
1275 (when (and (re-search-forward org-babel-result-regexp nil t
)
1277 (let* ((start (match-beginning 5))
1278 (hide-start (+ org-babel-hash-show start
))
1280 (hash (match-string 5))
1282 (setq ov1
(make-overlay start hide-start
))
1283 (setq ov2
(make-overlay hide-start end
))
1284 (overlay-put ov2
'invisible
'org-babel-hide-hash
)
1285 (overlay-put ov1
'babel-hash hash
)))))
1287 (defun org-babel-hide-all-hashes ()
1288 "Hide the hash in the current buffer.
1289 Only the initial `org-babel-hash-show' characters of each hash
1290 will remain visible. This function should be called as part of
1291 the `org-mode-hook'."
1293 (while (and (not org-babel-hash-show-time
)
1294 (re-search-forward org-babel-result-regexp nil t
))
1295 (goto-char (match-beginning 0))
1296 (org-babel-hide-hash)
1297 (goto-char (match-end 0)))))
1298 (add-hook 'org-mode-hook
'org-babel-hide-all-hashes
)
1300 (defun org-babel-hash-at-point (&optional point
)
1301 "Return the value of the hash at POINT.
1302 The hash is also added as the last element of the kill ring.
1303 This can be called with C-c C-c."
1305 (let ((hash (car (delq nil
(mapcar
1306 (lambda (ol) (overlay-get ol
'babel-hash
))
1307 (overlays-at (or point
(point))))))))
1308 (when hash
(kill-new hash
) (message hash
))))
1309 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-hash-at-point
)
1311 (defun org-babel-result-hide-spec ()
1312 "Hide portions of results lines.
1313 Add `org-babel-hide-result' as an invisibility spec for hiding
1314 portions of results lines."
1315 (add-to-invisibility-spec '(org-babel-hide-result . t
)))
1316 (add-hook 'org-mode-hook
'org-babel-result-hide-spec
)
1318 (defvar org-babel-hide-result-overlays nil
1319 "Overlays hiding results.")
1321 (defun org-babel-result-hide-all ()
1322 "Fold all results in the current buffer."
1324 (org-babel-show-result-all)
1326 (while (re-search-forward org-babel-result-regexp nil t
)
1327 (save-excursion (goto-char (match-beginning 0))
1328 (org-babel-hide-result-toggle-maybe)))))
1330 (defun org-babel-show-result-all ()
1331 "Unfold all results in the current buffer."
1332 (mapc 'delete-overlay org-babel-hide-result-overlays
)
1333 (setq org-babel-hide-result-overlays nil
))
1336 (defun org-babel-hide-result-toggle-maybe ()
1337 "Toggle visibility of result at point."
1339 (let ((case-fold-search t
))
1341 (beginning-of-line 1)
1342 (looking-at org-babel-result-regexp
))
1343 (progn (org-babel-hide-result-toggle)
1344 t
) ;; to signal that we took action
1345 nil
))) ;; to signal that we did not
1347 (defun org-babel-hide-result-toggle (&optional force
)
1348 "Toggle the visibility of the current result."
1352 (if (re-search-forward org-babel-result-regexp nil t
)
1353 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
1355 (while (looking-at org-babel-multi-line-header-regexp
)
1357 (goto-char (- (org-babel-result-end) 1)) (point)))
1359 (if (memq t
(mapcar (lambda (overlay)
1360 (eq (overlay-get overlay
'invisible
)
1361 'org-babel-hide-result
))
1362 (overlays-at start
)))
1363 (if (or (not force
) (eq force
'off
))
1365 (when (member ov org-babel-hide-result-overlays
)
1366 (setq org-babel-hide-result-overlays
1367 (delq ov org-babel-hide-result-overlays
)))
1368 (when (eq (overlay-get ov
'invisible
)
1369 'org-babel-hide-result
)
1370 (delete-overlay ov
)))
1371 (overlays-at start
)))
1372 (setq ov
(make-overlay start end
))
1373 (overlay-put ov
'invisible
'org-babel-hide-result
)
1374 ;; make the block accessible to isearch
1376 ov
'isearch-open-invisible
1378 (when (member ov org-babel-hide-result-overlays
)
1379 (setq org-babel-hide-result-overlays
1380 (delq ov org-babel-hide-result-overlays
)))
1381 (when (eq (overlay-get ov
'invisible
)
1382 'org-babel-hide-result
)
1383 (delete-overlay ov
))))
1384 (push ov org-babel-hide-result-overlays
)))
1385 (error "Not looking at a result line"))))
1387 ;; org-tab-after-check-for-cycling-hook
1388 (add-hook 'org-tab-first-hook
'org-babel-hide-result-toggle-maybe
)
1389 ;; Remove overlays when changing major mode
1390 (add-hook 'org-mode-hook
1391 (lambda () (org-add-hook 'change-major-mode-hook
1392 'org-babel-show-result-all
'append
'local
)))
1394 (defvar org-file-properties
)
1395 (defun org-babel-params-from-properties (&optional lang
)
1396 "Retrieve parameters specified as properties.
1397 Return a list of association lists of source block params
1398 specified in the properties of the current outline entry."
1401 ;; DEPRECATED header arguments specified as separate property at
1402 ;; point of definition
1404 (org-babel-parse-multiple-vars
1407 (lambda (header-arg)
1408 (and (setq val
(org-entry-get (point) header-arg t
))
1409 (cons (intern (concat ":" header-arg
))
1410 (org-babel-read val
))))
1415 (org-babel-combine-header-arg-lists
1416 org-babel-common-header-args-w-values
1418 (setq sym
(intern (concat "org-babel-header-args:" lang
)))
1419 (and (boundp sym
) (eval sym
))))))))))
1420 ;; header arguments specified with the header-args property at
1422 (org-babel-parse-header-arguments
1423 (org-entry-get org-babel-current-src-block-location
1424 "header-args" 'inherit
))
1425 (when lang
;; language-specific header arguments at point of call
1426 (org-babel-parse-header-arguments
1427 (org-entry-get org-babel-current-src-block-location
1428 (concat "header-args:" lang
) 'inherit
))))))
1430 (defvar org-src-preserve-indentation
)
1431 (defun org-babel-parse-src-block-match ()
1432 "Parse the results from a match of the `org-babel-src-block-regexp'."
1433 (let* ((block-indentation (length (match-string 1)))
1434 (lang (org-no-properties (match-string 2)))
1435 (lang-headers (intern (concat "org-babel-default-header-args:" lang
)))
1436 (switches (match-string 3))
1437 (body (org-no-properties
1438 (let* ((body (match-string 5))
1439 (sub-length (- (length body
) 1)))
1440 (if (and (> sub-length
0)
1441 (string= "\n" (substring body sub-length
)))
1442 (substring body
0 sub-length
)
1444 (preserve-indentation (or org-src-preserve-indentation
1446 (string-match "-i\\>" switches
)))))
1448 ;; get block body less properties, protective commas, and indentation
1451 (insert (org-unescape-code-in-string body
))
1452 (unless preserve-indentation
(org-do-remove-indentation))
1454 (apply #'org-babel-merge-params
1455 org-babel-default-header-args
1456 (when (boundp lang-headers
) (eval lang-headers
))
1458 (org-babel-params-from-properties lang
)
1459 (list (org-babel-parse-header-arguments
1460 (org-no-properties (or (match-string 4) ""))))))
1462 block-indentation
)))
1464 (defun org-babel-parse-inline-src-block-match ()
1465 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
1466 (let* ((lang (org-no-properties (match-string 2)))
1467 (lang-headers (intern (concat "org-babel-default-header-args:" lang
))))
1469 (org-unescape-code-in-string (org-no-properties (match-string 5)))
1470 (apply #'org-babel-merge-params
1471 org-babel-default-inline-header-args
1472 (if (boundp lang-headers
) (eval lang-headers
) nil
)
1474 (org-babel-params-from-properties lang
)
1475 (list (org-babel-parse-header-arguments
1476 (org-no-properties (or (match-string 4) ""))))))
1479 (defun org-babel-balanced-split (string alts
)
1480 "Split STRING on instances of ALTS.
1481 ALTS is a cons of two character options where each option may be
1482 either the numeric code of a single character or a list of
1483 character alternatives. For example to split on balanced
1484 instances of \"[ \t]:\" set ALTS to '((32 9) . 58)."
1485 (let* ((matches (lambda (ch spec
) (if (listp spec
) (member ch spec
) (equal spec ch
))))
1486 (matched (lambda (ch last
)
1488 (and (funcall matches ch
(cdr alts
))
1489 (funcall matches last
(car alts
)))
1490 (funcall matches ch alts
))))
1491 (balance 0) (last 0)
1493 (mapc (lambda (ch) ; split on [], (), "" balanced instances of [ \t]:
1494 (setq balance
(+ balance
1495 (cond ((or (equal 91 ch
) (equal 40 ch
)) 1)
1496 ((or (equal 93 ch
) (equal 41 ch
)) -
1)
1498 (when (and (equal 34 ch
) (not (equal 92 last
)))
1499 (setq quote
(not quote
)))
1500 (setq partial
(cons ch partial
))
1501 (when (and (= balance
0) (not quote
) (funcall matched ch last
))
1502 (setq lst
(cons (apply #'string
(nreverse
1509 (string-to-list string
))
1510 (nreverse (cons (apply #'string
(nreverse partial
)) lst
))))
1512 (defun org-babel-join-splits-near-ch (ch list
)
1513 "Join splits where \"=\" is on either end of the split."
1514 (let ((last= (lambda (str) (= ch
(aref str
(1- (length str
))))))
1515 (first= (lambda (str) (= ch
(aref str
0)))))
1517 (org-reduce (lambda (acc el
)
1518 (let ((head (car acc
)))
1519 (if (and head
(or (funcall last
= head
) (funcall first
= el
)))
1520 (cons (concat head el
) (cdr acc
))
1522 list
:initial-value nil
))))
1524 (defun org-babel-parse-header-arguments (arg-string)
1525 "Parse a string of header arguments returning an alist."
1526 (when (> (length arg-string
) 0)
1527 (org-babel-parse-multiple-vars
1532 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1534 (cons (intern (match-string 1 arg
))
1535 (org-babel-read (org-babel-chomp (match-string 2 arg
))))
1536 (cons (intern (org-babel-chomp arg
)) nil
)))
1537 (let ((raw (org-babel-balanced-split arg-string
'((32 9) .
58))))
1538 (cons (car raw
) (mapcar (lambda (r) (concat ":" r
)) (cdr raw
)))))))))
1540 (defun org-babel-parse-multiple-vars (header-arguments)
1541 "Expand multiple variable assignments behind a single :var keyword.
1543 This allows expression of multiple variables with one :var as
1546 #+PROPERTY: var foo=1, bar=2"
1548 (mapc (lambda (pair)
1549 (if (eq (car pair
) :var
)
1550 (mapcar (lambda (v) (push (cons :var
(org-babel-trim v
)) results
))
1551 (org-babel-join-splits-near-ch
1552 61 (org-babel-balanced-split (cdr pair
) 32)))
1553 (push pair results
)))
1555 (nreverse results
)))
1557 (defun org-babel-process-params (params)
1558 "Expand variables in PARAMS and add summary parameters."
1559 (let* ((processed-vars (mapcar (lambda (el)
1560 (if (consp (cdr el
))
1562 (org-babel-ref-parse (cdr el
))))
1563 (org-babel-get-header params
:var
)))
1564 (vars-and-names (if (and (assoc :colname-names params
)
1565 (assoc :rowname-names params
))
1566 (list processed-vars
)
1567 (org-babel-disassemble-tables
1569 (cdr (assoc :hlines params
))
1570 (cdr (assoc :colnames params
))
1571 (cdr (assoc :rownames params
)))))
1572 (raw-result (or (cdr (assoc :results params
)) ""))
1573 (result-params (append
1574 (split-string (if (stringp raw-result
)
1577 (cdr (assoc :result-params params
)))))
1579 (mapcar (lambda (var) (cons :var var
)) (car vars-and-names
))
1581 (cons :colname-names
(or (cdr (assoc :colname-names params
))
1582 (cadr vars-and-names
)))
1583 (cons :rowname-names
(or (cdr (assoc :rowname-names params
))
1584 (caddr vars-and-names
)))
1585 (cons :result-params result-params
)
1586 (cons :result-type
(cond ((member "output" result-params
) 'output
)
1587 ((member "value" result-params
) 'value
)
1589 (org-babel-get-header params
:var
'other
))))
1591 ;; row and column names
1592 (defun org-babel-del-hlines (table)
1593 "Remove all 'hlines from TABLE."
1594 (remove 'hline table
))
1596 (defun org-babel-get-colnames (table)
1597 "Return the column names of TABLE.
1598 Return a cons cell, the `car' of which contains the TABLE less
1599 colnames, and the `cdr' of which contains a list of the column
1601 (if (equal 'hline
(nth 1 table
))
1602 (cons (cddr table
) (car table
))
1603 (cons (cdr table
) (car table
))))
1605 (defun org-babel-get-rownames (table)
1606 "Return the row names of TABLE.
1607 Return a cons cell, the `car' of which contains the TABLE less
1608 rownames, and the `cdr' of which contains a list of the rownames.
1609 Note: this function removes any hlines in TABLE."
1610 (let* ((table (org-babel-del-hlines table
))
1611 (rownames (funcall (lambda ()
1617 (setq tp
(cdr tp
))))
1619 (cons table rownames
)))
1621 (defun org-babel-put-colnames (table colnames
)
1622 "Add COLNAMES to TABLE if they exist."
1623 (if colnames
(apply 'list colnames
'hline table
) table
))
1625 (defun org-babel-put-rownames (table rownames
)
1626 "Add ROWNAMES to TABLE if they exist."
1628 (mapcar (lambda (row)
1630 (cons (or (pop rownames
) "") row
)
1634 (defun org-babel-pick-name (names selector
)
1635 "Select one out of an alist of row or column names.
1636 SELECTOR can be either a list of names in which case those names
1637 will be returned directly, or an index into the list NAMES in
1638 which case the indexed names will be return."
1639 (if (listp selector
)
1642 (if (and selector
(symbolp selector
) (not (equal t selector
)))
1643 (cdr (assoc selector names
))
1644 (if (integerp selector
)
1645 (nth (- selector
1) names
)
1646 (cdr (car (last names
))))))))
1648 (defun org-babel-disassemble-tables (vars hlines colnames rownames
)
1649 "Parse tables for further processing.
1650 Process the variables in VARS according to the HLINES,
1651 ROWNAMES and COLNAMES header arguments. Return a list consisting
1652 of the vars, cnames and rnames."
1653 (let (cnames rnames
)
1657 (when (listp (cdr var
))
1658 (when (and (not (equal colnames
"no"))
1659 (or colnames
(and (equal (nth 1 (cdr var
)) 'hline
)
1660 (not (member 'hline
(cddr (cdr var
)))))))
1661 (let ((both (org-babel-get-colnames (cdr var
))))
1662 (setq cnames
(cons (cons (car var
) (cdr both
))
1664 (setq var
(cons (car var
) (car both
)))))
1665 (when (and rownames
(not (equal rownames
"no")))
1666 (let ((both (org-babel-get-rownames (cdr var
))))
1667 (setq rnames
(cons (cons (car var
) (cdr both
))
1669 (setq var
(cons (car var
) (car both
)))))
1670 (when (and hlines
(not (equal hlines
"yes")))
1671 (setq var
(cons (car var
) (org-babel-del-hlines (cdr var
))))))
1674 (reverse cnames
) (reverse rnames
))))
1676 (defun org-babel-reassemble-table (table colnames rownames
)
1677 "Add column and row names to a table.
1678 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1679 to the table for reinsertion to org-mode."
1681 (let ((table (if (and rownames
(= (length table
) (length rownames
)))
1682 (org-babel-put-rownames table rownames
) table
)))
1683 (if (and colnames
(listp (car table
)) (= (length (car table
))
1685 (org-babel-put-colnames table colnames
) table
))
1688 (defun org-babel-where-is-src-block-head ()
1689 "Find where the current source block begins.
1690 Return the point at the beginning of the current source
1691 block. Specifically at the beginning of the #+BEGIN_SRC line.
1692 If the point is not on a source block then return nil."
1693 (let ((initial (point)) (case-fold-search t
) top bottom
)
1695 (save-excursion ;; on a source name line or a #+header line
1696 (beginning-of-line 1)
1697 (and (or (looking-at org-babel-src-name-regexp
)
1698 (looking-at org-babel-multi-line-header-regexp
))
1700 (while (and (forward-line 1)
1701 (or (looking-at org-babel-src-name-regexp
)
1702 (looking-at org-babel-multi-line-header-regexp
))))
1703 (looking-at org-babel-src-block-regexp
))
1705 (save-excursion ;; on a #+begin_src line
1706 (beginning-of-line 1)
1707 (and (looking-at org-babel-src-block-regexp
)
1709 (save-excursion ;; inside a src block
1711 (re-search-backward "^[ \t]*#\\+begin_src" nil t
) (setq top
(point))
1712 (re-search-forward "^[ \t]*#\\+end_src" nil t
) (setq bottom
(point))
1713 (< top initial
) (< initial bottom
)
1714 (progn (goto-char top
) (beginning-of-line 1)
1715 (looking-at org-babel-src-block-regexp
))
1719 (defun org-babel-goto-src-block-head ()
1720 "Go to the beginning of the current code block."
1722 (let ((head (org-babel-where-is-src-block-head)))
1723 (if head
(goto-char head
) (error "Not currently in a code block"))))
1726 (defun org-babel-goto-named-src-block (name)
1727 "Go to a named source-code block."
1729 (let ((completion-ignore-case t
)
1730 (case-fold-search t
)
1731 (under-point (thing-at-point 'line
)))
1732 (list (org-icompleting-read
1733 "source-block name: " (org-babel-src-block-names) nil t
1736 ((string-match (org-babel-noweb-wrap) under-point
)
1737 (let ((block-name (match-string 1 under-point
)))
1738 (string-match "[^(]*" block-name
)
1739 (match-string 0 block-name
)))
1741 ((string-match org-babel-lob-one-liner-regexp under-point
)
1742 (let ((source-info (car (org-babel-lob-get-info))))
1743 (if (string-match "^\\([^\\[]+?\\)\\(\\[.*\\]\\)?(" source-info
)
1744 (let ((source-name (match-string 1 source-info
)))
1747 ((string-match (concat "#\\+" org-babel-results-keyword
1748 "\\:\s+\\([^\\(]*\\)") under-point
)
1749 (match-string 1 under-point
))
1751 ((and (thing-at-point 'symbol
))
1752 (org-babel-find-named-block (thing-at-point 'symbol
))
1753 (thing-at-point 'symbol
))
1755 (let ((point (org-babel-find-named-block name
)))
1757 ;; taken from `org-open-at-point'
1758 (progn (org-mark-ring-push) (goto-char point
) (org-show-context))
1759 (message "source-code block '%s' not found in this buffer" name
))))
1761 (defun org-babel-find-named-block (name)
1762 "Find a named source-code block.
1763 Return the location of the source block identified by source
1764 NAME, or nil if no such block exists. Set match data according to
1765 org-babel-named-src-block-regexp."
1767 (let ((case-fold-search t
)
1768 (regexp (org-babel-named-src-block-regexp-for-name name
)) msg
)
1769 (goto-char (point-min))
1770 (when (or (re-search-forward regexp nil t
)
1771 (re-search-backward regexp nil t
))
1772 (match-beginning 0)))))
1774 (defun org-babel-src-block-names (&optional file
)
1775 "Returns the names of source blocks in FILE or the current buffer."
1777 (when file
(find-file file
)) (goto-char (point-min))
1778 (let ((case-fold-search t
) names
)
1779 (while (re-search-forward org-babel-src-name-w-name-regexp nil t
)
1780 (setq names
(cons (match-string 3) names
)))
1784 (defun org-babel-goto-named-result (name)
1785 "Go to a named result."
1787 (let ((completion-ignore-case t
))
1788 (list (org-icompleting-read "source-block name: "
1789 (org-babel-result-names) nil t
))))
1790 (let ((point (org-babel-find-named-result name
)))
1792 ;; taken from `org-open-at-point'
1793 (progn (goto-char point
) (org-show-context))
1794 (message "result '%s' not found in this buffer" name
))))
1796 (defun org-babel-find-named-result (name &optional point
)
1797 "Find a named result.
1798 Return the location of the result named NAME in the current
1799 buffer or nil if no such result exists."
1801 (let ((case-fold-search t
))
1802 (goto-char (or point
(point-min)))
1803 (catch 'is-a-code-block
1804 (when (re-search-forward
1805 (concat org-babel-result-regexp
1806 "[ \t]" (regexp-quote name
) "[ \t]*[\n\f\v\r]") nil t
)
1807 (when (and (string= "name" (downcase (match-string 1)))
1808 (or (beginning-of-line 1)
1809 (looking-at org-babel-src-block-regexp
)
1810 (looking-at org-babel-multi-line-header-regexp
)
1811 (looking-at org-babel-lob-one-liner-regexp
)))
1812 (throw 'is-a-code-block
(org-babel-find-named-result name
(point))))
1813 (beginning-of-line 0) (point))))))
1815 (defun org-babel-result-names (&optional file
)
1816 "Returns the names of results in FILE or the current buffer."
1818 (when file
(find-file file
)) (goto-char (point-min))
1819 (let ((case-fold-search t
) names
)
1820 (while (re-search-forward org-babel-result-w-name-regexp nil t
)
1821 (setq names
(cons (match-string 4) names
)))
1825 (defun org-babel-next-src-block (&optional arg
)
1826 "Jump to the next source block.
1827 With optional prefix argument ARG, jump forward ARG many source blocks."
1829 (org-next-block arg nil org-babel-src-block-regexp
))
1832 (defun org-babel-previous-src-block (&optional arg
)
1833 "Jump to the previous source block.
1834 With optional prefix argument ARG, jump backward ARG many source blocks."
1836 (org-previous-block arg org-babel-src-block-regexp
))
1838 (defvar org-babel-load-languages
)
1841 (defun org-babel-mark-block ()
1842 "Mark current src block."
1844 (let ((head (org-babel-where-is-src-block-head)))
1848 (looking-at org-babel-src-block-regexp
))
1849 (push-mark (match-end 5) nil t
)
1850 (goto-char (match-beginning 5)))))
1852 (defun org-babel-demarcate-block (&optional arg
)
1853 "Wrap or split the code in the region or on the point.
1854 When called from inside of a code block the current block is
1855 split. When called from outside of a code block a new code block
1856 is created. In both cases if the region is demarcated and if the
1857 region is not active then the point is demarcated."
1859 (let ((info (org-babel-get-src-block-info 'light
))
1860 (headers (progn (org-babel-where-is-src-block-head)
1862 (stars (concat (make-string (or (org-current-level) 1) ?
*) " ")))
1868 (let ((lang (nth 0 info
))
1869 (indent (make-string (nth 5 info
) ?
)))
1870 (when (string-match "^[[:space:]]*$"
1871 (buffer-substring (point-at-bol)
1873 (delete-region (point-at-bol) (point-at-eol)))
1875 (if (looking-at "^") "" "\n")
1876 indent
"#+end_src\n"
1877 (if arg stars indent
) "\n"
1878 indent
"#+begin_src " lang
1879 (if (> (length headers
) 1)
1880 (concat " " headers
) headers
)
1881 (if (looking-at "[\n\r]")
1883 (concat "\n" (make-string (current-column) ?
)))))))
1884 (move-end-of-line 2))
1885 (sort (if (org-region-active-p) (list (mark) (point)) (list (point))) #'>))
1886 (let ((start (point))
1887 (lang (org-icompleting-read
1889 (mapcar #'symbol-name
1891 (append (mapcar #'car org-babel-load-languages
)
1892 (mapcar (lambda (el) (intern (car el
)))
1893 org-src-lang-modes
))))))
1894 (body (delete-and-extract-region
1895 (if (org-region-active-p) (mark) (point)) (point))))
1896 (insert (concat (if (looking-at "^") "" "\n")
1897 (if arg
(concat stars
"\n") "")
1898 "#+begin_src " lang
"\n"
1900 (if (or (= (length body
) 0)
1901 (string-match "[\r\n]$" body
)) "" "\n")
1903 (goto-char start
) (move-end-of-line 1)))))
1905 (defvar org-babel-lob-one-liner-regexp
)
1906 (defun org-babel-where-is-src-block-result (&optional insert info hash indent
)
1907 "Find where the current source block results begin.
1908 Return the point at the beginning of the result of the current
1909 source block. Specifically at the beginning of the results line.
1910 If no result exists for this block then create a results line
1911 following the source block."
1913 (let* ((case-fold-search t
)
1914 (on-lob-line (save-excursion
1915 (beginning-of-line 1)
1916 (looking-at org-babel-lob-one-liner-regexp
)))
1917 (inlinep (when (org-babel-get-inline-src-block-matches)
1919 (name (nth 4 (or info
(org-babel-get-src-block-info 'light
))))
1920 (head (unless on-lob-line
(org-babel-where-is-src-block-head)))
1922 (when head
(goto-char head
))
1923 (org-with-wide-buffer
1925 found
;; was there a result (before we potentially insert one)
1930 ;; - return t if it is found, else return nil
1931 ;; - if it does not need to be rebuilt, then don't set end
1932 ;; - if it does need to be rebuilt then do set end
1933 name
(setq beg
(org-babel-find-named-result name
))
1935 (when (and hash
(not (string= hash
(match-string 5))))
1936 (goto-char beg
) (setq end beg
) ;; beginning of result
1938 (delete-region end
(org-babel-result-end)) nil
)))
1941 ;; - return t if it is found, else return nil
1942 ;; - if it is found, and the hash doesn't match, delete and set end
1943 (or on-lob-line
(re-search-forward "^[ \t]*#\\+end_src" nil t
))
1944 (progn (end-of-line 1)
1945 (if (eobp) (insert "\n") (forward-char 1))
1949 (progn ;; unnamed results line already exists
1951 (while (re-search-forward "[^ \f\t\n\r\v]" nil t
)
1952 (beginning-of-line 1)
1954 ((looking-at (concat org-babel-result-regexp
"\n"))
1955 (throw 'non-comment t
))
1956 ((and (looking-at "^[ \t]*#")
1958 org-babel-lob-one-liner-regexp
)))
1960 (t (throw 'non-comment nil
))))))
1961 (let ((this-hash (match-string 5)))
1963 ;; must remove and rebuild if hash!=old-hash
1964 (if (and hash
(not (string= hash this-hash
)))
1966 (setq end
(point-at-bol))
1968 (delete-region end
(org-babel-result-end))
1970 (setq end nil
))))))))))
1971 (if (not (and insert end
)) found
1974 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1976 (when (wholenump indent
) (make-string indent ?
))
1977 "#+" org-babel-results-keyword
1979 (if org-babel-hash-show-time
1981 "["(format-time-string "<%Y-%m-%d %H:%M:%S>")" "hash
"]")
1982 (concat "["hash
"]")))
1984 (when name
(concat " " name
)) "\n"))
1985 (unless beg
(insert "\n") (backward-char))
1986 (beginning-of-line 0)
1987 (if hash
(org-babel-hide-hash))
1990 (defvar org-block-regexp
)
1991 (defun org-babel-read-result ()
1992 "Read the result at `point' into emacs-lisp."
1993 (let ((case-fold-search t
) result-string
)
1995 ((org-at-table-p) (org-babel-read-table))
1996 ((org-at-item-p) (org-babel-read-list))
1997 ((looking-at org-bracket-link-regexp
) (org-babel-read-link))
1998 ((looking-at org-block-regexp
) (org-remove-indentation (match-string 4)))
1999 ((or (looking-at "^[ \t]*: ") (looking-at "^[ \t]*:$"))
2002 (mapconcat (lambda (line)
2003 (or (and (> (length line
) 1)
2004 (string-match "^[ \t]*: ?\\(.+\\)" line
)
2005 (match-string 1 line
))
2009 (point) (org-babel-result-end)) "[\r\n]+")
2011 (or (org-babel-number-p result-string
) result-string
))
2012 ((looking-at org-babel-result-regexp
)
2013 (save-excursion (forward-line 1) (org-babel-read-result))))))
2015 (defun org-babel-read-table ()
2016 "Read the table at `point' into emacs-lisp."
2017 (mapcar (lambda (row)
2018 (if (and (symbolp row
) (equal row
'hline
)) row
2019 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
)) row
)))
2020 (org-table-to-lisp)))
2022 (defun org-babel-read-list ()
2023 "Read the list at `point' into emacs-lisp."
2024 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
))
2025 (mapcar #'cadr
(cdr (org-list-parse-list)))))
2027 (defvar org-link-types-re
)
2028 (defun org-babel-read-link ()
2029 "Read the link at `point' into emacs-lisp.
2030 If the path of the link is a file path it is expanded using
2031 `expand-file-name'."
2032 (let* ((case-fold-search t
)
2033 (raw (and (looking-at org-bracket-link-regexp
)
2034 (org-no-properties (match-string 1))))
2035 (type (and (string-match org-link-types-re raw
)
2036 (match-string 1 raw
))))
2038 ((not type
) (expand-file-name raw
))
2039 ((string= type
"file")
2040 (and (string-match "file\\(.*\\):\\(.+\\)" raw
)
2041 (expand-file-name (match-string 2 raw
))))
2044 (defun org-babel-format-result (result &optional sep
)
2045 "Format RESULT for writing to file."
2046 (let ((echo-res (lambda (r) (if (stringp r
) r
(format "%S" r
)))))
2050 result
(list :sep
(or sep
"\t") :fmt echo-res
))
2052 (funcall echo-res result
))))
2054 (defun org-babel-insert-result
2055 (result &optional result-params info hash indent lang
)
2056 "Insert RESULT into the current buffer.
2057 By default RESULT is inserted after the end of the
2058 current source block. With optional argument RESULT-PARAMS
2059 controls insertion of results in the org-mode file.
2060 RESULT-PARAMS can take the following values:
2062 replace - (default option) insert results after the source block
2063 replacing any previously inserted results
2065 silent -- no results are inserted into the Org-mode buffer but
2066 the results are echoed to the minibuffer and are
2067 ingested by Emacs (a potentially time consuming
2070 file ---- the results are interpreted as a file path, and are
2071 inserted into the buffer using the Org-mode file syntax
2073 list ---- the results are interpreted as an Org-mode list.
2075 raw ----- results are added directly to the Org-mode file. This
2076 is a good option if you code block will output org-mode
2079 drawer -- results are added directly to the Org-mode file as with
2080 \"raw\", but are wrapped in a RESULTS drawer, allowing
2081 them to later be replaced or removed automatically.
2083 org ----- results are added inside of a \"#+BEGIN_SRC org\" block.
2084 They are not comma-escaped when inserted, but Org syntax
2085 here will be discarded when exporting the file.
2087 html ---- results are added inside of a #+BEGIN_HTML block. This
2088 is a good option if you code block will output html
2091 latex --- results are added inside of a #+BEGIN_LATEX block.
2092 This is a good option if you code block will output
2093 latex formatted text.
2095 code ---- the results are extracted in the syntax of the source
2096 code of the language being evaluated and are added
2097 inside of a #+BEGIN_SRC block with the source-code
2098 language set appropriately. Note this relies on the
2099 optional LANG argument."
2100 (if (stringp result
)
2102 (setq result
(org-no-properties result
))
2103 (when (member "file" result-params
)
2104 (setq result
(org-babel-result-to-file
2105 result
(when (assoc :file-desc
(nth 2 info
))
2106 (or (cdr (assoc :file-desc
(nth 2 info
)))
2108 (unless (listp result
) (setq result
(format "%S" result
))))
2109 (if (and result-params
(member "silent" result-params
))
2111 (message (replace-regexp-in-string "%" "%%" (format "%S" result
)))
2116 (when (or (org-babel-get-inline-src-block-matches)
2117 (org-babel-get-lob-one-liner-matches))
2118 (goto-char (match-end 0))
2119 (insert (if (listp result
) "\n" " "))
2121 (existing-result (unless inlinep
2122 (org-babel-where-is-src-block-result
2123 t info hash indent
)))
2125 (cdr (assoc :results_switches
(nth 2 info
))))
2126 (visible-beg (copy-marker (point-min)))
2127 (visible-end (copy-marker (point-max)))
2128 ;; When results exist outside of the current visible
2129 ;; region of the buffer, be sure to widen buffer to
2131 (outside-scope-p (and existing-result
2132 (or (> visible-beg existing-result
)
2133 (<= visible-end existing-result
))))
2135 (when (and (stringp result
) ; ensure results end in a newline
2137 (> (length result
) 0)
2138 (not (or (string-equal (substring result -
1) "\n")
2139 (string-equal (substring result -
1) "\r"))))
2140 (setq result
(concat result
"\n")))
2143 (when outside-scope-p
(widen))
2144 (if (not existing-result
)
2145 (setq beg
(or inlinep
(point)))
2146 (goto-char existing-result
)
2148 (re-search-forward "#" nil t
)
2149 (setq indent
(- (current-column) 1)))
2153 ((member "replace" result-params
)
2154 (delete-region (point) (org-babel-result-end)))
2155 ((member "append" result-params
)
2156 (goto-char (org-babel-result-end)) (setq beg
(point-marker)))
2157 ((member "prepend" result-params
)))) ; already there
2158 (setq results-switches
2159 (if results-switches
(concat " " results-switches
) ""))
2160 (let ((wrap (lambda (start finish
&optional no-escape
)
2161 (goto-char end
) (insert (concat finish
"\n"))
2162 (goto-char beg
) (insert (concat start
"\n"))
2164 (org-escape-code-in-region (min (point) end
) end
))
2165 (goto-char end
) (goto-char (point-at-eol))
2166 (setq end
(point-marker))))
2167 (proper-list-p (lambda (it) (and (listp it
) (null (cdr (last it
)))))))
2168 ;; insert results based on type
2170 ;; do nothing for an empty result
2172 ;; insert a list if preferred
2173 ((member "list" result-params
)
2176 (org-list-to-generic
2179 (lambda (el) (list nil
(if (stringp el
) el
(format "%S" el
))))
2180 (if (listp result
) result
(split-string result
"\n" t
))))
2181 '(:splicep nil
:istart
"- " :iend
"\n")))
2183 ;; assume the result is a table if it's not a string
2184 ((funcall proper-list-p result
)
2186 (insert (concat (orgtbl-to-orgtbl
2187 (if (or (eq 'hline
(car result
))
2188 (and (listp (car result
))
2189 (listp (cdr (car result
)))))
2190 result
(list result
))
2191 '(:fmt
(lambda (cell) (format "%s" cell
)))) "\n"))
2192 (goto-char beg
) (when (org-at-table-p) (org-table-align)))
2193 ((and (listp result
) (not (funcall proper-list-p result
)))
2194 (insert (format "%s\n" result
)))
2195 ((member "file" result-params
)
2196 (when inlinep
(goto-char inlinep
))
2198 (t (goto-char beg
) (insert result
)))
2199 (when (funcall proper-list-p result
) (goto-char (org-table-end)))
2200 (setq end
(point-marker))
2201 ;; possibly wrap result
2203 ((assoc :wrap
(nth 2 info
))
2204 (let ((name (or (cdr (assoc :wrap
(nth 2 info
))) "RESULTS")))
2205 (funcall wrap
(concat "#+BEGIN_" name
)
2206 (concat "#+END_" (car (org-split-string name
))))))
2207 ((member "html" result-params
)
2208 (funcall wrap
"#+BEGIN_HTML" "#+END_HTML"))
2209 ((member "latex" result-params
)
2210 (funcall wrap
"#+BEGIN_LaTeX" "#+END_LaTeX"))
2211 ((member "org" result-params
)
2212 (goto-char beg
) (if (org-at-table-p) (org-cycle))
2213 (funcall wrap
"#+BEGIN_SRC org" "#+END_SRC"))
2214 ((member "code" result-params
)
2215 (funcall wrap
(format "#+BEGIN_SRC %s%s" (or lang
"none") results-switches
)
2217 ((member "raw" result-params
)
2218 (goto-char beg
) (if (org-at-table-p) (org-cycle)))
2219 ((or (member "drawer" result-params
)
2220 ;; Stay backward compatible with <7.9.2
2221 (member "wrap" result-params
))
2222 (goto-char beg
) (if (org-at-table-p) (org-cycle))
2223 (funcall wrap
":RESULTS:" ":END:" 'no-escape
))
2224 ((and (not (funcall proper-list-p result
))
2225 (not (member "file" result-params
)))
2226 (org-babel-examplify-region beg end results-switches
)
2227 (setq end
(point)))))
2228 ;; possibly indent the results to match the #+results line
2229 (when (and (not inlinep
) (numberp indent
) indent
(> indent
0)
2230 ;; in this case `table-align' does the work for us
2231 (not (and (listp result
)
2232 (member "append" result-params
))))
2233 (indent-rigidly beg end indent
))
2235 (if (member "value" result-params
)
2236 (message "Code block returned no value.")
2237 (message "Code block produced no output."))
2238 (message "Code block evaluation complete.")))
2239 (when outside-scope-p
(narrow-to-region visible-beg visible-end
))
2240 (set-marker visible-beg nil
)
2241 (set-marker visible-end nil
))))))
2243 (defun org-babel-remove-result (&optional info keep-keyword
)
2244 "Remove the result of the current source block."
2246 (let ((location (org-babel-where-is-src-block-result nil info
)))
2249 (goto-char location
)
2250 (when (looking-at (concat org-babel-result-regexp
".*$"))
2252 (if keep-keyword
(1+ (match-end 0)) (1- (match-beginning 0)))
2253 (progn (forward-line 1) (org-babel-result-end))))))))
2255 (defun org-babel-result-end ()
2256 "Return the point at the end of the current set of results."
2259 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
2260 ((org-at-item-p) (let* ((struct (org-list-struct))
2261 (prvs (org-list-prevs-alist struct
)))
2262 (org-list-get-list-end (point-at-bol) struct prvs
)))
2263 ((let ((case-fold-search t
)) (looking-at "^\\([ \t]*\\):results:"))
2264 (progn (re-search-forward (concat "^" (match-string 1) ":END:"))
2265 (forward-char 1) (point)))
2267 (let ((case-fold-search t
))
2268 (if (looking-at (concat "[ \t]*#\\+begin_\\([^ \t\n\r]+\\)"))
2269 (progn (re-search-forward (concat "[ \t]*#\\+end_" (match-string 1))
2272 (while (looking-at "[ \t]*\\(: \\|:$\\|\\[\\[\\)")
2276 (defun org-babel-result-to-file (result &optional description
)
2277 "Convert RESULT into an `org-mode' link with optional DESCRIPTION.
2278 If the `default-directory' is different from the containing
2279 file's directory then expand relative links."
2280 (when (stringp result
)
2281 (format "[[file:%s]%s]"
2282 (if (and default-directory
2284 (not (string= (expand-file-name default-directory
)
2286 (file-name-directory buffer-file-name
)))))
2287 (expand-file-name result default-directory
)
2289 (if description
(concat "[" description
"]") ""))))
2291 (defvar org-babel-capitalize-example-region-markers nil
2292 "Make true to capitalize begin/end example markers inserted by code blocks.")
2294 (define-obsolete-function-alias
2295 'org-babel-examplize-region
2296 'org-babel-examplify-region
"24.5")
2298 (defun org-babel-examplify-region (beg end
&optional results-switches
)
2299 "Comment out region using the inline '==' or ': ' org example quote."
2301 (let ((chars-between (lambda (b e
)
2302 (not (string-match "^[\\s]*$"
2303 (buffer-substring b e
)))))
2304 (maybe-cap (lambda (str) (if org-babel-capitalize-example-region-markers
2306 (beg-bol (save-excursion (goto-char beg
) (point-at-bol)))
2307 (end-bol (save-excursion (goto-char end
) (point-at-bol)))
2308 (end-eol (save-excursion (goto-char end
) (point-at-eol))))
2309 (if (and (not (= end end-bol
))
2310 (or (funcall chars-between beg-bol beg
)
2311 (funcall chars-between end end-eol
)))
2314 (insert (format org-babel-inline-result-wrap
2315 (prog1 (buffer-substring beg end
)
2316 (delete-region beg end
)))))
2317 (let ((size (count-lines beg end
)))
2319 (cond ((= size
0)) ; do nothing for an empty result
2320 ((< size org-babel-min-lines-for-block-output
)
2323 (beginning-of-line 1) (insert ": ") (forward-line 1)))
2326 (insert (if results-switches
2328 (funcall maybe-cap
"#+begin_example")
2330 (funcall maybe-cap
"#+begin_example\n")))
2331 (if (markerp end
) (goto-char end
) (forward-char (- end beg
)))
2332 (insert (funcall maybe-cap
"#+end_example\n")))))))))
2334 (defun org-babel-update-block-body (new-body)
2335 "Update the body of the current code block to NEW-BODY."
2336 (if (not (org-babel-where-is-src-block-head))
2337 (error "Not in a source block")
2339 (replace-match (concat (org-babel-trim (org-remove-indentation new-body
))
2341 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
2343 (defun org-babel-merge-params (&rest plists
)
2344 "Combine all parameter association lists in PLISTS.
2345 Later elements of PLISTS override the values of previous elements.
2346 This takes into account some special considerations for certain
2347 parameters when merging lists."
2348 (let* ((results-exclusive-groups
2349 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2350 (cdr (assoc 'results org-babel-common-header-args-w-values
))))
2351 (exports-exclusive-groups
2352 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2353 (cdr (assoc 'exports org-babel-common-header-args-w-values
))))
2355 (e-merge (lambda (exclusive-groups &rest result-params
)
2356 ;; maintain exclusivity of mutually exclusive parameters
2358 (mapc (lambda (new-params)
2359 (mapc (lambda (new-param)
2360 (mapc (lambda (exclusive-group)
2361 (when (member new-param exclusive-group
)
2362 (mapcar (lambda (excluded-param)
2369 (setq output
(org-uniquify
2370 (cons new-param output
))))
2374 params results exports tangle noweb cache vars shebang comments padline
2383 (let ((name (if (listp (cdr pair
))
2385 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
2387 (intern (match-string 1 (cdr pair
)))))))
2391 (if (member name
(mapcar #'car vars
))
2393 (push name clearnames
)
2397 (unless (equal (car p
) name
) p
))
2400 (list (cons name pair
))))
2401 ;; if no name is given and we already have named variables
2402 ;; then assign to named variables in order
2403 (if (and vars
(nth variable-index vars
))
2404 (let ((name (car (nth variable-index vars
))))
2405 (push name clearnames
) ; clear out colnames
2408 (prog1 (setf (cddr (nth variable-index vars
))
2409 (concat (symbol-name name
) "=" (cdr pair
)))
2410 (incf variable-index
)))
2411 (error "Variable \"%s\" must be assigned a default value"
2414 (setq results
(funcall e-merge results-exclusive-groups
2417 (let ((r (cdr pair
)))
2418 (if (stringp r
) r
(eval r
)))))))
2421 (setq results
(funcall e-merge results-exclusive-groups
2423 (unless (or (member "both" exports
)
2424 (member "none" exports
)
2425 (member "code" exports
))
2426 (setq exports
(funcall e-merge exports-exclusive-groups
2427 exports
'("results"))))
2428 (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))
2430 (setq exports
(funcall e-merge exports-exclusive-groups
2431 exports
(split-string (cdr pair
)))))
2432 (:tangle
;; take the latest -- always overwrite
2433 (setq tangle
(or (list (cdr pair
)) tangle
)))
2435 (setq noweb
(funcall e-merge
2436 '(("yes" "no" "tangle" "no-export"
2437 "strip-export" "eval"))
2439 (split-string (or (cdr pair
) "")))))
2441 (setq cache
(funcall e-merge
'(("yes" "no")) cache
2442 (split-string (or (cdr pair
) "")))))
2444 (setq padline
(funcall e-merge
'(("yes" "no")) padline
2445 (split-string (or (cdr pair
) "")))))
2446 (:shebang
;; take the latest -- always overwrite
2447 (setq shebang
(or (list (cdr pair
)) shebang
)))
2449 (setq comments
(funcall e-merge
'(("yes" "no")) comments
2450 (split-string (or (cdr pair
) "")))))
2451 (t ;; replace: this covers e.g. :session
2452 (setq params
(cons pair
(assq-delete-all (car pair
) params
))))))
2455 (setq vars
(reverse vars
))
2456 (while vars
(setq params
(cons (cons :var
(cddr (pop vars
))) params
)))
2457 ;; clear out col-names and row-names for replaced variables
2462 (when (assoc param params
)
2463 (setf (cdr (assoc param params
))
2464 (org-remove-if (lambda (pair) (equal (car pair
) name
))
2465 (cdr (assoc param params
))))
2466 (setf params
(org-remove-if (lambda (pair) (and (equal (car pair
) param
)
2469 (list :colname-names
:rowname-names
)))
2473 (let ((key (intern (concat ":" (symbol-name hd
))))
2475 (setf params
(cons (cons key
(mapconcat 'identity val
" ")) params
))))
2476 '(results exports tangle noweb padline cache shebang comments
))
2479 (defvar org-babel-use-quick-and-dirty-noweb-expansion nil
2480 "Set to true to use regular expressions to expand noweb references.
2481 This results in much faster noweb reference expansion but does
2482 not properly allow code blocks to inherit the \":noweb-ref\"
2483 header argument from buffer or subtree wide properties.")
2485 (defun org-babel-noweb-p (params context
)
2486 "Check if PARAMS require expansion in CONTEXT.
2487 CONTEXT may be one of :tangle, :export or :eval."
2489 (intersect (lambda (as bs
)
2491 (if (member (car as
) bs
)
2493 (funcall intersect
(cdr as
) bs
))))))
2494 (funcall intersect
(case context
2495 (:tangle
'("yes" "tangle" "no-export" "strip-export"))
2496 (:eval
'("yes" "no-export" "strip-export" "eval"))
2498 (split-string (or (cdr (assoc :noweb params
)) "")))))
2500 (defun org-babel-expand-noweb-references (&optional info parent-buffer
)
2501 "Expand Noweb references in the body of the current source code block.
2503 For example the following reference would be replaced with the
2504 body of the source-code block named 'example-block'.
2508 Note that any text preceding the <<foo>> construct on a line will
2509 be interposed between the lines of the replacement text. So for
2510 example if <<foo>> is placed behind a comment, then the entire
2511 replacement text will also be commented.
2513 This function must be called from inside of the buffer containing
2514 the source-code block which holds BODY.
2516 In addition the following syntax can be used to insert the
2517 results of evaluating the source-code block named 'example-block'.
2521 Any optional arguments can be passed to example-block by placing
2522 the arguments inside the parenthesis following the convention
2523 defined by `org-babel-lob'. For example
2525 <<example-block(a=9)>>
2527 would set the value of argument \"a\" equal to \"9\". Note that
2528 these arguments are not evaluated in the current source-code
2529 block but are passed literally to the \"example-block\"."
2530 (let* ((parent-buffer (or parent-buffer
(current-buffer)))
2531 (info (or info
(org-babel-get-src-block-info 'light
)))
2534 (ob-nww-start org-babel-noweb-wrap-start
)
2535 (ob-nww-end org-babel-noweb-wrap-end
)
2536 (comment (string= "noweb" (cdr (assoc :comments
(nth 2 info
)))))
2537 (rx-prefix (concat "\\(" org-babel-src-name-regexp
"\\|"
2538 ":noweb-ref[ \t]+" "\\)"))
2540 (nb-add (lambda (text) (setq new-body
(concat new-body text
))))
2541 (c-wrap (lambda (text)
2543 (funcall (intern (concat lang
"-mode")))
2544 (comment-region (point) (progn (insert text
) (point)))
2545 (org-babel-trim (buffer-string)))))
2546 index source-name evaluate prefix
)
2548 (org-set-local 'org-babel-noweb-wrap-start ob-nww-start
)
2549 (org-set-local 'org-babel-noweb-wrap-end ob-nww-end
)
2550 (insert body
) (goto-char (point-min))
2551 (setq index
(point))
2552 (while (and (re-search-forward (org-babel-noweb-wrap) nil t
))
2553 (save-match-data (setf source-name
(match-string 1)))
2554 (save-match-data (setq evaluate
(string-match "\(.*\)" source-name
)))
2557 (buffer-substring (match-beginning 0)
2559 (beginning-of-line 1) (point)))))
2560 ;; add interval to new-body (removing noweb reference)
2561 (goto-char (match-beginning 0))
2562 (funcall nb-add
(buffer-substring index
(point)))
2563 (goto-char (match-end 0))
2564 (setq index
(point))
2567 (with-current-buffer parent-buffer
2570 (mapconcat ;; Interpose PREFIX between every line.
2574 (let ((raw (org-babel-ref-resolve source-name
)))
2575 (if (stringp raw
) raw
(format "%S" raw
)))
2577 ;; Retrieve from the library of babel.
2578 (nth 2 (assoc (intern source-name
)
2579 org-babel-library-of-babel
))
2580 ;; Return the contents of headlines literally.
2582 (when (org-babel-ref-goto-headline-id source-name
)
2583 (org-babel-ref-headline-body)))
2584 ;; Find the expansion of reference in this buffer.
2585 (let ((rx (concat rx-prefix source-name
"[ \t\n]"))
2588 (goto-char (point-min))
2589 (if org-babel-use-quick-and-dirty-noweb-expansion
2590 (while (re-search-forward rx nil t
)
2591 (let* ((i (org-babel-get-src-block-info 'light
))
2592 (body (org-babel-expand-noweb-references i
))
2593 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2596 (let ((cs (org-babel-tangle-comment-links i
)))
2597 (concat (funcall c-wrap
(car cs
)) "\n"
2599 (funcall c-wrap
(cadr cs
))))
2601 (setq expansion
(cons sep
(cons full expansion
)))))
2602 (org-babel-map-src-blocks nil
2603 (let ((i (org-babel-get-src-block-info 'light
)))
2604 (when (equal (or (cdr (assoc :noweb-ref
(nth 2 i
)))
2607 (let* ((body (org-babel-expand-noweb-references i
))
2608 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2611 (let ((cs (org-babel-tangle-comment-links i
)))
2612 (concat (funcall c-wrap
(car cs
)) "\n"
2614 (funcall c-wrap
(cadr cs
))))
2617 (cons sep
(cons full expansion
)))))))))
2619 (mapconcat #'identity
(nreverse (cdr expansion
)) "")))
2620 ;; Possibly raise an error if named block doesn't exist.
2621 (if (member lang org-babel-noweb-error-langs
)
2623 (org-babel-noweb-wrap source-name
)
2624 "could not be resolved (see "
2625 "`org-babel-noweb-error-langs')"))
2627 "[\n\r]") (concat "\n" prefix
))))))
2628 (funcall nb-add
(buffer-substring index
(point-max))))
2631 (defun org-babel-script-escape (str &optional force
)
2632 "Safely convert tables into elisp lists."
2637 (or (and (string-equal "[" (substring str
0 1))
2638 (string-equal "]" (substring str -
1)))
2639 (and (string-equal "{" (substring str
0 1))
2640 (string-equal "}" (substring str -
1)))
2641 (and (string-equal "(" (substring str
0 1))
2642 (string-equal ")" (substring str -
1))))))
2646 (let (in-single in-double out
)
2652 (91 (if (or in-double in-single
) ; [
2655 (93 (if (or in-double in-single
) ; ]
2658 (123 (if (or in-double in-single
) ; {
2661 (125 (if (or in-double in-single
) ; }
2664 (44 (if (or in-double in-single
) ; ,
2665 (cons 44 out
) (cons 32 out
)))
2666 (39 (if in-double
; '
2668 (setq in-single
(not in-single
)) (cons 34 out
)))
2669 (34 (if in-single
; "
2670 (append (list 34 32) out
)
2671 (setq in-double
(not in-double
)) (cons 34 out
)))
2672 (t (cons ch out
)))))
2673 (string-to-list str
))
2674 (apply #'string
(reverse out
)))))
2676 (condition-case nil
(org-babel-read escaped
) (error escaped
))))
2678 (defun org-babel-read (cell &optional inhibit-lisp-eval
)
2679 "Convert the string value of CELL to a number if appropriate.
2680 Otherwise if cell looks like lisp (meaning it starts with a
2681 \"(\", \"'\", \"`\" or a \"[\") then read it as lisp,
2682 otherwise return it unmodified as a string. Optional argument
2683 NO-LISP-EVAL inhibits lisp evaluation for situations in which is
2684 it not appropriate."
2685 (if (and (stringp cell
) (not (equal cell
"")))
2686 (or (org-babel-number-p cell
)
2687 (if (and (not inhibit-lisp-eval
)
2688 (or (member (substring cell
0 1) '("(" "'" "`" "["))
2689 (string= cell
"*this*")))
2691 (if (string= (substring cell
0 1) "\"")
2693 (progn (set-text-properties 0 (length cell
) nil cell
) cell
))))
2696 (defun org-babel-number-p (string)
2697 "If STRING represents a number return its value."
2698 (if (and (string-match "[0-9]+" string
)
2699 (string-match "^-?[0-9]*\\.?[0-9]*$" string
)
2700 (= (length (substring string
(match-beginning 0)
2703 (string-to-number string
)))
2705 (defun org-babel-import-elisp-from-file (file-name &optional separator
)
2706 "Read the results located at FILE-NAME into an elisp table.
2707 If the table is trivial, then return it as a scalar."
2709 (save-window-excursion
2713 (org-table-import file-name separator
)
2714 (delete-file file-name
)
2715 (setq result
(mapcar (lambda (row)
2716 (mapcar #'org-babel-string-read row
))
2717 (org-table-to-lisp))))
2718 (error (message "Error reading results: %s" err
) nil
)))
2719 (if (null (cdr result
)) ;; if result is trivial vector, then scalarize it
2720 (if (consp (car result
))
2721 (if (null (cdr (car result
)))
2727 (defun org-babel-string-read (cell)
2728 "Strip nested \"s from around strings."
2729 (org-babel-read (or (and (stringp cell
)
2730 (string-match "\\\"\\(.+\\)\\\"" cell
)
2731 (match-string 1 cell
))
2734 (defun org-babel-chomp (string &optional regexp
)
2735 "Strip trailing spaces and carriage returns from STRING.
2736 Default regexp used is \"[ \f\t\n\r\v]\" but can be
2737 overwritten by specifying a regexp as a second argument."
2738 (let ((regexp (or regexp
"[ \f\t\n\r\v]")))
2739 (while (and (> (length string
) 0)
2740 (string-match regexp
(substring string -
1)))
2741 (setq string
(substring string
0 -
1)))
2744 (defun org-babel-trim (string &optional regexp
)
2745 "Strip leading and trailing spaces and carriage returns from STRING.
2746 Like `org-babel-chomp' only it runs on both the front and back
2748 (org-babel-chomp (org-reverse-string
2749 (org-babel-chomp (org-reverse-string string
) regexp
))
2752 (defun org-babel-tramp-handle-call-process-region
2753 (start end program
&optional delete buffer display
&rest args
)
2754 "Use Tramp to handle `call-process-region'.
2755 Fixes a bug in `tramp-handle-call-process-region'."
2756 (if (and (featurep 'tramp
) (file-remote-p default-directory
))
2757 (let ((tmpfile (tramp-compat-make-temp-file "")))
2758 (write-region start end tmpfile
)
2759 (when delete
(delete-region start end
))
2761 ;; (apply 'call-process program tmpfile buffer display args)
2763 (apply 'process-file program tmpfile buffer display args
)
2764 (delete-file tmpfile
)))
2765 ;; org-babel-call-process-region-original is the original emacs
2766 ;; definition. It is in scope from the let binding in
2767 ;; org-babel-execute-src-block
2768 (apply org-babel-call-process-region-original
2769 start end program delete buffer display args
)))
2771 (defun org-babel-local-file-name (file)
2772 "Return the local name component of FILE."
2773 (or (file-remote-p file
'localname
) file
))
2775 (defun org-babel-process-file-name (name &optional no-quote-p
)
2776 "Prepare NAME to be used in an external process.
2777 If NAME specifies a remote location, the remote portion of the
2778 name is removed, since in that case the process will be executing
2779 remotely. The file name is then processed by `expand-file-name'.
2780 Unless second argument NO-QUOTE-P is non-nil, the file name is
2781 additionally processed by `shell-quote-argument'"
2782 (let ((f (org-babel-local-file-name (expand-file-name name
))))
2783 (if no-quote-p f
(shell-quote-argument f
))))
2785 (defvar org-babel-temporary-directory
)
2786 (unless (or noninteractive
(boundp 'org-babel-temporary-directory
))
2787 (defvar org-babel-temporary-directory
2788 (or (and (boundp 'org-babel-temporary-directory
)
2789 (file-exists-p org-babel-temporary-directory
)
2790 org-babel-temporary-directory
)
2791 (make-temp-file "babel-" t
))
2792 "Directory to hold temporary files created to execute code blocks.
2793 Used by `org-babel-temp-file'. This directory will be removed on
2796 (defcustom org-babel-remote-temporary-directory
"/tmp/"
2797 "Directory to hold temporary files on remote hosts."
2801 (defmacro org-babel-result-cond
(result-params scalar-form
&rest table-forms
)
2802 "Call the code to parse raw string results according to RESULT-PARAMS."
2804 (debug (form form
&rest form
)))
2805 (org-with-gensyms (params)
2806 `(let ((,params
,result-params
))
2807 (unless (member "none" ,params
)
2808 (if (or (member "scalar" ,params
)
2809 (member "verbatim" ,params
)
2810 (member "html" ,params
)
2811 (member "code" ,params
)
2812 (member "pp" ,params
)
2813 (and (or (member "output" ,params
)
2814 (member "raw" ,params
)
2815 (member "org" ,params
)
2816 (member "drawer" ,params
))
2817 (not (member "table" ,params
))))
2820 (def-edebug-spec org-babel-result-cond
(form form body
))
2822 (defun org-babel-temp-file (prefix &optional suffix
)
2823 "Create a temporary file in the `org-babel-temporary-directory'.
2824 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2825 value of `temporary-file-directory' temporarily set to the value
2826 of `org-babel-temporary-directory'."
2827 (if (file-remote-p default-directory
)
2829 (concat (file-remote-p default-directory
)
2831 prefix org-babel-remote-temporary-directory
))))
2832 (make-temp-file prefix nil suffix
))
2833 (let ((temporary-file-directory
2834 (or (and (boundp 'org-babel-temporary-directory
)
2835 (file-exists-p org-babel-temporary-directory
)
2836 org-babel-temporary-directory
)
2837 temporary-file-directory
)))
2838 (make-temp-file prefix nil suffix
))))
2840 (defun org-babel-remove-temporary-directory ()
2841 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2842 (when (and (boundp 'org-babel-temporary-directory
)
2843 (file-exists-p org-babel-temporary-directory
))
2844 ;; taken from `delete-directory' in files.el
2847 (mapc (lambda (file)
2848 ;; This test is equivalent to
2849 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2850 ;; but more efficient
2851 (if (eq t
(car (file-attributes file
)))
2852 (delete-directory file
)
2853 (delete-file file
)))
2854 ;; We do not want to delete "." and "..".
2855 (directory-files org-babel-temporary-directory
'full
2856 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2857 (delete-directory org-babel-temporary-directory
))
2859 (message "Failed to remove temporary Org-babel directory %s"
2860 (if (boundp 'org-babel-temporary-directory
)
2861 org-babel-temporary-directory
2862 "[directory not defined]"))))))
2864 (add-hook 'kill-emacs-hook
'org-babel-remove-temporary-directory
)
2866 (defun org-babel-one-header-arg-safe-p (pair safe-list
)
2867 "Determine if the PAIR is a safe babel header arg according to SAFE-LIST.
2869 For the format of SAFE-LIST, see `org-babel-safe-header-args'."
2871 (keywordp (car pair
))
2872 (stringp (cdr pair
))
2874 (memq (car pair
) safe-list
)
2875 (let ((entry (assq (car pair
) safe-list
)))
2878 (cond ((functionp (cdr entry
))
2879 (funcall (cdr entry
) (cdr pair
)))
2880 ((listp (cdr entry
))
2881 (member (cdr pair
) (cdr entry
)))
2887 ;; generated-autoload-file: "org-loaddefs.el"
2890 ;;; ob-core.el ends here