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
))))
287 (setf (nth 2 info
) (org-babel-generate-file-param name
(nth 2 info
))))
288 (when info
(append info
(list name indent head
)))))
290 (defvar org-babel-exp-reference-buffer nil
291 "Buffer containing original contents of the exported buffer.
292 This is used by Babel to resolve references in source blocks.
293 Its value is dynamically bound during export.")
295 (defmacro org-babel-check-confirm-evaluate
(info &rest body
)
296 "Evaluate BODY with special execution confirmation variables set.
298 Specifically; NOEVAL will indicate if evaluation is allowed,
299 QUERY will indicate if a user query is required, CODE-BLOCK will
300 hold the language of the code block, and BLOCK-NAME will hold the
301 name of the code block."
302 (declare (indent defun
))
304 (lang block-body headers name head eval eval-no export eval-no-export
)
305 `(let* ((,lang
(nth 0 ,info
))
306 (,block-body
(nth 1 ,info
))
307 (,headers
(nth 2 ,info
))
308 (,name
(nth 4 ,info
))
309 (,head
(nth 6 ,info
))
310 (,eval
(or (cdr (assoc :eval
,headers
))
311 (when (assoc :noeval
,headers
) "no")))
312 (,eval-no
(or (equal ,eval
"no")
313 (equal ,eval
"never")))
314 (,export org-babel-exp-reference-buffer
)
315 (,eval-no-export
(and ,export
(or (equal ,eval
"no-export")
316 (equal ,eval
"never-export"))))
317 (noeval (or ,eval-no
,eval-no-export
))
318 (query (or (equal ,eval
"query")
319 (and ,export
(equal ,eval
"query-export"))
320 (if (functionp org-confirm-babel-evaluate
)
323 (funcall org-confirm-babel-evaluate
325 org-confirm-babel-evaluate
)))
326 (code-block (if ,info
(format " %s " ,lang
) " "))
327 (block-name (if ,name
(format " (%s) " ,name
) " ")))
330 (defsubst org-babel-check-evaluate
(info)
331 "Check if code block INFO should be evaluated.
332 Do not query the user."
333 (org-babel-check-confirm-evaluate info
335 (message (format "Evaluation of this%scode-block%sis disabled."
336 code-block block-name
))))))
338 ;; dynamically scoped for asynchronous export
339 (defvar org-babel-confirm-evaluate-answer-no
)
341 (defsubst org-babel-confirm-evaluate
(info)
342 "Confirm evaluation of the code block INFO.
344 If the variable `org-babel-confirm-evaluate-answer-no' is bound
345 to a non-nil value, auto-answer with \"no\".
347 This query can also be suppressed by setting the value of
348 `org-confirm-babel-evaluate' to nil, in which case all future
349 interactive code block evaluations will proceed without any
350 confirmation from the user.
352 Note disabling confirmation may result in accidental evaluation
353 of potentially harmful code."
354 (org-babel-check-confirm-evaluate info
357 (and (not (org-bound-and-true-p
358 org-babel-confirm-evaluate-answer-no
))
360 (format "Evaluate this%scode block%son your system? "
361 code-block block-name
)))
362 (message (format "Evaluation of this%scode-block%sis aborted."
363 code-block block-name
)))))))
366 (defun org-babel-execute-safely-maybe ()
367 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
368 (org-babel-execute-maybe)))
370 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-execute-safely-maybe
)
373 (defun org-babel-execute-maybe ()
375 (or (org-babel-execute-src-block-maybe)
376 (org-babel-lob-execute-maybe)))
378 (defmacro org-babel-when-in-src-block
(&rest body
)
379 "Execute BODY if point is in a source block and return t.
381 Otherwise do nothing and return nil."
382 `(if (or (org-babel-where-is-src-block-head)
383 (org-babel-get-inline-src-block-matches))
389 (defun org-babel-execute-src-block-maybe ()
390 "Conditionally execute a source block.
391 Detect if this is context for a Babel src-block and if so
392 then run `org-babel-execute-src-block'."
394 (org-babel-when-in-src-block
395 (org-babel-eval-wipe-error-buffer)
396 (org-babel-execute-src-block current-prefix-arg
)))
399 (defun org-babel-view-src-block-info ()
400 "Display information on the current source block.
401 This includes header arguments, language and name, and is largely
402 a window into the `org-babel-get-src-block-info' function."
404 (let ((info (org-babel-get-src-block-info 'light
))
405 (full (lambda (it) (> (length it
) 0)))
406 (printf (lambda (fmt &rest args
) (princ (apply #'format fmt args
)))))
408 (with-help-window (help-buffer)
409 (let ((name (nth 4 info
))
411 (switches (nth 3 info
))
412 (header-args (nth 2 info
)))
413 (when name
(funcall printf
"Name: %s\n" name
))
414 (when lang
(funcall printf
"Lang: %s\n" lang
))
415 (when (funcall full switches
) (funcall printf
"Switches: %s\n" switches
))
416 (funcall printf
"Header Arguments:\n")
417 (dolist (pair (sort header-args
418 (lambda (a b
) (string< (symbol-name (car a
))
419 (symbol-name (car b
))))))
420 (when (funcall full
(cdr pair
))
421 (funcall printf
"\t%S%s\t%s\n"
423 (if (> (length (format "%S" (car pair
))) 7) "" "\t")
427 (defun org-babel-expand-src-block-maybe ()
428 "Conditionally expand a source block.
429 Detect if this is context for a org-babel src-block and if so
430 then run `org-babel-expand-src-block'."
432 (org-babel-when-in-src-block
433 (org-babel-expand-src-block current-prefix-arg
)))
436 (defun org-babel-load-in-session-maybe ()
437 "Conditionally load a source block in a session.
438 Detect if this is context for a org-babel src-block and if so
439 then run `org-babel-load-in-session'."
441 (org-babel-when-in-src-block
442 (org-babel-load-in-session current-prefix-arg
)))
444 (add-hook 'org-metaup-hook
'org-babel-load-in-session-maybe
)
447 (defun org-babel-pop-to-session-maybe ()
448 "Conditionally pop to a session.
449 Detect if this is context for a org-babel src-block and if so
450 then run `org-babel-switch-to-session'."
452 (org-babel-when-in-src-block
453 (org-babel-switch-to-session current-prefix-arg
)))
455 (add-hook 'org-metadown-hook
'org-babel-pop-to-session-maybe
)
457 (defconst org-babel-common-header-args-w-values
458 '((cache .
((no yes
)))
460 (colnames .
((nil no yes
)))
461 (comments .
((no link yes org both noweb
)))
463 (eval .
((never query
)))
464 (exports .
((code results both none
)))
468 (hlines .
((no yes
)))
469 (mkdirp .
((yes no
)))
472 (noweb .
((yes no tangle no-export strip-export
)))
475 (padline .
((yes no
)))
478 (results .
((file list vector table scalar verbatim
)
479 (raw html latex org code pp drawer
)
480 (replace silent none append prepend
)
482 (rownames .
((no yes
)))
486 (tangle .
((tangle yes no
:any
)))
487 (tangle-mode .
((#o755
#o555
#o444
:any
)))
491 (defconst org-babel-header-arg-names
492 (mapcar #'car org-babel-common-header-args-w-values
)
493 "Common header arguments used by org-babel.
494 Note that individual languages may define their own language
495 specific header arguments as well.")
497 (defconst org-babel-safe-header-args
498 '(:cache
:colnames
:comments
:exports
:epilogue
:hlines
:noeval
499 :noweb
:noweb-ref
:noweb-sep
:padline
:prologue
:rownames
500 :sep
:session
:tangle
:wrap
501 (:eval .
("never" "query"))
502 (:results .
(lambda (str) (not (string-match "file" str
)))))
503 "A list of safe header arguments for babel source blocks.
505 The list can have entries of the following forms:
506 - :ARG -> :ARG is always a safe header arg
507 - (:ARG . (VAL1 VAL2 ...)) -> :ARG is safe as a header arg if it is
508 `equal' to one of the VALs.
509 - (:ARG . FN) -> :ARG is safe as a header arg if the function FN
510 returns non-nil. FN is passed one
511 argument, the value of the header arg
514 (defmacro org-babel-header-args-safe-fn
(safe-list)
515 "Return a function that determines whether a list of header args are safe.
518 \(put 'org-babel-default-header-args 'safe-local-variable
519 (org-babel-header-args-safe-p org-babel-safe-header-args)
521 This allows org-babel languages to extend the list of safe values for
522 their `org-babel-default-header-args:foo' variable.
524 For the format of SAFE-LIST, see `org-babel-safe-header-args'."
530 (org-babel-one-header-arg-safe-p pair
,safe-list
)))
533 (defvar org-babel-default-header-args
534 '((:session .
"none") (:results .
"replace") (:exports .
"code")
535 (:cache .
"no") (:noweb .
"no") (:hlines .
"no") (:tangle .
"no"))
536 "Default arguments to use when evaluating a source block.")
537 (put 'org-babel-default-header-args
'safe-local-variable
538 (org-babel-header-args-safe-fn org-babel-safe-header-args
))
540 (defvar org-babel-default-inline-header-args
541 '((:session .
"none") (:results .
"replace")
542 (:exports .
"results") (:hlines .
"yes"))
543 "Default arguments to use when evaluating an inline source block.")
544 (put 'org-babel-default-inline-header-args
'safe-local-variable
545 (org-babel-header-args-safe-fn org-babel-safe-header-args
))
547 (defvar org-babel-data-names
'("tblname" "results" "name"))
549 (defvar org-babel-result-regexp
550 (concat "^[ \t]*#\\+"
551 (regexp-opt org-babel-data-names t
)
553 ;; FIXME The string below is `org-ts-regexp'
554 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
555 " \\)?\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*")
556 "Regular expression used to match result lines.
557 If the results are associated with a hash key then the hash will
558 be saved in the second match data.")
560 (defvar org-babel-result-w-name-regexp
561 (concat org-babel-result-regexp
562 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
564 (defvar org-babel-min-lines-for-block-output
10
565 "The minimum number of lines for block output.
566 If number of lines of output is equal to or exceeds this
567 value, the output is placed in a #+begin_example...#+end_example
568 block. Otherwise the output is marked as literal by inserting
569 colons at the starts of the lines. This variable only takes
570 effect if the :results output option is in effect.")
572 (defvar org-babel-noweb-error-langs nil
573 "Languages for which Babel will raise literate programming errors.
574 List of languages for which errors should be raised when the
575 source code block satisfying a noweb reference in this language
576 can not be resolved.")
578 (defvar org-babel-hash-show
4
579 "Number of initial characters to show of a hidden results hash.")
581 (defvar org-babel-hash-show-time nil
582 "Non-nil means show the time the code block was evaluated in the result hash.")
584 (defvar org-babel-after-execute-hook nil
585 "Hook for functions to be called after `org-babel-execute-src-block'")
587 (defun org-babel-named-src-block-regexp-for-name (name)
588 "This generates a regexp used to match a src block named NAME."
589 (concat org-babel-src-name-regexp
(regexp-quote name
)
590 "[ \t(]*[\r\n]\\(?:^[[:space:]]*#.*[\r\n]\\)*"
591 (substring org-babel-src-block-regexp
1)))
593 (defun org-babel-named-data-regexp-for-name (name)
594 "This generates a regexp used to match data named NAME."
595 (concat org-babel-result-regexp
(regexp-quote name
) "\\([ \t]\\|$\\)"))
598 (defvar call-process-region
)
599 (defvar org-babel-current-src-block-location nil
600 "Marker pointing to the src block currently being executed.
601 This may also point to a call line or an inline code block. If
602 multiple blocks are being executed (e.g., in chained execution
603 through use of the :var header argument) this marker points to
604 the outer-most code block.")
607 (defun org-babel-execute-src-block (&optional arg info params
)
608 "Execute the current source code block.
609 Insert the results of execution into the buffer. Source code
610 execution and the collection and formatting of results can be
611 controlled through a variety of header arguments.
613 With prefix argument ARG, force re-execution even if an existing
614 result cached in the buffer would otherwise have been returned.
616 Optionally supply a value for INFO in the form returned by
617 `org-babel-get-src-block-info'.
619 Optionally supply a value for PARAMS which will be merged with
620 the header arguments specified at the front of the source code
623 (let* ((org-babel-current-src-block-location
624 (or org-babel-current-src-block-location
626 (org-babel-where-is-src-block-head)
628 (and (org-babel-get-inline-src-block-matches)
629 (match-beginning 0))))
632 (org-babel-get-src-block-info)))
633 (merged-params (org-babel-merge-params (nth 2 info
) params
)))
634 (when (org-babel-check-evaluate
635 (let ((i info
)) (setf (nth 2 i
) merged-params
) i
))
636 (let* ((params (if params
637 (org-babel-process-params merged-params
)
639 (cachep (and (not arg
) (cdr (assoc :cache params
))
640 (string= "yes" (cdr (assoc :cache params
)))))
641 (new-hash (when cachep
(org-babel-sha1-hash info
)))
642 (old-hash (when cachep
(org-babel-current-result-hash)))
643 (cache-current-p (and (not arg
) new-hash
644 (equal new-hash old-hash
))))
647 (save-excursion ;; return cached result
648 (goto-char (org-babel-where-is-src-block-result nil info
))
649 (end-of-line 1) (forward-char 1)
650 (let ((result (org-babel-read-result)))
651 (message (replace-regexp-in-string
652 "%" "%%" (format "%S" result
))) result
)))
653 ((org-babel-confirm-evaluate
654 (let ((i info
)) (setf (nth 2 i
) merged-params
) i
))
655 (let* ((lang (nth 0 info
))
656 (result-params (cdr (assoc :result-params params
)))
657 (body (setf (nth 1 info
)
658 (if (org-babel-noweb-p params
:eval
)
659 (org-babel-expand-noweb-references info
)
661 (dir (cdr (assoc :dir params
)))
663 (or (and dir
(file-name-as-directory (expand-file-name dir
)))
665 (org-babel-call-process-region-original ;; for tramp handler
666 (or (org-bound-and-true-p
667 org-babel-call-process-region-original
)
668 (symbol-function 'call-process-region
)))
669 (indent (nth 5 info
))
672 (let ((call-process-region
674 (apply 'org-babel-tramp-handle-call-process-region
678 (let ((f (intern (concat "org-babel-execute:" f
))))
679 (when (fboundp f
) f
)))))
681 (or (funcall lang-check lang
)
684 (cdr (assoc lang org-src-lang-modes
))))
685 (error "No org-babel-execute function for %s!"
687 (message "executing %s code block%s..."
689 (if (nth 4 info
) (format " (%s)" (nth 4 info
)) ""))
690 (if (member "none" result-params
)
692 (funcall cmd body params
)
693 (message "result silenced")
696 (let ((result (funcall cmd body params
)))
697 (if (and (eq (cdr (assoc :result-type params
))
699 (or (member "vector" result-params
)
700 (member "table" result-params
))
701 (not (listp result
)))
702 (list (list result
)) result
)))
703 ;; If non-empty result and :file then write to :file.
704 (when (cdr (assoc :file params
))
706 (with-temp-file (cdr (assoc :file params
))
708 (org-babel-format-result
709 result
(cdr (assoc :sep
(nth 2 info
)))))))
710 (setq result
(cdr (assoc :file params
))))
711 ;; Possibly perform post process provided its appropriate.
712 (when (cdr (assoc :post params
))
713 (let ((*this
* (if (cdr (assoc :file params
))
714 (org-babel-result-to-file
715 (cdr (assoc :file params
))
716 (when (assoc :file-desc params
)
717 (or (cdr (assoc :file-desc params
))
720 (setq result
(org-babel-ref-resolve
721 (cdr (assoc :post params
))))
722 (when (cdr (assoc :file params
))
724 (remove "file" result-params
)))))
725 (org-babel-insert-result
726 result result-params info new-hash indent lang
))
727 (run-hooks 'org-babel-after-execute-hook
)
729 (setq call-process-region
730 'org-babel-call-process-region-original
)))))))))
732 (defun org-babel-expand-body:generic
(body params
&optional var-lines
)
733 "Expand BODY with PARAMS.
734 Expand a block of code with org-babel according to its header
735 arguments. This generic implementation of body expansion is
736 called for languages which have not defined their own specific
737 org-babel-expand-body:lang function."
738 (let ((pro (cdr (assoc :prologue params
)))
739 (epi (cdr (assoc :epilogue params
))))
740 (mapconcat #'identity
741 (append (when pro
(list pro
))
744 (when epi
(list epi
)))
748 (defun org-babel-expand-src-block (&optional arg info params
)
749 "Expand the current source code block.
750 Expand according to the source code block's header
751 arguments and pop open the results in a preview buffer."
753 (let* ((info (or info
(org-babel-get-src-block-info)))
755 (params (setf (nth 2 info
)
756 (sort (org-babel-merge-params (nth 2 info
) params
)
757 (lambda (el1 el2
) (string< (symbol-name (car el1
))
758 (symbol-name (car el2
)))))))
759 (body (setf (nth 1 info
)
760 (if (org-babel-noweb-p params
:eval
)
761 (org-babel-expand-noweb-references info
) (nth 1 info
))))
762 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
763 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
766 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
767 (org-babel-expand-body:generic
768 body params
(and (fboundp assignments-cmd
)
769 (funcall assignments-cmd params
))))))
770 (if (org-called-interactively-p 'any
)
773 (concat "*Org-Babel Preview " (buffer-name) "[ " lang
" ]*"))
776 (defun org-babel-edit-distance (s1 s2
)
777 "Return the edit (levenshtein) distance between strings S1 S2."
778 (let* ((l1 (length s1
))
780 (dist (vconcat (mapcar (lambda (_) (make-vector (1+ l2
) nil
))
781 (number-sequence 1 (1+ l1
)))))
782 (in (lambda (i j
) (aref (aref dist i
) j
))))
783 (setf (aref (aref dist
0) 0) 0)
784 (dolist (j (number-sequence 1 l2
))
785 (setf (aref (aref dist
0) j
) j
))
786 (dolist (i (number-sequence 1 l1
))
787 (setf (aref (aref dist i
) 0) i
)
788 (dolist (j (number-sequence 1 l2
))
789 (setf (aref (aref dist i
) j
)
791 (1+ (funcall in
(1- i
) j
))
792 (1+ (funcall in i
(1- j
)))
793 (+ (if (equal (aref s1
(1- i
)) (aref s2
(1- j
))) 0 1)
794 (funcall in
(1- i
) (1- j
)))))))
797 (defun org-babel-combine-header-arg-lists (original &rest others
)
798 "Combine a number of lists of header argument names and arguments."
799 (let ((results (copy-sequence original
)))
800 (dolist (new-list others
)
801 (dolist (arg-pair new-list
)
802 (let ((header (car arg-pair
))
803 (args (cdr arg-pair
)))
805 (cons arg-pair
(org-remove-if
806 (lambda (pair) (equal header
(car pair
)))
811 (defun org-babel-check-src-block ()
812 "Check for misspelled header arguments in the current code block."
814 ;; TODO: report malformed code block
815 ;; TODO: report incompatible combinations of header arguments
816 ;; TODO: report uninitialized variables
817 (let ((too-close 2) ;; <- control closeness to report potential match
818 (names (mapcar #'symbol-name org-babel-header-arg-names
)))
819 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg
)) 1))
820 (and (org-babel-where-is-src-block-head)
821 (org-babel-parse-header-arguments
823 (match-string 4))))))
825 (when (and (not (string= header name
))
826 (<= (org-babel-edit-distance header name
) too-close
)
827 (not (member header names
)))
828 (error "Supplied header \"%S\" is suspiciously close to \"%S\""
830 (message "No suspicious header arguments found.")))
833 (defun org-babel-insert-header-arg (&optional header-arg value
)
834 "Insert a header argument selecting from lists of common args and values."
836 (let* ((info (org-babel-get-src-block-info 'light
))
839 (lang-headers (intern (concat "org-babel-header-args:" lang
)))
840 (headers (org-babel-combine-header-arg-lists
841 org-babel-common-header-args-w-values
842 (when (boundp lang-headers
) (eval lang-headers
))))
843 (header-arg (or header-arg
844 (org-icompleting-read
847 (lambda (header-spec) (symbol-name (car header-spec
)))
849 (vals (cdr (assoc (intern header-arg
) headers
)))
853 (read-from-minibuffer "value: "))
857 (let ((arg (org-icompleting-read
860 (mapcar #'symbol-name group
)))))
861 (if (and arg
(not (string= "default" arg
)))
867 (goto-char (point-at-eol))
868 (unless (= (char-before (point)) ?\
) (insert " "))
869 (insert ":" header-arg
) (when value
(insert " " value
)))))
871 ;; Add support for completing-read insertion of header arguments after ":"
872 (defun org-babel-header-arg-expand ()
873 "Call `org-babel-enter-header-arg-w-completion' in appropriate contexts."
874 (when (and (equal (char-before) ?\
:) (org-babel-where-is-src-block-head))
875 (org-babel-enter-header-arg-w-completion (match-string 2))))
877 (defun org-babel-enter-header-arg-w-completion (&optional lang
)
878 "Insert header argument appropriate for LANG with completion."
879 (let* ((lang-headers-var (intern (concat "org-babel-header-args:" lang
)))
880 (lang-headers (when (boundp lang-headers-var
) (eval lang-headers-var
)))
881 (headers-w-values (org-babel-combine-header-arg-lists
882 org-babel-common-header-args-w-values lang-headers
))
883 (headers (mapcar #'symbol-name
(mapcar #'car headers-w-values
)))
884 (header (org-completing-read "Header Arg: " headers
))
885 (args (cdr (assoc (intern header
) headers-w-values
)))
886 (arg (when (and args
(listp args
))
888 (format "%s: " header
)
889 (mapcar #'symbol-name
(apply #'append args
))))))
890 (insert (concat header
" " (or arg
"")))
893 (add-hook 'org-tab-first-hook
'org-babel-header-arg-expand
)
896 (defun org-babel-load-in-session (&optional arg info
)
897 "Load the body of the current source-code block.
898 Evaluate the header arguments for the source block before
899 entering the session. After loading the body this pops open the
902 (let* ((info (or info
(org-babel-get-src-block-info)))
904 (params (nth 2 info
))
906 (user-error "No src code block at point")
908 (if (org-babel-noweb-p params
:eval
)
909 (org-babel-expand-noweb-references info
)
911 (session (cdr (assoc :session params
)))
912 (dir (cdr (assoc :dir params
)))
914 (or (and dir
(file-name-as-directory dir
)) default-directory
))
915 (cmd (intern (concat "org-babel-load-session:" lang
))))
916 (unless (fboundp cmd
)
917 (error "No org-babel-load-session function for %s!" lang
))
918 (pop-to-buffer (funcall cmd session body params
))
922 (defun org-babel-initiate-session (&optional arg info
)
923 "Initiate session for current code block.
924 If called with a prefix argument then resolve any variable
925 references in the header arguments and assign these variables in
926 the session. Copy the body of the code block to the kill ring."
928 (let* ((info (or info
(org-babel-get-src-block-info (not arg
))))
931 (params (nth 2 info
))
932 (session (cdr (assoc :session params
)))
933 (dir (cdr (assoc :dir params
)))
935 (or (and dir
(file-name-as-directory dir
)) default-directory
))
936 (init-cmd (intern (format "org-babel-%s-initiate-session" lang
)))
937 (prep-cmd (intern (concat "org-babel-prep-session:" lang
))))
938 (if (and (stringp session
) (string= session
"none"))
939 (error "This block is not using a session!"))
940 (unless (fboundp init-cmd
)
941 (error "No org-babel-initiate-session function for %s!" lang
))
942 (with-temp-buffer (insert (org-babel-trim body
))
943 (copy-region-as-kill (point-min) (point-max)))
945 (unless (fboundp prep-cmd
)
946 (error "No org-babel-prep-session function for %s!" lang
))
947 (funcall prep-cmd session params
))
948 (funcall init-cmd session params
)))
951 (defun org-babel-switch-to-session (&optional arg info
)
952 "Switch to the session of the current code block.
953 Uses `org-babel-initiate-session' to start the session. If called
954 with a prefix argument then this is passed on to
955 `org-babel-initiate-session'."
957 (pop-to-buffer (org-babel-initiate-session arg info
))
960 (defalias 'org-babel-pop-to-session
'org-babel-switch-to-session
)
962 (defvar org-src-window-setup
)
965 (defun org-babel-switch-to-session-with-code (&optional arg info
)
966 "Switch to code buffer and display session."
970 (let ((other-window-buffer (window-buffer (next-window))))
971 (set-window-buffer (next-window) (current-buffer))
972 (set-window-buffer (selected-window) other-window-buffer
))
974 (info (org-babel-get-src-block-info))
975 (org-src-window-setup 'reorganize-frame
))
977 (org-babel-switch-to-session arg info
))
979 (funcall swap-windows
)))
982 (defmacro org-babel-do-in-edit-buffer
(&rest body
)
983 "Evaluate BODY in edit buffer if there is a code block at point.
984 Return t if a code block was found at point, nil otherwise."
985 `(let ((org-src-window-setup 'switch-invisibly
))
986 (when (and (org-babel-where-is-src-block-head)
988 (unwind-protect (progn ,@body
)
989 (if (org-bound-and-true-p org-edit-src-from-org-mode
)
990 (org-edit-src-exit)))
992 (def-edebug-spec org-babel-do-in-edit-buffer
(body))
994 (defun org-babel-do-key-sequence-in-edit-buffer (key)
995 "Read key sequence and execute the command in edit buffer.
996 Enter a key sequence to be executed in the language major-mode
997 edit buffer. For example, TAB will alter the contents of the
998 Org-mode code block according to the effect of TAB in the
999 language major-mode buffer. For languages that support
1000 interactive sessions, this can be used to send code from the Org
1001 buffer to the session for evaluation using the native major-mode
1002 evaluation mechanisms."
1003 (interactive "kEnter key-sequence to execute in edit buffer: ")
1004 (org-babel-do-in-edit-buffer
1006 (key-binding (or key
(read-key-sequence nil
))))))
1008 (defvar org-bracket-link-regexp
)
1010 (defun org-babel-active-location-p ()
1011 (memq (car (save-match-data (org-element-context)))
1012 '(babel-call inline-babel-call inline-src-block src-block
)))
1015 (defun org-babel-open-src-block-result (&optional re-run
)
1016 "If `point' is on a src block then open the results of the
1017 source code block, otherwise return nil. With optional prefix
1018 argument RE-RUN the source-code block is evaluated even if
1019 results already exist."
1021 (let ((info (org-babel-get-src-block-info 'light
)))
1024 ;; go to the results, if there aren't any then run the block
1025 (goto-char (or (and (not re-run
) (org-babel-where-is-src-block-result))
1026 (progn (org-babel-execute-src-block)
1027 (org-babel-where-is-src-block-result))))
1029 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
1031 (if (looking-at org-bracket-link-regexp
)
1034 (let ((r (org-babel-format-result
1035 (org-babel-read-result) (cdr (assoc :sep
(nth 2 info
))))))
1036 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
1037 (delete-region (point-min) (point-max))
1042 (defmacro org-babel-map-src-blocks
(file &rest body
)
1043 "Evaluate BODY forms on each source-block in FILE.
1044 If FILE is nil evaluate BODY forms on source blocks in current
1045 buffer. During evaluation of BODY the following local variables
1046 are set relative to the currently matched code block.
1048 full-block ------- string holding the entirety of the code block
1049 beg-block -------- point at the beginning of the code block
1050 end-block -------- point at the end of the matched code block
1051 lang ------------- string holding the language of the code block
1052 beg-lang --------- point at the beginning of the lang
1053 end-lang --------- point at the end of the lang
1054 switches --------- string holding the switches
1055 beg-switches ----- point at the beginning of the switches
1056 end-switches ----- point at the end of the switches
1057 header-args ------ string holding the header-args
1058 beg-header-args -- point at the beginning of the header-args
1059 end-header-args -- point at the end of the header-args
1060 body ------------- string holding the body of the code block
1061 beg-body --------- point at the beginning of the body
1062 end-body --------- point at the end of the body"
1063 (declare (indent 1))
1064 (let ((tempvar (make-symbol "file")))
1065 `(let* ((,tempvar
,file
)
1066 (visited-p (or (null ,tempvar
)
1067 (get-file-buffer (expand-file-name ,tempvar
))))
1068 (point (point)) to-be-removed
)
1069 (save-window-excursion
1070 (when ,tempvar
(find-file ,tempvar
))
1071 (setq to-be-removed
(current-buffer))
1072 (goto-char (point-min))
1073 (while (re-search-forward org-babel-src-block-regexp nil t
)
1074 (when (org-babel-active-location-p)
1075 (goto-char (match-beginning 0))
1076 (let ((full-block (match-string 0))
1077 (beg-block (match-beginning 0))
1078 (end-block (match-end 0))
1079 (lang (match-string 2))
1080 (beg-lang (match-beginning 2))
1081 (end-lang (match-end 2))
1082 (switches (match-string 3))
1083 (beg-switches (match-beginning 3))
1084 (end-switches (match-end 3))
1085 (header-args (match-string 4))
1086 (beg-header-args (match-beginning 4))
1087 (end-header-args (match-end 4))
1088 (body (match-string 5))
1089 (beg-body (match-beginning 5))
1090 (end-body (match-end 5)))
1092 (goto-char end-block
)))))
1093 (unless visited-p
(kill-buffer to-be-removed
))
1094 (goto-char point
))))
1095 (def-edebug-spec org-babel-map-src-blocks
(form body
))
1098 (defmacro org-babel-map-inline-src-blocks
(file &rest body
)
1099 "Evaluate BODY forms on each inline source-block in FILE.
1100 If FILE is nil evaluate BODY forms on source blocks in current
1102 (declare (indent 1))
1103 (let ((tempvar (make-symbol "file")))
1104 `(let* ((,tempvar
,file
)
1105 (visited-p (or (null ,tempvar
)
1106 (get-file-buffer (expand-file-name ,tempvar
))))
1107 (point (point)) to-be-removed
)
1108 (save-window-excursion
1109 (when ,tempvar
(find-file ,tempvar
))
1110 (setq to-be-removed
(current-buffer))
1111 (goto-char (point-min))
1112 (while (re-search-forward org-babel-inline-src-block-regexp nil t
)
1113 (when (org-babel-active-location-p)
1114 (goto-char (match-beginning 1))
1115 (save-match-data ,@body
))
1116 (goto-char (match-end 0))))
1117 (unless visited-p
(kill-buffer to-be-removed
))
1118 (goto-char point
))))
1119 (def-edebug-spec org-babel-map-inline-src-blocks
(form body
))
1121 (defvar org-babel-lob-one-liner-regexp
)
1124 (defmacro org-babel-map-call-lines
(file &rest body
)
1125 "Evaluate BODY forms on each call line in FILE.
1126 If FILE is nil evaluate BODY forms on source blocks in current
1128 (declare (indent 1))
1129 (let ((tempvar (make-symbol "file")))
1130 `(let* ((,tempvar
,file
)
1131 (visited-p (or (null ,tempvar
)
1132 (get-file-buffer (expand-file-name ,tempvar
))))
1133 (point (point)) to-be-removed
)
1134 (save-window-excursion
1135 (when ,tempvar
(find-file ,tempvar
))
1136 (setq to-be-removed
(current-buffer))
1137 (goto-char (point-min))
1138 (while (re-search-forward org-babel-lob-one-liner-regexp nil t
)
1139 (when (org-babel-active-location-p)
1140 (goto-char (match-beginning 1))
1141 (save-match-data ,@body
))
1142 (goto-char (match-end 0))))
1143 (unless visited-p
(kill-buffer to-be-removed
))
1144 (goto-char point
))))
1145 (def-edebug-spec org-babel-map-call-lines
(form body
))
1148 (defmacro org-babel-map-executables
(file &rest body
)
1149 (declare (indent 1))
1150 (let ((tempvar (make-symbol "file"))
1151 (rx (make-symbol "rx")))
1152 `(let* ((,tempvar
,file
)
1153 (,rx
(concat "\\(" org-babel-src-block-regexp
1154 "\\|" org-babel-inline-src-block-regexp
1155 "\\|" org-babel-lob-one-liner-regexp
"\\)"))
1156 (visited-p (or (null ,tempvar
)
1157 (get-file-buffer (expand-file-name ,tempvar
))))
1158 (point (point)) to-be-removed
)
1159 (save-window-excursion
1160 (when ,tempvar
(find-file ,tempvar
))
1161 (setq to-be-removed
(current-buffer))
1162 (goto-char (point-min))
1163 (while (re-search-forward ,rx nil t
)
1164 (when (org-babel-active-location-p)
1165 (goto-char (match-beginning 1))
1166 (when (looking-at org-babel-inline-src-block-regexp
)
1168 (save-match-data ,@body
))
1169 (goto-char (match-end 0))))
1170 (unless visited-p
(kill-buffer to-be-removed
))
1171 (goto-char point
))))
1172 (def-edebug-spec org-babel-map-executables
(form body
))
1175 (defun org-babel-execute-buffer (&optional arg
)
1176 "Execute source code blocks in a buffer.
1177 Call `org-babel-execute-src-block' on every source block in
1178 the current buffer."
1180 (org-babel-eval-wipe-error-buffer)
1181 (org-save-outline-visibility t
1182 (org-babel-map-executables nil
1183 (if (looking-at org-babel-lob-one-liner-regexp
)
1184 (org-babel-lob-execute-maybe)
1185 (org-babel-execute-src-block arg
)))))
1188 (defun org-babel-execute-subtree (&optional arg
)
1189 "Execute source code blocks in a subtree.
1190 Call `org-babel-execute-src-block' on every source block in
1191 the current subtree."
1195 (org-narrow-to-subtree)
1196 (org-babel-execute-buffer arg
)
1200 (defun org-babel-sha1-hash (&optional info
)
1201 "Generate an sha1 hash based on the value of info."
1203 (let ((print-level nil
)
1204 (info (or info
(org-babel-get-src-block-info))))
1206 (sort (copy-sequence (nth 2 info
))
1207 (lambda (a b
) (string< (car a
) (car b
)))))
1208 (let* ((rm (lambda (lst)
1209 (dolist (p '("replace" "silent" "none"
1210 "append" "prepend"))
1211 (setq lst
(remove p lst
)))
1214 (let ((v (if (and (listp (cdr arg
)) (null (cddr arg
)))
1215 (copy-sequence (cdr arg
))
1217 (when (and v
(not (and (sequencep v
)
1221 ((and (listp v
) ; lists are sorted
1222 (member (car arg
) '(:result-params
)))
1223 (sort (funcall rm v
) #'string
<))
1224 ((and (stringp v
) ; strings are sorted
1225 (member (car arg
) '(:results
:exports
)))
1226 (mapconcat #'identity
(sort (funcall rm
(split-string v
))
1231 (params (nth 2 info
))
1232 (body (if (org-babel-noweb-p params
:eval
)
1233 (org-babel-expand-noweb-references info
) (nth 1 info
)))
1234 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
1235 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
1238 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
1239 (org-babel-expand-body:generic
1240 body params
(and (fboundp assignments-cmd
)
1241 (funcall assignments-cmd params
))))))
1242 (let* ((it (format "%s-%s"
1245 (delq nil
(mapcar (lambda (arg)
1246 (let ((normalized (funcall norm arg
)))
1248 (format "%S" normalized
))))
1252 (when (org-called-interactively-p 'interactive
) (message hash
))
1255 (defun org-babel-current-result-hash (&optional info
)
1256 "Return the current in-buffer hash."
1257 (org-babel-where-is-src-block-result nil info
)
1258 (org-no-properties (match-string 5)))
1260 (defun org-babel-set-current-result-hash (hash info
)
1261 "Set the current in-buffer hash to HASH."
1262 (org-babel-where-is-src-block-result nil info
)
1263 (save-excursion (goto-char (match-beginning 5))
1264 (mapc #'delete-overlay
(overlays-at (point)))
1265 (forward-char org-babel-hash-show
)
1266 (mapc #'delete-overlay
(overlays-at (point)))
1267 (replace-match hash nil nil nil
5)
1268 (goto-char (point-at-bol))
1269 (org-babel-hide-hash)))
1271 (defun org-babel-hide-hash ()
1272 "Hide the hash in the current results line.
1273 Only the initial `org-babel-hash-show' characters of the hash
1274 will remain visible."
1275 (add-to-invisibility-spec '(org-babel-hide-hash . t
))
1277 (when (and (re-search-forward org-babel-result-regexp nil t
)
1279 (let* ((start (match-beginning 5))
1280 (hide-start (+ org-babel-hash-show start
))
1282 (hash (match-string 5))
1284 (setq ov1
(make-overlay start hide-start
))
1285 (setq ov2
(make-overlay hide-start end
))
1286 (overlay-put ov2
'invisible
'org-babel-hide-hash
)
1287 (overlay-put ov1
'babel-hash hash
)))))
1289 (defun org-babel-hide-all-hashes ()
1290 "Hide the hash in the current buffer.
1291 Only the initial `org-babel-hash-show' characters of each hash
1292 will remain visible. This function should be called as part of
1293 the `org-mode-hook'."
1295 (while (and (not org-babel-hash-show-time
)
1296 (re-search-forward org-babel-result-regexp nil t
))
1297 (goto-char (match-beginning 0))
1298 (org-babel-hide-hash)
1299 (goto-char (match-end 0)))))
1300 (add-hook 'org-mode-hook
'org-babel-hide-all-hashes
)
1302 (defun org-babel-hash-at-point (&optional point
)
1303 "Return the value of the hash at POINT.
1304 The hash is also added as the last element of the kill ring.
1305 This can be called with C-c C-c."
1307 (let ((hash (car (delq nil
(mapcar
1308 (lambda (ol) (overlay-get ol
'babel-hash
))
1309 (overlays-at (or point
(point))))))))
1310 (when hash
(kill-new hash
) (message hash
))))
1311 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-hash-at-point
)
1313 (defun org-babel-result-hide-spec ()
1314 "Hide portions of results lines.
1315 Add `org-babel-hide-result' as an invisibility spec for hiding
1316 portions of results lines."
1317 (add-to-invisibility-spec '(org-babel-hide-result . t
)))
1318 (add-hook 'org-mode-hook
'org-babel-result-hide-spec
)
1320 (defvar org-babel-hide-result-overlays nil
1321 "Overlays hiding results.")
1323 (defun org-babel-result-hide-all ()
1324 "Fold all results in the current buffer."
1326 (org-babel-show-result-all)
1328 (while (re-search-forward org-babel-result-regexp nil t
)
1329 (save-excursion (goto-char (match-beginning 0))
1330 (org-babel-hide-result-toggle-maybe)))))
1332 (defun org-babel-show-result-all ()
1333 "Unfold all results in the current buffer."
1334 (mapc 'delete-overlay org-babel-hide-result-overlays
)
1335 (setq org-babel-hide-result-overlays nil
))
1338 (defun org-babel-hide-result-toggle-maybe ()
1339 "Toggle visibility of result at point."
1341 (let ((case-fold-search t
))
1343 (beginning-of-line 1)
1344 (looking-at org-babel-result-regexp
))
1345 (progn (org-babel-hide-result-toggle)
1346 t
) ;; to signal that we took action
1347 nil
))) ;; to signal that we did not
1349 (defun org-babel-hide-result-toggle (&optional force
)
1350 "Toggle the visibility of the current result."
1354 (if (re-search-forward org-babel-result-regexp nil t
)
1355 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
1357 (while (looking-at org-babel-multi-line-header-regexp
)
1359 (goto-char (- (org-babel-result-end) 1)) (point)))
1361 (if (memq t
(mapcar (lambda (overlay)
1362 (eq (overlay-get overlay
'invisible
)
1363 'org-babel-hide-result
))
1364 (overlays-at start
)))
1365 (if (or (not force
) (eq force
'off
))
1367 (when (member ov org-babel-hide-result-overlays
)
1368 (setq org-babel-hide-result-overlays
1369 (delq ov org-babel-hide-result-overlays
)))
1370 (when (eq (overlay-get ov
'invisible
)
1371 'org-babel-hide-result
)
1372 (delete-overlay ov
)))
1373 (overlays-at start
)))
1374 (setq ov
(make-overlay start end
))
1375 (overlay-put ov
'invisible
'org-babel-hide-result
)
1376 ;; make the block accessible to isearch
1378 ov
'isearch-open-invisible
1380 (when (member ov org-babel-hide-result-overlays
)
1381 (setq org-babel-hide-result-overlays
1382 (delq ov org-babel-hide-result-overlays
)))
1383 (when (eq (overlay-get ov
'invisible
)
1384 'org-babel-hide-result
)
1385 (delete-overlay ov
))))
1386 (push ov org-babel-hide-result-overlays
)))
1387 (error "Not looking at a result line"))))
1389 ;; org-tab-after-check-for-cycling-hook
1390 (add-hook 'org-tab-first-hook
'org-babel-hide-result-toggle-maybe
)
1391 ;; Remove overlays when changing major mode
1392 (add-hook 'org-mode-hook
1393 (lambda () (org-add-hook 'change-major-mode-hook
1394 'org-babel-show-result-all
'append
'local
)))
1396 (defvar org-file-properties
)
1397 (defun org-babel-params-from-properties (&optional lang
)
1398 "Retrieve parameters specified as properties.
1399 Return a list of association lists of source block params
1400 specified in the properties of the current outline entry."
1403 ;; DEPRECATED header arguments specified as separate property at
1404 ;; point of definition
1406 (org-babel-parse-multiple-vars
1409 (lambda (header-arg)
1410 (and (setq val
(org-entry-get (point) header-arg t
))
1411 (cons (intern (concat ":" header-arg
))
1412 (org-babel-read val
))))
1417 (org-babel-combine-header-arg-lists
1418 org-babel-common-header-args-w-values
1420 (setq sym
(intern (concat "org-babel-header-args:" lang
)))
1421 (and (boundp sym
) (eval sym
))))))))))
1422 ;; header arguments specified with the header-args property at
1424 (org-babel-parse-header-arguments
1425 (org-entry-get org-babel-current-src-block-location
1426 "header-args" 'inherit
))
1427 (when lang
;; language-specific header arguments at point of call
1428 (org-babel-parse-header-arguments
1429 (org-entry-get org-babel-current-src-block-location
1430 (concat "header-args:" lang
) 'inherit
))))))
1432 (defvar org-src-preserve-indentation
)
1433 (defun org-babel-parse-src-block-match ()
1434 "Parse the results from a match of the `org-babel-src-block-regexp'."
1435 (let* ((block-indentation (length (match-string 1)))
1436 (lang (org-no-properties (match-string 2)))
1437 (lang-headers (intern (concat "org-babel-default-header-args:" lang
)))
1438 (switches (match-string 3))
1439 (body (org-no-properties
1440 (let* ((body (match-string 5))
1441 (sub-length (- (length body
) 1)))
1442 (if (and (> sub-length
0)
1443 (string= "\n" (substring body sub-length
)))
1444 (substring body
0 sub-length
)
1446 (preserve-indentation (or org-src-preserve-indentation
1448 (string-match "-i\\>" switches
)))))
1450 ;; get block body less properties, protective commas, and indentation
1453 (insert (org-unescape-code-in-string body
))
1454 (unless preserve-indentation
(org-do-remove-indentation))
1456 (apply #'org-babel-merge-params
1457 org-babel-default-header-args
1458 (when (boundp lang-headers
) (eval lang-headers
))
1460 (org-babel-params-from-properties lang
)
1461 (list (org-babel-parse-header-arguments
1462 (org-no-properties (or (match-string 4) ""))))))
1464 block-indentation
)))
1466 (defun org-babel-parse-inline-src-block-match ()
1467 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
1468 (let* ((lang (org-no-properties (match-string 2)))
1469 (lang-headers (intern (concat "org-babel-default-header-args:" lang
))))
1471 (org-unescape-code-in-string (org-no-properties (match-string 5)))
1472 (apply #'org-babel-merge-params
1473 org-babel-default-inline-header-args
1474 (if (boundp lang-headers
) (eval lang-headers
) nil
)
1476 (org-babel-params-from-properties lang
)
1477 (list (org-babel-parse-header-arguments
1478 (org-no-properties (or (match-string 4) ""))))))
1481 (defun org-babel-balanced-split (string alts
)
1482 "Split STRING on instances of ALTS.
1483 ALTS is a cons of two character options where each option may be
1484 either the numeric code of a single character or a list of
1485 character alternatives. For example to split on balanced
1486 instances of \"[ \t]:\" set ALTS to '((32 9) . 58)."
1487 (let* ((matches (lambda (ch spec
) (if (listp spec
) (member ch spec
) (equal spec ch
))))
1488 (matched (lambda (ch last
)
1490 (and (funcall matches ch
(cdr alts
))
1491 (funcall matches last
(car alts
)))
1492 (funcall matches ch alts
))))
1493 (balance 0) (last 0)
1495 (mapc (lambda (ch) ; split on [], (), "" balanced instances of [ \t]:
1496 (setq balance
(+ balance
1497 (cond ((or (equal 91 ch
) (equal 40 ch
)) 1)
1498 ((or (equal 93 ch
) (equal 41 ch
)) -
1)
1500 (when (and (equal 34 ch
) (not (equal 92 last
)))
1501 (setq quote
(not quote
)))
1502 (setq partial
(cons ch partial
))
1503 (when (and (= balance
0) (not quote
) (funcall matched ch last
))
1504 (setq lst
(cons (apply #'string
(nreverse
1511 (string-to-list string
))
1512 (nreverse (cons (apply #'string
(nreverse partial
)) lst
))))
1514 (defun org-babel-join-splits-near-ch (ch list
)
1515 "Join splits where \"=\" is on either end of the split."
1516 (let ((last= (lambda (str) (= ch
(aref str
(1- (length str
))))))
1517 (first= (lambda (str) (= ch
(aref str
0)))))
1519 (org-reduce (lambda (acc el
)
1520 (let ((head (car acc
)))
1521 (if (and head
(or (funcall last
= head
) (funcall first
= el
)))
1522 (cons (concat head el
) (cdr acc
))
1524 list
:initial-value nil
))))
1526 (defun org-babel-parse-header-arguments (arg-string)
1527 "Parse a string of header arguments returning an alist."
1528 (when (> (length arg-string
) 0)
1529 (org-babel-parse-multiple-vars
1534 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1536 (cons (intern (match-string 1 arg
))
1537 (org-babel-read (org-babel-chomp (match-string 2 arg
))))
1538 (cons (intern (org-babel-chomp arg
)) nil
)))
1539 (let ((raw (org-babel-balanced-split arg-string
'((32 9) .
58))))
1540 (cons (car raw
) (mapcar (lambda (r) (concat ":" r
)) (cdr raw
)))))))))
1542 (defun org-babel-parse-multiple-vars (header-arguments)
1543 "Expand multiple variable assignments behind a single :var keyword.
1545 This allows expression of multiple variables with one :var as
1548 #+PROPERTY: var foo=1, bar=2"
1550 (mapc (lambda (pair)
1551 (if (eq (car pair
) :var
)
1552 (mapcar (lambda (v) (push (cons :var
(org-babel-trim v
)) results
))
1553 (org-babel-join-splits-near-ch
1554 61 (org-babel-balanced-split (cdr pair
) 32)))
1555 (push pair results
)))
1557 (nreverse results
)))
1559 (defun org-babel-process-params (params)
1560 "Expand variables in PARAMS and add summary parameters."
1561 (let* ((processed-vars (mapcar (lambda (el)
1562 (if (consp (cdr el
))
1564 (org-babel-ref-parse (cdr el
))))
1565 (org-babel-get-header params
:var
)))
1566 (vars-and-names (if (and (assoc :colname-names params
)
1567 (assoc :rowname-names params
))
1568 (list processed-vars
)
1569 (org-babel-disassemble-tables
1571 (cdr (assoc :hlines params
))
1572 (cdr (assoc :colnames params
))
1573 (cdr (assoc :rownames params
)))))
1574 (raw-result (or (cdr (assoc :results params
)) ""))
1575 (result-params (append
1576 (split-string (if (stringp raw-result
)
1579 (cdr (assoc :result-params params
)))))
1581 (mapcar (lambda (var) (cons :var var
)) (car vars-and-names
))
1583 (cons :colname-names
(or (cdr (assoc :colname-names params
))
1584 (cadr vars-and-names
)))
1585 (cons :rowname-names
(or (cdr (assoc :rowname-names params
))
1586 (caddr vars-and-names
)))
1587 (cons :result-params result-params
)
1588 (cons :result-type
(cond ((member "output" result-params
) 'output
)
1589 ((member "value" result-params
) 'value
)
1591 (org-babel-get-header params
:var
'other
))))
1593 ;; row and column names
1594 (defun org-babel-del-hlines (table)
1595 "Remove all 'hlines from TABLE."
1596 (remq 'hline table
))
1598 (defun org-babel-get-colnames (table)
1599 "Return the column names of TABLE.
1600 Return a cons cell, the `car' of which contains the TABLE less
1601 colnames, and the `cdr' of which contains a list of the column
1603 (if (equal 'hline
(nth 1 table
))
1604 (cons (cddr table
) (car table
))
1605 (cons (cdr table
) (car table
))))
1607 (defun org-babel-get-rownames (table)
1608 "Return the row names of TABLE.
1609 Return a cons cell, the `car' of which contains the TABLE less
1610 rownames, and the `cdr' of which contains a list of the rownames.
1611 Note: this function removes any hlines in TABLE."
1612 (let* ((table (org-babel-del-hlines table
))
1613 (rownames (funcall (lambda ()
1619 (setq tp
(cdr tp
))))
1621 (cons table rownames
)))
1623 (defun org-babel-put-colnames (table colnames
)
1624 "Add COLNAMES to TABLE if they exist."
1625 (if colnames
(apply 'list colnames
'hline table
) table
))
1627 (defun org-babel-put-rownames (table rownames
)
1628 "Add ROWNAMES to TABLE if they exist."
1630 (mapcar (lambda (row)
1632 (cons (or (pop rownames
) "") row
)
1636 (defun org-babel-pick-name (names selector
)
1637 "Select one out of an alist of row or column names.
1638 SELECTOR can be either a list of names in which case those names
1639 will be returned directly, or an index into the list NAMES in
1640 which case the indexed names will be return."
1641 (if (listp selector
)
1644 (if (and selector
(symbolp selector
) (not (equal t selector
)))
1645 (cdr (assoc selector names
))
1646 (if (integerp selector
)
1647 (nth (- selector
1) names
)
1648 (cdr (car (last names
))))))))
1650 (defun org-babel-disassemble-tables (vars hlines colnames rownames
)
1651 "Parse tables for further processing.
1652 Process the variables in VARS according to the HLINES,
1653 ROWNAMES and COLNAMES header arguments. Return a list consisting
1654 of the vars, cnames and rnames."
1655 (let (cnames rnames
)
1659 (when (listp (cdr var
))
1660 (when (and (not (equal colnames
"no"))
1661 (or colnames
(and (equal (nth 1 (cdr var
)) 'hline
)
1662 (not (member 'hline
(cddr (cdr var
)))))))
1663 (let ((both (org-babel-get-colnames (cdr var
))))
1664 (setq cnames
(cons (cons (car var
) (cdr both
))
1666 (setq var
(cons (car var
) (car both
)))))
1667 (when (and rownames
(not (equal rownames
"no")))
1668 (let ((both (org-babel-get-rownames (cdr var
))))
1669 (setq rnames
(cons (cons (car var
) (cdr both
))
1671 (setq var
(cons (car var
) (car both
)))))
1672 (when (and hlines
(not (equal hlines
"yes")))
1673 (setq var
(cons (car var
) (org-babel-del-hlines (cdr var
))))))
1676 (reverse cnames
) (reverse rnames
))))
1678 (defun org-babel-reassemble-table (table colnames rownames
)
1679 "Add column and row names to a table.
1680 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1681 to the table for reinsertion to org-mode."
1683 (let ((table (if (and rownames
(= (length table
) (length rownames
)))
1684 (org-babel-put-rownames table rownames
) table
)))
1685 (if (and colnames
(listp (car table
)) (= (length (car table
))
1687 (org-babel-put-colnames table colnames
) table
))
1690 (defun org-babel-where-is-src-block-head ()
1691 "Find where the current source block begins.
1692 Return the point at the beginning of the current source
1693 block. Specifically at the beginning of the #+BEGIN_SRC line.
1694 If the point is not on a source block then return nil."
1695 (let ((initial (point)) (case-fold-search t
) top bottom
)
1697 (save-excursion ;; on a source name line or a #+header line
1698 (beginning-of-line 1)
1699 (and (or (looking-at org-babel-src-name-regexp
)
1700 (looking-at org-babel-multi-line-header-regexp
))
1702 (while (and (forward-line 1)
1703 (or (looking-at org-babel-src-name-regexp
)
1704 (looking-at org-babel-multi-line-header-regexp
))))
1705 (looking-at org-babel-src-block-regexp
))
1707 (save-excursion ;; on a #+begin_src line
1708 (beginning-of-line 1)
1709 (and (looking-at org-babel-src-block-regexp
)
1711 (save-excursion ;; inside a src block
1713 (re-search-backward "^[ \t]*#\\+begin_src" nil t
) (setq top
(point))
1714 (re-search-forward "^[ \t]*#\\+end_src" nil t
) (setq bottom
(point))
1715 (< top initial
) (< initial bottom
)
1716 (progn (goto-char top
) (beginning-of-line 1)
1717 (looking-at org-babel-src-block-regexp
))
1721 (defun org-babel-goto-src-block-head ()
1722 "Go to the beginning of the current code block."
1724 (let ((head (org-babel-where-is-src-block-head)))
1725 (if head
(goto-char head
) (error "Not currently in a code block"))))
1728 (defun org-babel-goto-named-src-block (name)
1729 "Go to a named source-code block."
1731 (let ((completion-ignore-case t
)
1732 (case-fold-search t
)
1733 (under-point (thing-at-point 'line
)))
1734 (list (org-icompleting-read
1735 "source-block name: " (org-babel-src-block-names) nil t
1738 ((string-match (org-babel-noweb-wrap) under-point
)
1739 (let ((block-name (match-string 1 under-point
)))
1740 (string-match "[^(]*" block-name
)
1741 (match-string 0 block-name
)))
1743 ((string-match org-babel-lob-one-liner-regexp under-point
)
1744 (let ((source-info (car (org-babel-lob-get-info))))
1745 (if (string-match "^\\([^\\[]+?\\)\\(\\[.*\\]\\)?(" source-info
)
1746 (let ((source-name (match-string 1 source-info
)))
1749 ((string-match (concat "#\\+" org-babel-results-keyword
1750 "\\:\s+\\([^\\(]*\\)") under-point
)
1751 (match-string 1 under-point
))
1753 ((and (thing-at-point 'symbol
))
1754 (org-babel-find-named-block (thing-at-point 'symbol
))
1755 (thing-at-point 'symbol
))
1757 (let ((point (org-babel-find-named-block name
)))
1759 ;; taken from `org-open-at-point'
1760 (progn (org-mark-ring-push) (goto-char point
) (org-show-context))
1761 (message "source-code block '%s' not found in this buffer" name
))))
1763 (defun org-babel-find-named-block (name)
1764 "Find a named source-code block.
1765 Return the location of the source block identified by source
1766 NAME, or nil if no such block exists. Set match data according to
1767 org-babel-named-src-block-regexp."
1769 (let ((case-fold-search t
)
1770 (regexp (org-babel-named-src-block-regexp-for-name name
)) msg
)
1771 (goto-char (point-min))
1772 (when (or (re-search-forward regexp nil t
)
1773 (re-search-backward regexp nil t
))
1774 (match-beginning 0)))))
1776 (defun org-babel-src-block-names (&optional file
)
1777 "Returns the names of source blocks in FILE or the current buffer."
1779 (when file
(find-file file
)) (goto-char (point-min))
1780 (let ((case-fold-search t
) names
)
1781 (while (re-search-forward org-babel-src-name-w-name-regexp nil t
)
1782 (setq names
(cons (match-string 3) names
)))
1786 (defun org-babel-goto-named-result (name)
1787 "Go to a named result."
1789 (let ((completion-ignore-case t
))
1790 (list (org-icompleting-read "source-block name: "
1791 (org-babel-result-names) nil t
))))
1792 (let ((point (org-babel-find-named-result name
)))
1794 ;; taken from `org-open-at-point'
1795 (progn (goto-char point
) (org-show-context))
1796 (message "result '%s' not found in this buffer" name
))))
1798 (defun org-babel-find-named-result (name &optional point
)
1799 "Find a named result.
1800 Return the location of the result named NAME in the current
1801 buffer or nil if no such result exists."
1803 (let ((case-fold-search t
))
1804 (goto-char (or point
(point-min)))
1805 (catch 'is-a-code-block
1806 (when (re-search-forward
1807 (concat org-babel-result-regexp
1808 "[ \t]" (regexp-quote name
) "[ \t]*[\n\f\v\r]") nil t
)
1809 (when (and (string= "name" (downcase (match-string 1)))
1810 (or (beginning-of-line 1)
1811 (looking-at org-babel-src-block-regexp
)
1812 (looking-at org-babel-multi-line-header-regexp
)
1813 (looking-at org-babel-lob-one-liner-regexp
)))
1814 (throw 'is-a-code-block
(org-babel-find-named-result name
(point))))
1815 (beginning-of-line 0) (point))))))
1817 (defun org-babel-result-names (&optional file
)
1818 "Returns the names of results in FILE or the current buffer."
1820 (when file
(find-file file
)) (goto-char (point-min))
1821 (let ((case-fold-search t
) names
)
1822 (while (re-search-forward org-babel-result-w-name-regexp nil t
)
1823 (setq names
(cons (match-string 4) names
)))
1827 (defun org-babel-next-src-block (&optional arg
)
1828 "Jump to the next source block.
1829 With optional prefix argument ARG, jump forward ARG many source blocks."
1831 (org-next-block arg nil org-babel-src-block-regexp
))
1834 (defun org-babel-previous-src-block (&optional arg
)
1835 "Jump to the previous source block.
1836 With optional prefix argument ARG, jump backward ARG many source blocks."
1838 (org-previous-block arg org-babel-src-block-regexp
))
1840 (defvar org-babel-load-languages
)
1843 (defun org-babel-mark-block ()
1844 "Mark current src block."
1846 (let ((head (org-babel-where-is-src-block-head)))
1850 (looking-at org-babel-src-block-regexp
))
1851 (push-mark (match-end 5) nil t
)
1852 (goto-char (match-beginning 5)))))
1854 (defun org-babel-demarcate-block (&optional arg
)
1855 "Wrap or split the code in the region or on the point.
1856 When called from inside of a code block the current block is
1857 split. When called from outside of a code block a new code block
1858 is created. In both cases if the region is demarcated and if the
1859 region is not active then the point is demarcated."
1861 (let* ((info (org-babel-get-src-block-info 'light
))
1862 (block (progn (org-babel-where-is-src-block-head) (match-string 0)))
1863 (headers (progn (org-babel-where-is-src-block-head) (match-string 4)))
1864 (stars (concat (make-string (or (org-current-level) 1) ?
*) " "))
1866 (if (let (case-fold-search) (string-match "#\\+begin_src" block
))
1867 (setq lower-case-p t
))
1873 (let ((lang (nth 0 info
))
1874 (indent (make-string (nth 5 info
) ?
)))
1875 (when (string-match "^[[:space:]]*$"
1876 (buffer-substring (point-at-bol)
1878 (delete-region (point-at-bol) (point-at-eol)))
1880 (if (looking-at "^") "" "\n")
1881 indent
(funcall (if lower-case-p
'downcase
'upcase
) "#+end_src\n")
1882 (if arg stars indent
) "\n"
1883 indent
(funcall (if lower-case-p
'downcase
'upcase
) "#+begin_src ")
1885 (if (> (length headers
) 1)
1886 (concat " " headers
) headers
)
1887 (if (looking-at "[\n\r]")
1889 (concat "\n" (make-string (current-column) ?
)))))))
1890 (move-end-of-line 2))
1891 (sort (if (org-region-active-p) (list (mark) (point)) (list (point))) #'>))
1892 (let ((start (point))
1893 (lang (org-icompleting-read
1895 (mapcar #'symbol-name
1897 (append (mapcar #'car org-babel-load-languages
)
1898 (mapcar (lambda (el) (intern (car el
)))
1899 org-src-lang-modes
))))))
1900 (body (delete-and-extract-region
1901 (if (org-region-active-p) (mark) (point)) (point))))
1902 (insert (concat (if (looking-at "^") "" "\n")
1903 (if arg
(concat stars
"\n") "")
1904 (funcall (if lower-case-p
'downcase
'upcase
) "#+begin_src ")
1907 (if (or (= (length body
) 0)
1908 (string-match "[\r\n]$" body
)) "" "\n")
1909 (funcall (if lower-case-p
'downcase
'upcase
) "#+end_src\n")))
1910 (goto-char start
) (move-end-of-line 1)))))
1912 (defvar org-babel-lob-one-liner-regexp
)
1913 (defun org-babel-where-is-src-block-result (&optional insert info hash indent
)
1914 "Find where the current source block results begin.
1915 Return the point at the beginning of the result of the current
1916 source block. Specifically at the beginning of the results line.
1917 If no result exists for this block then create a results line
1918 following the source block."
1920 (let* ((case-fold-search t
)
1921 (on-lob-line (save-excursion
1922 (beginning-of-line 1)
1923 (looking-at org-babel-lob-one-liner-regexp
)))
1924 (inlinep (when (org-babel-get-inline-src-block-matches)
1926 (name (nth 4 (or info
(org-babel-get-src-block-info 'light
))))
1927 (head (unless on-lob-line
(org-babel-where-is-src-block-head)))
1929 (when head
(goto-char head
))
1930 (org-with-wide-buffer
1932 found
;; was there a result (before we potentially insert one)
1937 ;; - return t if it is found, else return nil
1938 ;; - if it does not need to be rebuilt, then don't set end
1939 ;; - if it does need to be rebuilt then do set end
1940 name
(setq beg
(org-babel-find-named-result name
))
1942 (when (and hash
(not (string= hash
(match-string 5))))
1943 (goto-char beg
) (setq end beg
) ;; beginning of result
1945 (delete-region end
(org-babel-result-end)) nil
)))
1948 ;; - return t if it is found, else return nil
1949 ;; - if it is found, and the hash doesn't match, delete and set end
1950 (or on-lob-line
(re-search-forward "^[ \t]*#\\+end_src" nil t
))
1951 (progn (end-of-line 1)
1952 (if (eobp) (insert "\n") (forward-char 1))
1956 (progn ;; unnamed results line already exists
1958 (while (re-search-forward "[^ \f\t\n\r\v]" nil t
)
1959 (beginning-of-line 1)
1961 ((looking-at (concat org-babel-result-regexp
"\n"))
1962 (throw 'non-comment t
))
1963 ((and (looking-at "^[ \t]*#")
1965 org-babel-lob-one-liner-regexp
)))
1967 (t (throw 'non-comment nil
))))))
1968 (let ((this-hash (match-string 5)))
1970 ;; must remove and rebuild if hash!=old-hash
1971 (if (and hash
(not (string= hash this-hash
)))
1973 (setq end
(point-at-bol))
1975 (delete-region end
(org-babel-result-end))
1977 (setq end nil
))))))))))
1978 (if (not (and insert end
)) found
1981 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1983 (when (wholenump indent
) (make-string indent ?
))
1984 "#+" org-babel-results-keyword
1986 (if org-babel-hash-show-time
1988 "["(format-time-string "<%Y-%m-%d %H:%M:%S>")" "hash
"]")
1989 (concat "["hash
"]")))
1991 (when name
(concat " " name
)) "\n"))
1992 (unless beg
(insert "\n") (backward-char))
1993 (beginning-of-line 0)
1994 (if hash
(org-babel-hide-hash))
1997 (defvar org-block-regexp
)
1998 (defun org-babel-read-result ()
1999 "Read the result at `point' into emacs-lisp."
2000 (let ((case-fold-search t
) result-string
)
2002 ((org-at-table-p) (org-babel-read-table))
2003 ((org-at-item-p) (org-babel-read-list))
2004 ((looking-at org-bracket-link-regexp
) (org-babel-read-link))
2005 ((looking-at org-block-regexp
) (org-remove-indentation (match-string 4)))
2006 ((or (looking-at "^[ \t]*: ") (looking-at "^[ \t]*:$"))
2009 (mapconcat (lambda (line)
2010 (or (and (> (length line
) 1)
2011 (string-match "^[ \t]*: ?\\(.+\\)" line
)
2012 (match-string 1 line
))
2016 (point) (org-babel-result-end)) "[\r\n]+")
2018 (or (org-babel-number-p result-string
) result-string
))
2019 ((looking-at org-babel-result-regexp
)
2020 (save-excursion (forward-line 1) (org-babel-read-result))))))
2022 (defun org-babel-read-table ()
2023 "Read the table at `point' into emacs-lisp."
2024 (mapcar (lambda (row)
2025 (if (and (symbolp row
) (equal row
'hline
)) row
2026 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
)) row
)))
2027 (org-table-to-lisp)))
2029 (defun org-babel-read-list ()
2030 "Read the list at `point' into emacs-lisp."
2031 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
))
2032 (mapcar #'cadr
(cdr (org-list-parse-list)))))
2034 (defvar org-link-types-re
)
2035 (defun org-babel-read-link ()
2036 "Read the link at `point' into emacs-lisp.
2037 If the path of the link is a file path it is expanded using
2038 `expand-file-name'."
2039 (let* ((case-fold-search t
)
2040 (raw (and (looking-at org-bracket-link-regexp
)
2041 (org-no-properties (match-string 1))))
2042 (type (and (string-match org-link-types-re raw
)
2043 (match-string 1 raw
))))
2045 ((not type
) (expand-file-name raw
))
2046 ((string= type
"file")
2047 (and (string-match "file\\(.*\\):\\(.+\\)" raw
)
2048 (expand-file-name (match-string 2 raw
))))
2051 (defun org-babel-format-result (result &optional sep
)
2052 "Format RESULT for writing to file."
2053 (let ((echo-res (lambda (r) (if (stringp r
) r
(format "%S" r
)))))
2057 result
(list :sep
(or sep
"\t") :fmt echo-res
))
2059 (funcall echo-res result
))))
2061 (defun org-babel-insert-result
2062 (result &optional result-params info hash indent lang
)
2063 "Insert RESULT into the current buffer.
2064 By default RESULT is inserted after the end of the
2065 current source block. With optional argument RESULT-PARAMS
2066 controls insertion of results in the org-mode file.
2067 RESULT-PARAMS can take the following values:
2069 replace - (default option) insert results after the source block
2070 replacing any previously inserted results
2072 silent -- no results are inserted into the Org-mode buffer but
2073 the results are echoed to the minibuffer and are
2074 ingested by Emacs (a potentially time consuming
2077 file ---- the results are interpreted as a file path, and are
2078 inserted into the buffer using the Org-mode file syntax
2080 list ---- the results are interpreted as an Org-mode list.
2082 raw ----- results are added directly to the Org-mode file. This
2083 is a good option if you code block will output org-mode
2086 drawer -- results are added directly to the Org-mode file as with
2087 \"raw\", but are wrapped in a RESULTS drawer, allowing
2088 them to later be replaced or removed automatically.
2090 org ----- results are added inside of a \"#+BEGIN_SRC org\" block.
2091 They are not comma-escaped when inserted, but Org syntax
2092 here will be discarded when exporting the file.
2094 html ---- results are added inside of a #+BEGIN_HTML block. This
2095 is a good option if you code block will output html
2098 latex --- results are added inside of a #+BEGIN_LATEX block.
2099 This is a good option if you code block will output
2100 latex formatted text.
2102 code ---- the results are extracted in the syntax of the source
2103 code of the language being evaluated and are added
2104 inside of a #+BEGIN_SRC block with the source-code
2105 language set appropriately. Note this relies on the
2106 optional LANG argument."
2107 (if (stringp result
)
2109 (setq result
(org-no-properties result
))
2110 (when (member "file" result-params
)
2111 (setq result
(org-babel-result-to-file
2112 result
(when (assoc :file-desc
(nth 2 info
))
2113 (or (cdr (assoc :file-desc
(nth 2 info
)))
2115 (unless (listp result
) (setq result
(format "%S" result
))))
2116 (if (and result-params
(member "silent" result-params
))
2118 (message (replace-regexp-in-string "%" "%%" (format "%S" result
)))
2123 (when (or (org-babel-get-inline-src-block-matches)
2124 (org-babel-get-lob-one-liner-matches))
2125 (goto-char (match-end 0))
2126 (insert (if (listp result
) "\n" " "))
2128 (existing-result (unless inlinep
2129 (org-babel-where-is-src-block-result
2130 t info hash indent
)))
2132 (cdr (assoc :results_switches
(nth 2 info
))))
2133 (visible-beg (copy-marker (point-min)))
2134 (visible-end (copy-marker (point-max)))
2135 ;; When results exist outside of the current visible
2136 ;; region of the buffer, be sure to widen buffer to
2138 (outside-scope-p (and existing-result
2139 (or (> visible-beg existing-result
)
2140 (<= visible-end existing-result
))))
2142 (when (and (stringp result
) ; ensure results end in a newline
2144 (> (length result
) 0)
2145 (not (or (string-equal (substring result -
1) "\n")
2146 (string-equal (substring result -
1) "\r"))))
2147 (setq result
(concat result
"\n")))
2150 (when outside-scope-p
(widen))
2151 (if (not existing-result
)
2152 (setq beg
(or inlinep
(point)))
2153 (goto-char existing-result
)
2155 (re-search-forward "#" nil t
)
2156 (setq indent
(- (current-column) 1)))
2160 ((member "replace" result-params
)
2161 (delete-region (point) (org-babel-result-end)))
2162 ((member "append" result-params
)
2163 (goto-char (org-babel-result-end)) (setq beg
(point-marker)))
2164 ((member "prepend" result-params
)))) ; already there
2165 (setq results-switches
2166 (if results-switches
(concat " " results-switches
) ""))
2167 (let ((wrap (lambda (start finish
&optional no-escape
)
2168 (goto-char end
) (insert (concat finish
"\n"))
2169 (goto-char beg
) (insert (concat start
"\n"))
2171 (org-escape-code-in-region (min (point) end
) end
))
2172 (goto-char end
) (goto-char (point-at-eol))
2173 (setq end
(point-marker))))
2174 (proper-list-p (lambda (it) (and (listp it
) (null (cdr (last it
)))))))
2175 ;; insert results based on type
2177 ;; do nothing for an empty result
2179 ;; insert a list if preferred
2180 ((member "list" result-params
)
2183 (org-list-to-generic
2186 (lambda (el) (list nil
(if (stringp el
) el
(format "%S" el
))))
2187 (if (listp result
) result
(split-string result
"\n" t
))))
2188 '(:splicep nil
:istart
"- " :iend
"\n")))
2190 ;; assume the result is a table if it's not a string
2191 ((funcall proper-list-p result
)
2193 (insert (concat (orgtbl-to-orgtbl
2195 (lambda (el) (or (listp el
) (eq el
'hline
)))
2197 result
(list result
))
2198 '(:fmt
(lambda (cell) (format "%s" cell
)))) "\n"))
2199 (goto-char beg
) (when (org-at-table-p) (org-table-align)))
2200 ((and (listp result
) (not (funcall proper-list-p result
)))
2201 (insert (format "%s\n" result
)))
2202 ((member "file" result-params
)
2203 (when inlinep
(goto-char inlinep
))
2205 (t (goto-char beg
) (insert result
)))
2206 (when (funcall proper-list-p result
) (goto-char (org-table-end)))
2207 (setq end
(point-marker))
2208 ;; possibly wrap result
2210 ((assoc :wrap
(nth 2 info
))
2211 (let ((name (or (cdr (assoc :wrap
(nth 2 info
))) "RESULTS")))
2212 (funcall wrap
(concat "#+BEGIN_" name
)
2213 (concat "#+END_" (car (org-split-string name
))))))
2214 ((member "html" result-params
)
2215 (funcall wrap
"#+BEGIN_HTML" "#+END_HTML"))
2216 ((member "latex" result-params
)
2217 (funcall wrap
"#+BEGIN_LaTeX" "#+END_LaTeX"))
2218 ((member "org" result-params
)
2219 (goto-char beg
) (if (org-at-table-p) (org-cycle))
2220 (funcall wrap
"#+BEGIN_SRC org" "#+END_SRC"))
2221 ((member "code" result-params
)
2222 (funcall wrap
(format "#+BEGIN_SRC %s%s" (or lang
"none") results-switches
)
2224 ((member "raw" result-params
)
2225 (goto-char beg
) (if (org-at-table-p) (org-cycle)))
2226 ((or (member "drawer" result-params
)
2227 ;; Stay backward compatible with <7.9.2
2228 (member "wrap" result-params
))
2229 (goto-char beg
) (if (org-at-table-p) (org-cycle))
2230 (funcall wrap
":RESULTS:" ":END:" 'no-escape
))
2231 ((and (not (funcall proper-list-p result
))
2232 (not (member "file" result-params
)))
2233 (org-babel-examplify-region beg end results-switches
)
2234 (setq end
(point)))))
2235 ;; possibly indent the results to match the #+results line
2236 (when (and (not inlinep
) (numberp indent
) indent
(> indent
0)
2237 ;; in this case `table-align' does the work for us
2238 (not (and (listp result
)
2239 (member "append" result-params
))))
2240 (indent-rigidly beg end indent
))
2242 (if (member "value" result-params
)
2243 (message "Code block returned no value.")
2244 (message "Code block produced no output."))
2245 (message "Code block evaluation complete.")))
2246 (when outside-scope-p
(narrow-to-region visible-beg visible-end
))
2247 (set-marker visible-beg nil
)
2248 (set-marker visible-end nil
))))))
2250 (defun org-babel-remove-result (&optional info keep-keyword
)
2251 "Remove the result of the current source block."
2253 (let ((location (org-babel-where-is-src-block-result nil info
)))
2256 (goto-char location
)
2257 (when (looking-at (concat org-babel-result-regexp
".*$"))
2259 (if keep-keyword
(1+ (match-end 0)) (1- (match-beginning 0)))
2260 (progn (forward-line 1) (org-babel-result-end))))))))
2262 (defun org-babel-remove-result-one-or-many (x)
2263 "Remove the result of the current source block.
2264 If called with a prefix argument, remove all result blocks
2268 (org-babel-map-src-blocks nil
(org-babel-remove-result))
2269 (org-babel-remove-result)))
2271 (defun org-babel-result-end ()
2272 "Return the point at the end of the current set of results."
2275 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
2276 ((org-at-item-p) (let* ((struct (org-list-struct))
2277 (prvs (org-list-prevs-alist struct
)))
2278 (org-list-get-list-end (point-at-bol) struct prvs
)))
2279 ((let ((case-fold-search t
)) (looking-at "^\\([ \t]*\\):results:"))
2280 (progn (re-search-forward (concat "^" (match-string 1) ":END:"))
2281 (forward-char 1) (point)))
2283 (let ((case-fold-search t
))
2284 (if (looking-at (concat "[ \t]*#\\+begin_\\([^ \t\n\r]+\\)"))
2285 (progn (re-search-forward (concat "[ \t]*#\\+end_" (match-string 1))
2288 (while (looking-at "[ \t]*\\(: \\|:$\\|\\[\\[\\)")
2292 (defun org-babel-result-to-file (result &optional description
)
2293 "Convert RESULT into an `org-mode' link with optional DESCRIPTION.
2294 If the `default-directory' is different from the containing
2295 file's directory then expand relative links."
2296 (when (stringp result
)
2297 (format "[[file:%s]%s]"
2298 (if (and default-directory
2300 (not (string= (expand-file-name default-directory
)
2302 (file-name-directory buffer-file-name
)))))
2303 (expand-file-name result default-directory
)
2305 (if description
(concat "[" description
"]") ""))))
2307 (defvar org-babel-capitalize-example-region-markers nil
2308 "Make true to capitalize begin/end example markers inserted by code blocks.")
2310 (define-obsolete-function-alias
2311 'org-babel-examplize-region
2312 'org-babel-examplify-region
"24.5")
2314 (defun org-babel-examplify-region (beg end
&optional results-switches
)
2315 "Comment out region using the inline '==' or ': ' org example quote."
2317 (let ((chars-between (lambda (b e
)
2318 (not (string-match "^[\\s]*$"
2319 (buffer-substring b e
)))))
2320 (maybe-cap (lambda (str) (if org-babel-capitalize-example-region-markers
2322 (beg-bol (save-excursion (goto-char beg
) (point-at-bol)))
2323 (end-bol (save-excursion (goto-char end
) (point-at-bol)))
2324 (end-eol (save-excursion (goto-char end
) (point-at-eol))))
2325 (if (and (not (= end end-bol
))
2326 (or (funcall chars-between beg-bol beg
)
2327 (funcall chars-between end end-eol
)))
2330 (insert (format org-babel-inline-result-wrap
2331 (prog1 (buffer-substring beg end
)
2332 (delete-region beg end
)))))
2333 (let ((size (count-lines beg end
)))
2335 (cond ((= size
0)) ; do nothing for an empty result
2336 ((< size org-babel-min-lines-for-block-output
)
2339 (beginning-of-line 1) (insert ": ") (forward-line 1)))
2342 (insert (if results-switches
2344 (funcall maybe-cap
"#+begin_example")
2346 (funcall maybe-cap
"#+begin_example\n")))
2347 (if (markerp end
) (goto-char end
) (forward-char (- end beg
)))
2348 (insert (funcall maybe-cap
"#+end_example\n")))))))))
2350 (defun org-babel-update-block-body (new-body)
2351 "Update the body of the current code block to NEW-BODY."
2352 (if (not (org-babel-where-is-src-block-head))
2353 (error "Not in a source block")
2355 (replace-match (concat (org-babel-trim (org-remove-indentation new-body
))
2357 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
2359 (defun org-babel-merge-params (&rest plists
)
2360 "Combine all parameter association lists in PLISTS.
2361 Later elements of PLISTS override the values of previous elements.
2362 This takes into account some special considerations for certain
2363 parameters when merging lists."
2364 (let* ((results-exclusive-groups
2365 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2366 (cdr (assoc 'results org-babel-common-header-args-w-values
))))
2367 (exports-exclusive-groups
2368 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2369 (cdr (assoc 'exports org-babel-common-header-args-w-values
))))
2371 (e-merge (lambda (exclusive-groups &rest result-params
)
2372 ;; maintain exclusivity of mutually exclusive parameters
2374 (mapc (lambda (new-params)
2375 (mapc (lambda (new-param)
2376 (mapc (lambda (exclusive-group)
2377 (when (member new-param exclusive-group
)
2378 (mapcar (lambda (excluded-param)
2385 (setq output
(org-uniquify
2386 (cons new-param output
))))
2390 params results exports tangle noweb cache vars shebang comments padline
2399 (let ((name (if (listp (cdr pair
))
2401 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
2403 (intern (match-string 1 (cdr pair
)))))))
2407 (if (member name
(mapcar #'car vars
))
2409 (push name clearnames
)
2413 (unless (equal (car p
) name
) p
))
2416 (list (cons name pair
))))
2417 ;; if no name is given and we already have named variables
2418 ;; then assign to named variables in order
2419 (if (and vars
(nth variable-index vars
))
2420 (let ((name (car (nth variable-index vars
))))
2421 (push name clearnames
) ; clear out colnames
2424 (prog1 (setf (cddr (nth variable-index vars
))
2425 (concat (symbol-name name
) "=" (cdr pair
)))
2426 (incf variable-index
)))
2427 (error "Variable \"%s\" must be assigned a default value"
2430 (setq results
(funcall e-merge results-exclusive-groups
2433 (let ((r (cdr pair
)))
2434 (if (stringp r
) r
(eval r
)))))))
2437 (setq results
(funcall e-merge results-exclusive-groups
2439 (unless (or (member "both" exports
)
2440 (member "none" exports
)
2441 (member "code" exports
))
2442 (setq exports
(funcall e-merge exports-exclusive-groups
2443 exports
'("results"))))
2444 (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))
2447 (setq results
(funcall e-merge results-exclusive-groups
2449 (unless (or (member "both" exports
)
2450 (member "none" exports
)
2451 (member "code" exports
))
2452 (setq exports
(funcall e-merge exports-exclusive-groups
2453 exports
'("results"))))
2454 (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))
2456 (setq exports
(funcall e-merge exports-exclusive-groups
2457 exports
(split-string (cdr pair
)))))
2458 (:tangle
;; take the latest -- always overwrite
2459 (setq tangle
(or (list (cdr pair
)) tangle
)))
2461 (setq noweb
(funcall e-merge
2462 '(("yes" "no" "tangle" "no-export"
2463 "strip-export" "eval"))
2465 (split-string (or (cdr pair
) "")))))
2467 (setq cache
(funcall e-merge
'(("yes" "no")) cache
2468 (split-string (or (cdr pair
) "")))))
2470 (setq padline
(funcall e-merge
'(("yes" "no")) padline
2471 (split-string (or (cdr pair
) "")))))
2472 (:shebang
;; take the latest -- always overwrite
2473 (setq shebang
(or (list (cdr pair
)) shebang
)))
2475 (setq comments
(funcall e-merge
'(("yes" "no")) comments
2476 (split-string (or (cdr pair
) "")))))
2477 (t ;; replace: this covers e.g. :session
2478 (setq params
(cons pair
(assq-delete-all (car pair
) params
))))))
2481 (setq vars
(reverse vars
))
2482 (while vars
(setq params
(cons (cons :var
(cddr (pop vars
))) params
)))
2483 ;; clear out col-names and row-names for replaced variables
2488 (when (assoc param params
)
2489 (setf (cdr (assoc param params
))
2490 (org-remove-if (lambda (pair) (equal (car pair
) name
))
2491 (cdr (assoc param params
))))
2492 (setf params
(org-remove-if (lambda (pair) (and (equal (car pair
) param
)
2495 (list :colname-names
:rowname-names
)))
2499 (let ((key (intern (concat ":" (symbol-name hd
))))
2501 (setf params
(cons (cons key
(mapconcat 'identity val
" ")) params
))))
2502 '(results exports tangle noweb padline cache shebang comments
))
2505 (defvar org-babel-use-quick-and-dirty-noweb-expansion nil
2506 "Set to true to use regular expressions to expand noweb references.
2507 This results in much faster noweb reference expansion but does
2508 not properly allow code blocks to inherit the \":noweb-ref\"
2509 header argument from buffer or subtree wide properties.")
2511 (defun org-babel-noweb-p (params context
)
2512 "Check if PARAMS require expansion in CONTEXT.
2513 CONTEXT may be one of :tangle, :export or :eval."
2515 (intersect (lambda (as bs
)
2517 (if (member (car as
) bs
)
2519 (funcall intersect
(cdr as
) bs
))))))
2520 (funcall intersect
(case context
2521 (:tangle
'("yes" "tangle" "no-export" "strip-export"))
2522 (:eval
'("yes" "no-export" "strip-export" "eval"))
2524 (split-string (or (cdr (assoc :noweb params
)) "")))))
2526 (defun org-babel-expand-noweb-references (&optional info parent-buffer
)
2527 "Expand Noweb references in the body of the current source code block.
2529 For example the following reference would be replaced with the
2530 body of the source-code block named 'example-block'.
2534 Note that any text preceding the <<foo>> construct on a line will
2535 be interposed between the lines of the replacement text. So for
2536 example if <<foo>> is placed behind a comment, then the entire
2537 replacement text will also be commented.
2539 This function must be called from inside of the buffer containing
2540 the source-code block which holds BODY.
2542 In addition the following syntax can be used to insert the
2543 results of evaluating the source-code block named 'example-block'.
2547 Any optional arguments can be passed to example-block by placing
2548 the arguments inside the parenthesis following the convention
2549 defined by `org-babel-lob'. For example
2551 <<example-block(a=9)>>
2553 would set the value of argument \"a\" equal to \"9\". Note that
2554 these arguments are not evaluated in the current source-code
2555 block but are passed literally to the \"example-block\"."
2556 (let* ((parent-buffer (or parent-buffer
(current-buffer)))
2557 (info (or info
(org-babel-get-src-block-info 'light
)))
2560 (ob-nww-start org-babel-noweb-wrap-start
)
2561 (ob-nww-end org-babel-noweb-wrap-end
)
2562 (comment (string= "noweb" (cdr (assoc :comments
(nth 2 info
)))))
2563 (rx-prefix (concat "\\(" org-babel-src-name-regexp
"\\|"
2564 ":noweb-ref[ \t]+" "\\)"))
2566 (nb-add (lambda (text) (setq new-body
(concat new-body text
))))
2567 (c-wrap (lambda (text)
2569 (funcall (intern (concat lang
"-mode")))
2570 (comment-region (point) (progn (insert text
) (point)))
2571 (org-babel-trim (buffer-string)))))
2572 index source-name evaluate prefix
)
2574 (org-set-local 'org-babel-noweb-wrap-start ob-nww-start
)
2575 (org-set-local 'org-babel-noweb-wrap-end ob-nww-end
)
2576 (insert body
) (goto-char (point-min))
2577 (setq index
(point))
2578 (while (and (re-search-forward (org-babel-noweb-wrap) nil t
))
2579 (save-match-data (setf source-name
(match-string 1)))
2580 (save-match-data (setq evaluate
(string-match "\(.*\)" source-name
)))
2583 (buffer-substring (match-beginning 0)
2585 (beginning-of-line 1) (point)))))
2586 ;; add interval to new-body (removing noweb reference)
2587 (goto-char (match-beginning 0))
2588 (funcall nb-add
(buffer-substring index
(point)))
2589 (goto-char (match-end 0))
2590 (setq index
(point))
2593 (with-current-buffer parent-buffer
2596 (mapconcat ;; Interpose PREFIX between every line.
2600 (let ((raw (org-babel-ref-resolve source-name
)))
2601 (if (stringp raw
) raw
(format "%S" raw
)))
2603 ;; Retrieve from the library of babel.
2604 (nth 2 (assoc (intern source-name
)
2605 org-babel-library-of-babel
))
2606 ;; Return the contents of headlines literally.
2608 (when (org-babel-ref-goto-headline-id source-name
)
2609 (org-babel-ref-headline-body)))
2610 ;; Find the expansion of reference in this buffer.
2611 (let ((rx (concat rx-prefix source-name
"[ \t\n]"))
2614 (goto-char (point-min))
2615 (if org-babel-use-quick-and-dirty-noweb-expansion
2616 (while (re-search-forward rx nil t
)
2617 (let* ((i (org-babel-get-src-block-info 'light
))
2618 (body (org-babel-expand-noweb-references i
))
2619 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2622 (let ((cs (org-babel-tangle-comment-links i
)))
2623 (concat (funcall c-wrap
(car cs
)) "\n"
2625 (funcall c-wrap
(cadr cs
))))
2627 (setq expansion
(cons sep
(cons full expansion
)))))
2628 (org-babel-map-src-blocks nil
2629 (let ((i (org-babel-get-src-block-info 'light
)))
2630 (when (equal (or (cdr (assoc :noweb-ref
(nth 2 i
)))
2633 (let* ((body (org-babel-expand-noweb-references i
))
2634 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2637 (let ((cs (org-babel-tangle-comment-links i
)))
2638 (concat (funcall c-wrap
(car cs
)) "\n"
2640 (funcall c-wrap
(cadr cs
))))
2643 (cons sep
(cons full expansion
)))))))))
2645 (mapconcat #'identity
(nreverse (cdr expansion
)) "")))
2646 ;; Possibly raise an error if named block doesn't exist.
2647 (if (member lang org-babel-noweb-error-langs
)
2649 (org-babel-noweb-wrap source-name
)
2650 "could not be resolved (see "
2651 "`org-babel-noweb-error-langs')"))
2653 "[\n\r]") (concat "\n" prefix
))))))
2654 (funcall nb-add
(buffer-substring index
(point-max))))
2657 (defun org-babel-script-escape (str &optional force
)
2658 "Safely convert tables into elisp lists."
2663 (or (and (string-equal "[" (substring str
0 1))
2664 (string-equal "]" (substring str -
1)))
2665 (and (string-equal "{" (substring str
0 1))
2666 (string-equal "}" (substring str -
1)))
2667 (and (string-equal "(" (substring str
0 1))
2668 (string-equal ")" (substring str -
1))))))
2672 (let (in-single in-double out
)
2678 (91 (if (or in-double in-single
) ; [
2681 (93 (if (or in-double in-single
) ; ]
2684 (123 (if (or in-double in-single
) ; {
2687 (125 (if (or in-double in-single
) ; }
2690 (44 (if (or in-double in-single
) ; ,
2691 (cons 44 out
) (cons 32 out
)))
2692 (39 (if in-double
; '
2694 (setq in-single
(not in-single
)) (cons 34 out
)))
2695 (34 (if in-single
; "
2696 (append (list 34 32) out
)
2697 (setq in-double
(not in-double
)) (cons 34 out
)))
2698 (t (cons ch out
)))))
2699 (string-to-list str
))
2700 (apply #'string
(reverse out
)))))
2702 (condition-case nil
(org-babel-read escaped
) (error escaped
))))
2704 (defun org-babel-read (cell &optional inhibit-lisp-eval
)
2705 "Convert the string value of CELL to a number if appropriate.
2706 Otherwise if cell looks like lisp (meaning it starts with a
2707 \"(\", \"'\", \"`\" or a \"[\") then read it as lisp,
2708 otherwise return it unmodified as a string. Optional argument
2709 NO-LISP-EVAL inhibits lisp evaluation for situations in which is
2710 it not appropriate."
2711 (if (and (stringp cell
) (not (equal cell
"")))
2712 (or (org-babel-number-p cell
)
2713 (if (and (not inhibit-lisp-eval
)
2714 (or (member (substring cell
0 1) '("(" "'" "`" "["))
2715 (string= cell
"*this*")))
2717 (if (string= (substring cell
0 1) "\"")
2719 (progn (set-text-properties 0 (length cell
) nil cell
) cell
))))
2722 (defun org-babel-number-p (string)
2723 "If STRING represents a number return its value."
2724 (if (and (string-match "[0-9]+" string
)
2725 (string-match "^-?[0-9]*\\.?[0-9]*$" string
)
2726 (= (length (substring string
(match-beginning 0)
2729 (string-to-number string
)))
2731 (defun org-babel-import-elisp-from-file (file-name &optional separator
)
2732 "Read the results located at FILE-NAME into an elisp table.
2733 If the table is trivial, then return it as a scalar."
2735 (save-window-excursion
2739 (org-table-import file-name separator
)
2740 (delete-file file-name
)
2741 (setq result
(mapcar (lambda (row)
2742 (mapcar #'org-babel-string-read row
))
2743 (org-table-to-lisp))))
2744 (error (message "Error reading results: %s" err
) nil
)))
2745 (if (null (cdr result
)) ;; if result is trivial vector, then scalarize it
2746 (if (consp (car result
))
2747 (if (null (cdr (car result
)))
2753 (defun org-babel-string-read (cell)
2754 "Strip nested \"s from around strings."
2755 (org-babel-read (or (and (stringp cell
)
2756 (string-match "\\\"\\(.+\\)\\\"" cell
)
2757 (match-string 1 cell
))
2760 (defun org-babel-chomp (string &optional regexp
)
2761 "Strip a trailing space or carriage return from STRING.
2762 The default regexp used is \"[ \\f\\t\\n\\r\\v]\" but another one
2763 can be specified as the REGEXP argument."
2764 (let ((regexp (or regexp
"[ \f\t\n\r\v]")))
2765 (while (and (> (length string
) 0)
2766 (string-match regexp
(substring string -
1)))
2767 (setq string
(substring string
0 -
1)))
2770 (defun org-babel-trim (string &optional regexp
)
2771 "Strip a leading and trailing space or carriage return from STRING.
2772 Like `org-babel-chomp', but run on both the first and last
2773 character of the string."
2776 (org-babel-chomp (org-reverse-string string
) regexp
)) regexp
))
2778 (defun org-babel-tramp-handle-call-process-region
2779 (start end program
&optional delete buffer display
&rest args
)
2780 "Use Tramp to handle `call-process-region'.
2781 Fixes a bug in `tramp-handle-call-process-region'."
2782 (if (and (featurep 'tramp
) (file-remote-p default-directory
))
2783 (let ((tmpfile (tramp-compat-make-temp-file "")))
2784 (write-region start end tmpfile
)
2785 (when delete
(delete-region start end
))
2787 ;; (apply 'call-process program tmpfile buffer display args)
2789 (apply 'process-file program tmpfile buffer display args
)
2790 (delete-file tmpfile
)))
2791 ;; org-babel-call-process-region-original is the original emacs
2792 ;; definition. It is in scope from the let binding in
2793 ;; org-babel-execute-src-block
2794 (apply org-babel-call-process-region-original
2795 start end program delete buffer display args
)))
2797 (defun org-babel-local-file-name (file)
2798 "Return the local name component of FILE."
2799 (or (file-remote-p file
'localname
) file
))
2801 (defun org-babel-process-file-name (name &optional no-quote-p
)
2802 "Prepare NAME to be used in an external process.
2803 If NAME specifies a remote location, the remote portion of the
2804 name is removed, since in that case the process will be executing
2805 remotely. The file name is then processed by `expand-file-name'.
2806 Unless second argument NO-QUOTE-P is non-nil, the file name is
2807 additionally processed by `shell-quote-argument'"
2808 (let ((f (org-babel-local-file-name (expand-file-name name
))))
2809 (if no-quote-p f
(shell-quote-argument f
))))
2811 (defvar org-babel-temporary-directory
)
2812 (unless (or noninteractive
(boundp 'org-babel-temporary-directory
))
2813 (defvar org-babel-temporary-directory
2814 (or (and (boundp 'org-babel-temporary-directory
)
2815 (file-exists-p org-babel-temporary-directory
)
2816 org-babel-temporary-directory
)
2817 (make-temp-file "babel-" t
))
2818 "Directory to hold temporary files created to execute code blocks.
2819 Used by `org-babel-temp-file'. This directory will be removed on
2822 (defcustom org-babel-remote-temporary-directory
"/tmp/"
2823 "Directory to hold temporary files on remote hosts."
2827 (defmacro org-babel-result-cond
(result-params scalar-form
&rest table-forms
)
2828 "Call the code to parse raw string results according to RESULT-PARAMS."
2830 (debug (form form
&rest form
)))
2831 (org-with-gensyms (params)
2832 `(let ((,params
,result-params
))
2833 (unless (member "none" ,params
)
2834 (if (or (member "scalar" ,params
)
2835 (member "verbatim" ,params
)
2836 (member "html" ,params
)
2837 (member "code" ,params
)
2838 (member "pp" ,params
)
2839 (and (or (member "output" ,params
)
2840 (member "raw" ,params
)
2841 (member "org" ,params
)
2842 (member "drawer" ,params
))
2843 (not (member "table" ,params
))))
2846 (def-edebug-spec org-babel-result-cond
(form form body
))
2848 (defun org-babel-temp-file (prefix &optional suffix
)
2849 "Create a temporary file in the `org-babel-temporary-directory'.
2850 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2851 value of `temporary-file-directory' temporarily set to the value
2852 of `org-babel-temporary-directory'."
2853 (if (file-remote-p default-directory
)
2855 (concat (file-remote-p default-directory
)
2857 prefix org-babel-remote-temporary-directory
))))
2858 (make-temp-file prefix nil suffix
))
2859 (let ((temporary-file-directory
2860 (or (and (boundp 'org-babel-temporary-directory
)
2861 (file-exists-p org-babel-temporary-directory
)
2862 org-babel-temporary-directory
)
2863 temporary-file-directory
)))
2864 (make-temp-file prefix nil suffix
))))
2866 (defun org-babel-remove-temporary-directory ()
2867 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2868 (when (and (boundp 'org-babel-temporary-directory
)
2869 (file-exists-p org-babel-temporary-directory
))
2870 ;; taken from `delete-directory' in files.el
2873 (mapc (lambda (file)
2874 ;; This test is equivalent to
2875 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2876 ;; but more efficient
2877 (if (eq t
(car (file-attributes file
)))
2878 (delete-directory file
)
2879 (delete-file file
)))
2880 ;; We do not want to delete "." and "..".
2881 (directory-files org-babel-temporary-directory
'full
2882 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2883 (delete-directory org-babel-temporary-directory
))
2885 (message "Failed to remove temporary Org-babel directory %s"
2886 (if (boundp 'org-babel-temporary-directory
)
2887 org-babel-temporary-directory
2888 "[directory not defined]"))))))
2890 (add-hook 'kill-emacs-hook
'org-babel-remove-temporary-directory
)
2892 (defun org-babel-one-header-arg-safe-p (pair safe-list
)
2893 "Determine if the PAIR is a safe babel header arg according to SAFE-LIST.
2895 For the format of SAFE-LIST, see `org-babel-safe-header-args'."
2897 (keywordp (car pair
))
2898 (stringp (cdr pair
))
2900 (memq (car pair
) safe-list
)
2901 (let ((entry (assq (car pair
) safe-list
)))
2904 (cond ((functionp (cdr entry
))
2905 (funcall (cdr entry
) (cdr pair
)))
2906 ((listp (cdr entry
))
2907 (member (cdr pair
) (cdr entry
)))
2910 (defun org-babel-generate-file-param (src-name params
)
2911 "Calculate the filename for source block results.
2913 The directory is calculated from the :output-dir property of the
2914 source block; if not specified, use the current directory.
2916 If the source block has a #+NAME and the :file parameter does not
2917 contain any period characters, then the :file parameter is
2918 treated as an extension, and the output file name is the
2919 concatenation of the directory (as calculated above), the block
2920 name, a period, and the parameter value as a file extension.
2921 Otherwise, the :file parameter is treated as a full file name,
2922 and the output file name is the directory (as calculated above)
2923 plus the parameter value."
2924 (let* ((file-cons (assq :file params
))
2925 (file-ext-cons (assq :file-ext params
))
2926 (file-ext (cdr-safe file-ext-cons
))
2927 (dir (cdr-safe (assq :output-dir params
)))
2929 ;; create the output-dir if it does not exist
2931 (make-directory dir t
))
2933 ;; :file given; add :output-dir if given
2935 (setcdr file-cons
(concat (file-name-as-directory dir
) (cdr file-cons
))))
2936 ;; :file not given; compute from name and :file-ext if possible
2937 (when (and src-name file-ext
)
2939 (setq fname
(concat (file-name-as-directory (or dir
""))
2940 src-name
"." file-ext
))
2941 (setq fname
(concat src-name
"." file-ext
)))
2942 (setq params
(cons (cons :file fname
) params
))))
2945 ;;; Used by backends: R, Maxima, Octave.
2946 (defun org-babel-graphical-output-file (params)
2947 "File where a babel block should send graphical output, per PARAMS."
2948 (unless (assq :file params
)
2949 (if (assq :file-ext params
)
2950 (user-error ":file-ext given but no :file generated; did you forget to give a block a #+NAME?")
2951 (user-error "No :file header argument given; cannot create graphical result.")))
2952 (and (member "graphics" (cdr (assq :result-params params
)))
2953 (cdr (assq :file params
))))
2958 ;; generated-autoload-file: "org-loaddefs.el"
2961 ;;; ob-core.el ends here