1 ;;; ob-core.el --- working with code blocks in org-mode
3 ;; Copyright (C) 2009-2013 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-reduce
"org" (CL-FUNC CL-SEQ
&rest CL-KEYS
))
42 (declare-function org-mark-ring-push
"org" (&optional pos buffer
))
43 (declare-function tramp-compat-make-temp-file
"tramp-compat"
44 (filename &optional dir-flag
))
45 (declare-function tramp-dissect-file-name
"tramp" (name &optional nodefault
))
46 (declare-function tramp-file-name-user
"tramp" (vec))
47 (declare-function tramp-file-name-host
"tramp" (vec))
48 (declare-function with-parsed-tramp-file-name
"tramp" (filename var
&rest body
))
49 (declare-function org-icompleting-read
"org" (&rest args
))
50 (declare-function org-edit-src-code
"org-src"
51 (&optional context code edit-buffer-name quietp
))
52 (declare-function org-edit-src-exit
"org-src" (&optional context
))
53 (declare-function org-open-at-point
"org" (&optional in-emacs reference-buffer
))
54 (declare-function org-save-outline-visibility
"org-macs" (use-markers &rest body
))
55 (declare-function org-outline-overlay-data
"org" (&optional use-markers
))
56 (declare-function org-set-outline-overlay-data
"org" (data))
57 (declare-function org-narrow-to-subtree
"org" ())
58 (declare-function org-split-string
"org" (string &optional separators
))
59 (declare-function org-entry-get
"org"
60 (pom property
&optional inherit literal-nil
))
61 (declare-function org-make-options-regexp
"org" (kwds &optional extra
))
62 (declare-function org-do-remove-indentation
"org" (&optional n
))
63 (declare-function org-next-block
"org" (arg &optional backward block-regexp
))
64 (declare-function org-previous-block
"org" (arg &optional block-regexp
))
65 (declare-function org-show-context
"org" (&optional key
))
66 (declare-function org-at-table-p
"org" (&optional table-type
))
67 (declare-function org-cycle
"org" (&optional arg
))
68 (declare-function org-uniquify
"org" (list))
69 (declare-function org-current-level
"org" ())
70 (declare-function org-table-import
"org-table" (file arg
))
71 (declare-function org-add-hook
"org-compat"
72 (hook function
&optional append local
))
73 (declare-function org-table-align
"org-table" ())
74 (declare-function org-table-end
"org-table" (&optional table-type
))
75 (declare-function orgtbl-to-generic
"org-table" (table params
))
76 (declare-function orgtbl-to-orgtbl
"org-table" (table params
))
77 (declare-function org-babel-tangle-comment-links
"ob-tangle" (&optional info
))
78 (declare-function org-babel-lob-get-info
"ob-lob" nil
)
79 (declare-function org-babel-ref-split-args
"ob-ref" (arg-string))
80 (declare-function org-babel-ref-parse
"ob-ref" (assignment))
81 (declare-function org-babel-ref-resolve
"ob-ref" (ref))
82 (declare-function org-babel-ref-goto-headline-id
"ob-ref" (id))
83 (declare-function org-babel-ref-headline-body
"ob-ref" ())
84 (declare-function org-babel-lob-execute-maybe
"ob-lob" ())
85 (declare-function org-number-sequence
"org-compat" (from &optional to inc
))
86 (declare-function org-at-item-p
"org-list" ())
87 (declare-function org-list-parse-list
"org-list" (&optional delete
))
88 (declare-function org-list-to-generic
"org-list" (LIST PARAMS
))
89 (declare-function org-list-struct
"org-list" ())
90 (declare-function org-list-prevs-alist
"org-list" (struct))
91 (declare-function org-list-get-list-end
"org-list" (item struct prevs
))
92 (declare-function org-remove-if
"org" (predicate seq
))
93 (declare-function org-completing-read
"org" (&rest args
))
94 (declare-function org-escape-code-in-region
"org-src" (beg end
))
95 (declare-function org-unescape-code-in-string
"org-src" (s))
96 (declare-function org-table-to-lisp
"org-table" (&optional txt
))
97 (declare-function org-reverse-string
"org" (string))
98 (declare-function org-element-context
"org-element" (&optional ELEMENT
))
99 (declare-function org-every
"org" (pred seq
))
101 (defgroup org-babel nil
102 "Code block evaluation and management in `org-mode' documents."
106 (defcustom org-confirm-babel-evaluate t
107 "Confirm before evaluation.
108 Require confirmation before interactively evaluating code
109 blocks in Org-mode buffers. The default value of this variable
110 is t, meaning confirmation is required for any code block
111 evaluation. This variable can be set to nil to inhibit any
112 future confirmation requests. This variable can also be set to a
113 function which takes two arguments the language of the code block
114 and the body of the code block. Such a function should then
115 return a non-nil value if the user should be prompted for
116 execution or nil if no prompt is required.
118 Warning: Disabling confirmation may result in accidental
119 evaluation of potentially harmful code. It may be advisable
120 remove code block execution from C-c C-c as further protection
121 against accidental code block evaluation. The
122 `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
123 remove code block execution from the C-c C-c keybinding."
126 :type
'(choice boolean function
))
127 ;; don't allow this variable to be changed through file settings
128 (put 'org-confirm-babel-evaluate
'safe-local-variable
(lambda (x) (eq x t
)))
130 (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
131 "Remove code block evaluation from the C-c C-c key binding."
136 (defcustom org-babel-results-keyword
"RESULTS"
137 "Keyword used to name results generated by code blocks.
138 Should be either RESULTS or NAME however any capitalization may
142 :package-version
'(Org .
"8.0")
145 (defcustom org-babel-noweb-wrap-start
"<<"
146 "String used to begin a noweb reference in a code block.
147 See also `org-babel-noweb-wrap-end'."
151 (defcustom org-babel-noweb-wrap-end
">>"
152 "String used to end a noweb reference in a code block.
153 See also `org-babel-noweb-wrap-start'."
157 (defcustom org-babel-inline-result-wrap
"=%s="
158 "Format string used to wrap inline results.
159 This string must include a \"%s\" which will be replaced by the results."
162 (put 'org-babel-inline-result-wrap
166 (string-match-p "%s" value
))))
168 (defun org-babel-noweb-wrap (&optional regexp
)
169 (concat org-babel-noweb-wrap-start
170 (or regexp
"\\([^ \t\n].+?[^ \t]\\|[^ \t\n]\\)")
171 org-babel-noweb-wrap-end
))
173 (defvar org-babel-src-name-regexp
174 "^[ \t]*#\\+name:[ \t]*"
175 "Regular expression used to match a source name line.")
177 (defvar org-babel-multi-line-header-regexp
178 "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
179 "Regular expression used to match multi-line header arguments.")
181 (defvar org-babel-src-name-w-name-regexp
182 (concat org-babel-src-name-regexp
184 org-babel-multi-line-header-regexp
186 "\\([^ ()\f\t\n\r\v]+\\)")
187 "Regular expression matching source name lines with a name.")
189 (defvar org-babel-src-block-regexp
191 ;; (1) indentation (2) lang
192 "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
194 "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
195 ;; (4) header arguments
198 "\\([^\000]*?\n\\)??[ \t]*#\\+end_src")
199 "Regexp used to identify code blocks.")
201 (defvar org-babel-inline-src-block-regexp
203 ;; (1) replacement target (2) lang
204 "\\(?:^\\|[^-[:alnum:]]\\)\\(src_\\([^ \f\t\n\r\v]+\\)"
205 ;; (3,4) (unused, headers)
206 "\\(\\|\\[\\(.*?\\)\\]\\)"
208 "{\\([^\f\n\r\v]+?\\)}\\)")
209 "Regexp used to identify inline src-blocks.")
211 (defun org-babel-get-header (params key
&optional others
)
212 "Select only header argument of type KEY from a list.
213 Optional argument OTHERS indicates that only the header that do
214 not match KEY should be returned."
217 (lambda (p) (when (funcall (if others
#'not
#'identity
) (eq (car p
) key
)) p
))
220 (defun org-babel-get-inline-src-block-matches ()
221 "Set match data if within body of an inline source block.
222 Returns non-nil if match-data set"
223 (let ((src-at-0-p (save-excursion
224 (beginning-of-line 1)
225 (string= "src" (thing-at-point 'word
))))
226 (first-line-p (= 1 (line-number-at-pos)))
228 (let ((search-for (cond ((and src-at-0-p first-line-p
"src_"))
229 (first-line-p "[[:punct:] \t]src_")
230 (t "[[:punct:] \f\t\n\r\v]src_")))
231 (lower-limit (if first-line-p
233 (- (point-at-bol) 1))))
235 (when (or (and src-at-0-p
(bobp))
236 (and (re-search-forward "}" (point-at-eol) t
)
237 (re-search-backward search-for lower-limit t
)
239 (when (looking-at org-babel-inline-src-block-regexp
)
242 (defvar org-babel-inline-lob-one-liner-regexp
)
243 (defun org-babel-get-lob-one-liner-matches ()
244 "Set match data if on line of an lob one liner.
245 Returns non-nil if match-data set"
247 (unless (= (point) (point-at-bol)) ;; move before inline block
248 (re-search-backward "[ \f\t\n\r\v]" nil t
))
249 (if (looking-at org-babel-inline-lob-one-liner-regexp
)
253 (defun org-babel-get-src-block-info (&optional light
)
254 "Get information on the current source block.
256 Optional argument LIGHT does not resolve remote variable
257 references; a process which could likely result in the execution
258 of other code blocks.
261 (language body header-arguments-alist switches name indent block-head)."
262 (let ((case-fold-search t
) head info name indent
)
264 (if (setq head
(org-babel-where-is-src-block-head))
267 (setq info
(org-babel-parse-src-block-match))
268 (setq indent
(car (last info
)))
269 (setq info
(butlast info
))
270 (while (and (forward-line -
1)
271 (looking-at org-babel-multi-line-header-regexp
))
273 (org-babel-merge-params
275 (org-babel-parse-header-arguments (match-string 1)))))
276 (when (looking-at org-babel-src-name-w-name-regexp
)
277 (setq name
(org-no-properties (match-string 3)))))
278 ;; inline source block
279 (when (org-babel-get-inline-src-block-matches)
280 (setq head
(match-beginning 0))
281 (setq info
(org-babel-parse-inline-src-block-match))))
282 ;; resolve variable references and add summary parameters
283 (when (and info
(not light
))
284 (setf (nth 2 info
) (org-babel-process-params (nth 2 info
))))
285 (when info
(append info
(list name indent head
)))))
287 (defvar org-current-export-file
) ; dynamically bound
288 (defmacro org-babel-check-confirm-evaluate
(info &rest body
)
289 "Evaluate BODY with special execution confirmation variables set.
291 Specifically; NOEVAL will indicate if evaluation is allowed,
292 QUERY will indicate if a user query is required, CODE-BLOCK will
293 hold the language of the code block, and BLOCK-NAME will hold the
294 name of the code block."
295 (declare (indent defun
))
297 (lang block-body headers name head eval eval-no export eval-no-export
)
298 `(let* ((,lang
(nth 0 ,info
))
299 (,block-body
(nth 1 ,info
))
300 (,headers
(nth 2 ,info
))
301 (,name
(nth 4 ,info
))
302 (,head
(nth 6 ,info
))
303 (,eval
(or (cdr (assoc :eval
,headers
))
304 (when (assoc :noeval
,headers
) "no")))
305 (,eval-no
(or (equal ,eval
"no")
306 (equal ,eval
"never")))
307 (,export
(org-bound-and-true-p org-current-export-file
))
308 (,eval-no-export
(and ,export
(or (equal ,eval
"no-export")
309 (equal ,eval
"never-export"))))
310 (noeval (or ,eval-no
,eval-no-export
))
311 (query (or (equal ,eval
"query")
312 (and ,export
(equal ,eval
"query-export"))
313 (if (functionp org-confirm-babel-evaluate
)
316 (funcall org-confirm-babel-evaluate
318 org-confirm-babel-evaluate
)))
319 (code-block (if ,info
(format " %s " ,lang
) " "))
320 (block-name (if ,name
(format " (%s) " ,name
) " ")))
323 (defsubst org-babel-check-evaluate
(info)
324 "Check if code block INFO should be evaluated.
325 Do not query the user."
326 (org-babel-check-confirm-evaluate info
328 (message (format "Evaluation of this%scode-block%sis disabled."
329 code-block block-name
))))))
331 ;; dynamically scoped for asynchronous export
332 (defvar org-babel-confirm-evaluate-answer-no
)
334 (defsubst org-babel-confirm-evaluate
(info)
335 "Confirm evaluation of the code block INFO.
337 If the variable `org-babel-confirm-evaluate-answer-no' is bound
338 to a non-nil value, auto-answer with \"no\".
340 This query can also be suppressed by setting the value of
341 `org-confirm-babel-evaluate' to nil, in which case all future
342 interactive code block evaluations will proceed without any
343 confirmation from the user.
345 Note disabling confirmation may result in accidental evaluation
346 of potentially harmful code."
347 (org-babel-check-confirm-evaluate info
350 (and (not (org-bound-and-true-p
351 org-babel-confirm-evaluate-answer-no
))
353 (format "Evaluate this%scode block%son your system? "
354 code-block block-name
)))
355 (message (format "Evaluation of this%scode-block%sis aborted."
356 code-block block-name
)))))))
359 (defun org-babel-execute-safely-maybe ()
360 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
361 (org-babel-execute-maybe)))
363 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-execute-safely-maybe
)
366 (defun org-babel-execute-maybe ()
368 (or (org-babel-execute-src-block-maybe)
369 (org-babel-lob-execute-maybe)))
371 (defmacro org-babel-when-in-src-block
(&rest body
)
372 "Execute BODY if point is in a source block and return t.
374 Otherwise do nothing and return nil."
375 `(if (or (org-babel-where-is-src-block-head)
376 (org-babel-get-inline-src-block-matches))
382 (defun org-babel-execute-src-block-maybe ()
383 "Conditionally execute a source block.
384 Detect if this is context for a Babel src-block and if so
385 then run `org-babel-execute-src-block'."
387 (org-babel-when-in-src-block
388 (org-babel-eval-wipe-error-buffer)
389 (org-babel-execute-src-block current-prefix-arg
)))
392 (defun org-babel-view-src-block-info ()
393 "Display information on the current source block.
394 This includes header arguments, language and name, and is largely
395 a window into the `org-babel-get-src-block-info' function."
397 (let ((info (org-babel-get-src-block-info 'light
))
398 (full (lambda (it) (> (length it
) 0)))
399 (printf (lambda (fmt &rest args
) (princ (apply #'format fmt args
)))))
401 (with-help-window (help-buffer)
402 (let ((name (nth 4 info
))
404 (switches (nth 3 info
))
405 (header-args (nth 2 info
)))
406 (when name
(funcall printf
"Name: %s\n" name
))
407 (when lang
(funcall printf
"Lang: %s\n" lang
))
408 (when (funcall full switches
) (funcall printf
"Switches: %s\n" switches
))
409 (funcall printf
"Header Arguments:\n")
410 (dolist (pair (sort header-args
411 (lambda (a b
) (string< (symbol-name (car a
))
412 (symbol-name (car b
))))))
413 (when (funcall full
(cdr pair
))
414 (funcall printf
"\t%S%s\t%s\n"
416 (if (> (length (format "%S" (car pair
))) 7) "" "\t")
420 (defun org-babel-expand-src-block-maybe ()
421 "Conditionally expand a source block.
422 Detect if this is context for a org-babel src-block and if so
423 then run `org-babel-expand-src-block'."
425 (org-babel-when-in-src-block
426 (org-babel-expand-src-block current-prefix-arg
)))
429 (defun org-babel-load-in-session-maybe ()
430 "Conditionally load a source block in a session.
431 Detect if this is context for a org-babel src-block and if so
432 then run `org-babel-load-in-session'."
434 (org-babel-when-in-src-block
435 (org-babel-load-in-session current-prefix-arg
)))
437 (add-hook 'org-metaup-hook
'org-babel-load-in-session-maybe
)
440 (defun org-babel-pop-to-session-maybe ()
441 "Conditionally pop to a session.
442 Detect if this is context for a org-babel src-block and if so
443 then run `org-babel-switch-to-session'."
445 (org-babel-when-in-src-block
446 (org-babel-switch-to-session current-prefix-arg
)))
448 (add-hook 'org-metadown-hook
'org-babel-pop-to-session-maybe
)
450 (defconst org-babel-common-header-args-w-values
451 '((cache .
((no yes
)))
453 (colnames .
((nil no yes
)))
454 (comments .
((no link yes org both noweb
)))
456 (eval .
((never query
)))
457 (exports .
((code results both none
)))
461 (hlines .
((no yes
)))
462 (mkdirp .
((yes no
)))
465 (noweb .
((yes no tangle no-export strip-export
)))
468 (padline .
((yes no
)))
471 (results .
((file list vector table scalar verbatim
)
472 (raw html latex org code pp drawer
)
473 (replace silent none append prepend
)
475 (rownames .
((no yes
)))
479 (tangle .
((tangle yes no
:any
)))
480 (tangle-mode .
((#o755
#o555
#o444
:any
)))
484 (defconst org-babel-header-arg-names
485 (mapcar #'car org-babel-common-header-args-w-values
)
486 "Common header arguments used by org-babel.
487 Note that individual languages may define their own language
488 specific header arguments as well.")
490 (defconst org-babel-safe-header-args
491 '(:cache
:colnames
:comments
:exports
:epilogue
:hlines
:noeval
492 :noweb
:noweb-ref
:noweb-sep
:padline
:prologue
:rownames
493 :sep
:session
:tangle
:wrap
494 (:eval .
("never" "query"))
495 (:results .
(lambda (str) (not (string-match "file" str
)))))
496 "A list of safe header arguments for babel source blocks.
498 The list can have entries of the following forms:
499 - :ARG -> :ARG is always a safe header arg
500 - (:ARG . (VAL1 VAL2 ...)) -> :ARG is safe as a header arg if it is
501 `equal' to one of the VALs.
502 - (:ARG . FN) -> :ARG is safe as a header arg if the function FN
503 returns non-nil. FN is passed one
504 argument, the value of the header arg
507 (defmacro org-babel-header-args-safe-fn
(safe-list)
508 "Return a function that determines whether a list of header args are safe.
511 \(put 'org-babel-default-header-args 'safe-local-variable
512 (org-babel-header-args-safe-p org-babel-safe-header-args)
514 This allows org-babel languages to extend the list of safe values for
515 their `org-babel-default-header-args:foo' variable.
517 For the format of SAFE-LIST, see `org-babel-safe-header-args'."
523 (org-babel-one-header-arg-safe-p pair
,safe-list
)))
526 (defvar org-babel-default-header-args
527 '((:session .
"none") (:results .
"replace") (:exports .
"code")
528 (:cache .
"no") (:noweb .
"no") (:hlines .
"no") (:tangle .
"no"))
529 "Default arguments to use when evaluating a source block.")
530 (put 'org-babel-default-header-args
'safe-local-variable
531 (org-babel-header-args-safe-fn org-babel-safe-header-args
))
533 (defvar org-babel-default-inline-header-args
534 '((:session .
"none") (:results .
"replace")
535 (:exports .
"results") (:hlines .
"yes"))
536 "Default arguments to use when evaluating an inline source block.")
537 (put 'org-babel-default-inline-header-args
'safe-local-variable
538 (org-babel-header-args-safe-fn org-babel-safe-header-args
))
540 (defvar org-babel-data-names
'("tblname" "results" "name"))
542 (defvar org-babel-result-regexp
543 (concat "^[ \t]*#\\+"
544 (regexp-opt org-babel-data-names t
)
546 ;; FIXME The string below is `org-ts-regexp'
547 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
548 " \\)?\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*")
549 "Regular expression used to match result lines.
550 If the results are associated with a hash key then the hash will
551 be saved in the second match data.")
553 (defvar org-babel-result-w-name-regexp
554 (concat org-babel-result-regexp
555 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
557 (defvar org-babel-min-lines-for-block-output
10
558 "The minimum number of lines for block output.
559 If number of lines of output is equal to or exceeds this
560 value, the output is placed in a #+begin_example...#+end_example
561 block. Otherwise the output is marked as literal by inserting
562 colons at the starts of the lines. This variable only takes
563 effect if the :results output option is in effect.")
565 (defvar org-babel-noweb-error-langs nil
566 "Languages for which Babel will raise literate programming errors.
567 List of languages for which errors should be raised when the
568 source code block satisfying a noweb reference in this language
569 can not be resolved.")
571 (defvar org-babel-hash-show
4
572 "Number of initial characters to show of a hidden results hash.")
574 (defvar org-babel-hash-show-time nil
575 "Non-nil means show the time the code block was evaluated in the result hash.")
577 (defvar org-babel-after-execute-hook nil
578 "Hook for functions to be called after `org-babel-execute-src-block'")
580 (defun org-babel-named-src-block-regexp-for-name (name)
581 "This generates a regexp used to match a src block named NAME."
582 (concat org-babel-src-name-regexp
(regexp-quote name
)
583 "[ \t(]*[\r\n]\\(?:^#.*[\r\n]\\)*"
584 (substring org-babel-src-block-regexp
1)))
586 (defun org-babel-named-data-regexp-for-name (name)
587 "This generates a regexp used to match data named NAME."
588 (concat org-babel-result-regexp
(regexp-quote name
) "\\([ \t]\\|$\\)"))
591 (defvar call-process-region
)
592 (defvar org-babel-current-src-block-location nil
593 "Marker pointing to the src block currently being executed.
594 This may also point to a call line or an inline code block. If
595 multiple blocks are being executed (e.g., in chained execution
596 through use of the :var header argument) this marker points to
597 the outer-most code block.")
600 (defun org-babel-execute-src-block (&optional arg info params
)
601 "Execute the current source code block.
602 Insert the results of execution into the buffer. Source code
603 execution and the collection and formatting of results can be
604 controlled through a variety of header arguments.
606 With prefix argument ARG, force re-execution even if an existing
607 result cached in the buffer would otherwise have been returned.
609 Optionally supply a value for INFO in the form returned by
610 `org-babel-get-src-block-info'.
612 Optionally supply a value for PARAMS which will be merged with
613 the header arguments specified at the front of the source code
616 (let* ((org-babel-current-src-block-location
617 (or org-babel-current-src-block-location
619 (org-babel-where-is-src-block-head)
621 (and (org-babel-get-inline-src-block-matches)
622 (match-beginning 0))))
625 (org-babel-get-src-block-info)))
626 (merged-params (org-babel-merge-params (nth 2 info
) params
)))
627 (when (org-babel-check-evaluate
628 (let ((i info
)) (setf (nth 2 i
) merged-params
) i
))
629 (let* ((params (if params
630 (org-babel-process-params merged-params
)
632 (cachep (and (not arg
) (cdr (assoc :cache params
))
633 (string= "yes" (cdr (assoc :cache params
)))))
634 (new-hash (when cachep
(org-babel-sha1-hash info
)))
635 (old-hash (when cachep
(org-babel-current-result-hash)))
636 (cache-current-p (and (not arg
) new-hash
637 (equal new-hash old-hash
))))
640 (save-excursion ;; return cached result
641 (goto-char (org-babel-where-is-src-block-result nil info
))
642 (end-of-line 1) (forward-char 1)
643 (let ((result (org-babel-read-result)))
644 (message (replace-regexp-in-string
645 "%" "%%" (format "%S" result
))) result
)))
646 ((org-babel-confirm-evaluate
647 (let ((i info
)) (setf (nth 2 i
) merged-params
) i
))
648 (let* ((lang (nth 0 info
))
649 (result-params (cdr (assoc :result-params params
)))
650 (body (setf (nth 1 info
)
651 (if (org-babel-noweb-p params
:eval
)
652 (org-babel-expand-noweb-references info
)
654 (dir (cdr (assoc :dir params
)))
656 (or (and dir
(file-name-as-directory (expand-file-name dir
)))
658 (org-babel-call-process-region-original ;; for tramp handler
659 (or (org-bound-and-true-p
660 org-babel-call-process-region-original
)
661 (symbol-function 'call-process-region
)))
662 (indent (nth 5 info
))
665 (let ((call-process-region
667 (apply 'org-babel-tramp-handle-call-process-region
671 (let ((f (intern (concat "org-babel-execute:" f
))))
672 (when (fboundp f
) f
)))))
674 (or (funcall lang-check lang
)
677 (cdr (assoc lang org-src-lang-modes
))))
678 (error "No org-babel-execute function for %s!"
680 (message "executing %s code block%s..."
682 (if (nth 4 info
) (format " (%s)" (nth 4 info
)) ""))
683 (if (member "none" result-params
)
685 (funcall cmd body params
)
686 (message "result silenced")
689 (let ((result (funcall cmd body params
)))
690 (if (and (eq (cdr (assoc :result-type params
))
692 (or (member "vector" result-params
)
693 (member "table" result-params
))
694 (not (listp result
)))
695 (list (list result
)) result
)))
696 ;; If non-empty result and :file then write to :file.
697 (when (cdr (assoc :file params
))
699 (with-temp-file (cdr (assoc :file params
))
701 (org-babel-format-result
702 result
(cdr (assoc :sep
(nth 2 info
)))))))
703 (setq result
(cdr (assoc :file params
))))
704 ;; Possibly perform post process provided its appropriate.
705 (when (cdr (assoc :post params
))
706 (let ((*this
* (if (cdr (assoc :file params
))
707 (org-babel-result-to-file
708 (cdr (assoc :file params
))
709 (when (assoc :file-desc params
)
710 (or (cdr (assoc :file-desc params
))
713 (setq result
(org-babel-ref-resolve
714 (cdr (assoc :post params
))))
715 (when (cdr (assoc :file params
))
717 (remove "file" result-params
)))))
718 (org-babel-insert-result
719 result result-params info new-hash indent lang
))
720 (run-hooks 'org-babel-after-execute-hook
)
722 (setq call-process-region
723 'org-babel-call-process-region-original
)))))))))
725 (defun org-babel-expand-body:generic
(body params
&optional var-lines
)
726 "Expand BODY with PARAMS.
727 Expand a block of code with org-babel according to its header
728 arguments. This generic implementation of body expansion is
729 called for languages which have not defined their own specific
730 org-babel-expand-body:lang function."
731 (let ((pro (cdr (assoc :prologue params
)))
732 (epi (cdr (assoc :epilogue params
))))
733 (mapconcat #'identity
734 (append (when pro
(list pro
))
737 (when epi
(list epi
)))
741 (defun org-babel-expand-src-block (&optional arg info params
)
742 "Expand the current source code block.
743 Expand according to the source code block's header
744 arguments and pop open the results in a preview buffer."
746 (let* ((info (or info
(org-babel-get-src-block-info)))
748 (params (setf (nth 2 info
)
749 (sort (org-babel-merge-params (nth 2 info
) params
)
750 (lambda (el1 el2
) (string< (symbol-name (car el1
))
751 (symbol-name (car el2
)))))))
752 (body (setf (nth 1 info
)
753 (if (org-babel-noweb-p params
:eval
)
754 (org-babel-expand-noweb-references info
) (nth 1 info
))))
755 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
756 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
759 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
760 (org-babel-expand-body:generic
761 body params
(and (fboundp assignments-cmd
)
762 (funcall assignments-cmd params
))))))
763 (if (org-called-interactively-p 'any
)
766 (concat "*Org-Babel Preview " (buffer-name) "[ " lang
" ]*"))
769 (defun org-babel-edit-distance (s1 s2
)
770 "Return the edit (levenshtein) distance between strings S1 S2."
771 (let* ((l1 (length s1
))
773 (dist (vconcat (mapcar (lambda (_) (make-vector (1+ l2
) nil
))
774 (number-sequence 1 (1+ l1
)))))
775 (in (lambda (i j
) (aref (aref dist i
) j
))))
776 (setf (aref (aref dist
0) 0) 0)
777 (dolist (j (number-sequence 1 l2
))
778 (setf (aref (aref dist
0) j
) j
))
779 (dolist (i (number-sequence 1 l1
))
780 (setf (aref (aref dist i
) 0) i
)
781 (dolist (j (number-sequence 1 l2
))
782 (setf (aref (aref dist i
) j
)
784 (1+ (funcall in
(1- i
) j
))
785 (1+ (funcall in i
(1- j
)))
786 (+ (if (equal (aref s1
(1- i
)) (aref s2
(1- j
))) 0 1)
787 (funcall in
(1- i
) (1- j
)))))))
790 (defun org-babel-combine-header-arg-lists (original &rest others
)
791 "Combine a number of lists of header argument names and arguments."
792 (let ((results (copy-sequence original
)))
793 (dolist (new-list others
)
794 (dolist (arg-pair new-list
)
795 (let ((header (car arg-pair
))
796 (args (cdr arg-pair
)))
798 (cons arg-pair
(org-remove-if
799 (lambda (pair) (equal header
(car pair
)))
804 (defun org-babel-check-src-block ()
805 "Check for misspelled header arguments in the current code block."
807 ;; TODO: report malformed code block
808 ;; TODO: report incompatible combinations of header arguments
809 ;; TODO: report uninitialized variables
810 (let ((too-close 2) ;; <- control closeness to report potential match
811 (names (mapcar #'symbol-name org-babel-header-arg-names
)))
812 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg
)) 1))
813 (and (org-babel-where-is-src-block-head)
814 (org-babel-parse-header-arguments
816 (match-string 4))))))
818 (when (and (not (string= header name
))
819 (<= (org-babel-edit-distance header name
) too-close
)
820 (not (member header names
)))
821 (error "Supplied header \"%S\" is suspiciously close to \"%S\""
823 (message "No suspicious header arguments found.")))
826 (defun org-babel-insert-header-arg (&optional header-arg value
)
827 "Insert a header argument selecting from lists of common args and values."
829 (let* ((info (org-babel-get-src-block-info 'light
))
832 (lang-headers (intern (concat "org-babel-header-args:" lang
)))
833 (headers (org-babel-combine-header-arg-lists
834 org-babel-common-header-args-w-values
835 (when (boundp lang-headers
) (eval lang-headers
))))
836 (header-arg (or header-arg
837 (org-icompleting-read
840 (lambda (header-spec) (symbol-name (car header-spec
)))
842 (vals (cdr (assoc (intern header-arg
) headers
)))
846 (read-from-minibuffer "value: "))
850 (let ((arg (org-icompleting-read
853 (mapcar #'symbol-name group
)))))
854 (if (and arg
(not (string= "default" arg
)))
860 (goto-char (point-at-eol))
861 (unless (= (char-before (point)) ?\
) (insert " "))
862 (insert ":" header-arg
) (when value
(insert " " value
)))))
864 ;; Add support for completing-read insertion of header arguments after ":"
865 (defun org-babel-header-arg-expand ()
866 "Call `org-babel-enter-header-arg-w-completion' in appropriate contexts."
867 (when (and (equal (char-before) ?\
:) (org-babel-where-is-src-block-head))
868 (org-babel-enter-header-arg-w-completion (match-string 2))))
870 (defun org-babel-enter-header-arg-w-completion (&optional lang
)
871 "Insert header argument appropriate for LANG with completion."
872 (let* ((lang-headers-var (intern (concat "org-babel-header-args:" lang
)))
873 (lang-headers (when (boundp lang-headers-var
) (eval lang-headers-var
)))
874 (headers-w-values (org-babel-combine-header-arg-lists
875 org-babel-common-header-args-w-values lang-headers
))
876 (headers (mapcar #'symbol-name
(mapcar #'car headers-w-values
)))
877 (header (org-completing-read "Header Arg: " headers
))
878 (args (cdr (assoc (intern header
) headers-w-values
)))
879 (arg (when (and args
(listp args
))
881 (format "%s: " header
)
882 (mapcar #'symbol-name
(apply #'append args
))))))
883 (insert (concat header
" " (or arg
"")))
886 (add-hook 'org-tab-first-hook
'org-babel-header-arg-expand
)
889 (defun org-babel-load-in-session (&optional arg info
)
890 "Load the body of the current source-code block.
891 Evaluate the header arguments for the source block before
892 entering the session. After loading the body this pops open the
895 (let* ((info (or info
(org-babel-get-src-block-info)))
897 (params (nth 2 info
))
899 (user-error "No src code block at point")
901 (if (org-babel-noweb-p params
:eval
)
902 (org-babel-expand-noweb-references info
)
904 (session (cdr (assoc :session params
)))
905 (dir (cdr (assoc :dir params
)))
907 (or (and dir
(file-name-as-directory dir
)) default-directory
))
908 (cmd (intern (concat "org-babel-load-session:" lang
))))
909 (unless (fboundp cmd
)
910 (error "No org-babel-load-session function for %s!" lang
))
911 (pop-to-buffer (funcall cmd session body params
))
915 (defun org-babel-initiate-session (&optional arg info
)
916 "Initiate session for current code block.
917 If called with a prefix argument then resolve any variable
918 references in the header arguments and assign these variables in
919 the session. Copy the body of the code block to the kill ring."
921 (let* ((info (or info
(org-babel-get-src-block-info (not arg
))))
924 (params (nth 2 info
))
925 (session (cdr (assoc :session params
)))
926 (dir (cdr (assoc :dir params
)))
928 (or (and dir
(file-name-as-directory dir
)) default-directory
))
929 (init-cmd (intern (format "org-babel-%s-initiate-session" lang
)))
930 (prep-cmd (intern (concat "org-babel-prep-session:" lang
))))
931 (if (and (stringp session
) (string= session
"none"))
932 (error "This block is not using a session!"))
933 (unless (fboundp init-cmd
)
934 (error "No org-babel-initiate-session function for %s!" lang
))
935 (with-temp-buffer (insert (org-babel-trim body
))
936 (copy-region-as-kill (point-min) (point-max)))
938 (unless (fboundp prep-cmd
)
939 (error "No org-babel-prep-session function for %s!" lang
))
940 (funcall prep-cmd session params
))
941 (funcall init-cmd session params
)))
944 (defun org-babel-switch-to-session (&optional arg info
)
945 "Switch to the session of the current code block.
946 Uses `org-babel-initiate-session' to start the session. If called
947 with a prefix argument then this is passed on to
948 `org-babel-initiate-session'."
950 (pop-to-buffer (org-babel-initiate-session arg info
))
953 (defalias 'org-babel-pop-to-session
'org-babel-switch-to-session
)
955 (defvar org-src-window-setup
)
958 (defun org-babel-switch-to-session-with-code (&optional arg info
)
959 "Switch to code buffer and display session."
963 (let ((other-window-buffer (window-buffer (next-window))))
964 (set-window-buffer (next-window) (current-buffer))
965 (set-window-buffer (selected-window) other-window-buffer
))
967 (info (org-babel-get-src-block-info))
968 (org-src-window-setup 'reorganize-frame
))
970 (org-babel-switch-to-session arg info
))
972 (funcall swap-windows
)))
974 (defmacro org-babel-do-in-edit-buffer
(&rest body
)
975 "Evaluate BODY in edit buffer if there is a code block at point.
976 Return t if a code block was found at point, nil otherwise."
977 `(let ((org-src-window-setup 'switch-invisibly
))
978 (when (and (org-babel-where-is-src-block-head)
979 (org-edit-src-code nil nil nil
))
980 (unwind-protect (progn ,@body
)
981 (if (org-bound-and-true-p org-edit-src-from-org-mode
)
982 (org-edit-src-exit)))
984 (def-edebug-spec org-babel-do-in-edit-buffer
(body))
986 (defun org-babel-do-key-sequence-in-edit-buffer (key)
987 "Read key sequence and execute the command in edit buffer.
988 Enter a key sequence to be executed in the language major-mode
989 edit buffer. For example, TAB will alter the contents of the
990 Org-mode code block according to the effect of TAB in the
991 language major-mode buffer. For languages that support
992 interactive sessions, this can be used to send code from the Org
993 buffer to the session for evaluation using the native major-mode
994 evaluation mechanisms."
995 (interactive "kEnter key-sequence to execute in edit buffer: ")
996 (org-babel-do-in-edit-buffer
998 (key-binding (or key
(read-key-sequence nil
))))))
1000 (defvar org-bracket-link-regexp
)
1002 (defun org-babel-active-location-p ()
1003 (memq (car (save-match-data (org-element-context)))
1004 '(babel-call inline-babel-call inline-src-block src-block
)))
1007 (defun org-babel-open-src-block-result (&optional re-run
)
1008 "If `point' is on a src block then open the results of the
1009 source code block, otherwise return nil. With optional prefix
1010 argument RE-RUN the source-code block is evaluated even if
1011 results already exist."
1013 (let ((info (org-babel-get-src-block-info 'light
)))
1016 ;; go to the results, if there aren't any then run the block
1017 (goto-char (or (and (not re-run
) (org-babel-where-is-src-block-result))
1018 (progn (org-babel-execute-src-block)
1019 (org-babel-where-is-src-block-result))))
1021 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
1023 (if (looking-at org-bracket-link-regexp
)
1026 (let ((r (org-babel-format-result
1027 (org-babel-read-result) (cdr (assoc :sep
(nth 2 info
))))))
1028 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
1029 (delete-region (point-min) (point-max))
1034 (defmacro org-babel-map-src-blocks
(file &rest body
)
1035 "Evaluate BODY forms on each source-block in FILE.
1036 If FILE is nil evaluate BODY forms on source blocks in current
1037 buffer. During evaluation of BODY the following local variables
1038 are set relative to the currently matched code block.
1040 full-block ------- string holding the entirety of the code block
1041 beg-block -------- point at the beginning of the code block
1042 end-block -------- point at the end of the matched code block
1043 lang ------------- string holding the language of the code block
1044 beg-lang --------- point at the beginning of the lang
1045 end-lang --------- point at the end of the lang
1046 switches --------- string holding the switches
1047 beg-switches ----- point at the beginning of the switches
1048 end-switches ----- point at the end of the switches
1049 header-args ------ string holding the header-args
1050 beg-header-args -- point at the beginning of the header-args
1051 end-header-args -- point at the end of the header-args
1052 body ------------- string holding the body of the code block
1053 beg-body --------- point at the beginning of the body
1054 end-body --------- point at the end of the body"
1055 (declare (indent 1))
1056 (let ((tempvar (make-symbol "file")))
1057 `(let* ((,tempvar
,file
)
1058 (visited-p (or (null ,tempvar
)
1059 (get-file-buffer (expand-file-name ,tempvar
))))
1060 (point (point)) to-be-removed
)
1061 (save-window-excursion
1062 (when ,tempvar
(find-file ,tempvar
))
1063 (setq to-be-removed
(current-buffer))
1064 (goto-char (point-min))
1065 (while (re-search-forward org-babel-src-block-regexp nil t
)
1066 (when (org-babel-active-location-p)
1067 (goto-char (match-beginning 0))
1068 (let ((full-block (match-string 0))
1069 (beg-block (match-beginning 0))
1070 (end-block (match-end 0))
1071 (lang (match-string 2))
1072 (beg-lang (match-beginning 2))
1073 (end-lang (match-end 2))
1074 (switches (match-string 3))
1075 (beg-switches (match-beginning 3))
1076 (end-switches (match-end 3))
1077 (header-args (match-string 4))
1078 (beg-header-args (match-beginning 4))
1079 (end-header-args (match-end 4))
1080 (body (match-string 5))
1081 (beg-body (match-beginning 5))
1082 (end-body (match-end 5)))
1084 (goto-char end-block
)))))
1085 (unless visited-p
(kill-buffer to-be-removed
))
1086 (goto-char point
))))
1087 (def-edebug-spec org-babel-map-src-blocks
(form body
))
1090 (defmacro org-babel-map-inline-src-blocks
(file &rest body
)
1091 "Evaluate BODY forms on each inline source-block in FILE.
1092 If FILE is nil evaluate BODY forms on source blocks in current
1094 (declare (indent 1))
1095 (let ((tempvar (make-symbol "file")))
1096 `(let* ((,tempvar
,file
)
1097 (visited-p (or (null ,tempvar
)
1098 (get-file-buffer (expand-file-name ,tempvar
))))
1099 (point (point)) to-be-removed
)
1100 (save-window-excursion
1101 (when ,tempvar
(find-file ,tempvar
))
1102 (setq to-be-removed
(current-buffer))
1103 (goto-char (point-min))
1104 (while (re-search-forward org-babel-inline-src-block-regexp nil t
)
1105 (when (org-babel-active-location-p)
1106 (goto-char (match-beginning 1))
1107 (save-match-data ,@body
))
1108 (goto-char (match-end 0))))
1109 (unless visited-p
(kill-buffer to-be-removed
))
1110 (goto-char point
))))
1111 (def-edebug-spec org-babel-map-inline-src-blocks
(form body
))
1113 (defvar org-babel-lob-one-liner-regexp
)
1116 (defmacro org-babel-map-call-lines
(file &rest body
)
1117 "Evaluate BODY forms on each call line in FILE.
1118 If FILE is nil evaluate BODY forms on source blocks in current
1120 (declare (indent 1))
1121 (let ((tempvar (make-symbol "file")))
1122 `(let* ((,tempvar
,file
)
1123 (visited-p (or (null ,tempvar
)
1124 (get-file-buffer (expand-file-name ,tempvar
))))
1125 (point (point)) to-be-removed
)
1126 (save-window-excursion
1127 (when ,tempvar
(find-file ,tempvar
))
1128 (setq to-be-removed
(current-buffer))
1129 (goto-char (point-min))
1130 (while (re-search-forward org-babel-lob-one-liner-regexp nil t
)
1131 (when (org-babel-active-location-p)
1132 (goto-char (match-beginning 1))
1133 (save-match-data ,@body
))
1134 (goto-char (match-end 0))))
1135 (unless visited-p
(kill-buffer to-be-removed
))
1136 (goto-char point
))))
1137 (def-edebug-spec org-babel-map-call-lines
(form body
))
1140 (defmacro org-babel-map-executables
(file &rest body
)
1141 (declare (indent 1))
1142 (let ((tempvar (make-symbol "file"))
1143 (rx (make-symbol "rx")))
1144 `(let* ((,tempvar
,file
)
1145 (,rx
(concat "\\(" org-babel-src-block-regexp
1146 "\\|" org-babel-inline-src-block-regexp
1147 "\\|" org-babel-lob-one-liner-regexp
"\\)"))
1148 (visited-p (or (null ,tempvar
)
1149 (get-file-buffer (expand-file-name ,tempvar
))))
1150 (point (point)) to-be-removed
)
1151 (save-window-excursion
1152 (when ,tempvar
(find-file ,tempvar
))
1153 (setq to-be-removed
(current-buffer))
1154 (goto-char (point-min))
1155 (while (re-search-forward ,rx nil t
)
1156 (when (org-babel-active-location-p)
1157 (goto-char (match-beginning 1))
1158 (when (looking-at org-babel-inline-src-block-regexp
)
1160 (save-match-data ,@body
))
1161 (goto-char (match-end 0))))
1162 (unless visited-p
(kill-buffer to-be-removed
))
1163 (goto-char point
))))
1164 (def-edebug-spec org-babel-map-executables
(form body
))
1167 (defun org-babel-execute-buffer (&optional arg
)
1168 "Execute source code blocks in a buffer.
1169 Call `org-babel-execute-src-block' on every source block in
1170 the current buffer."
1172 (org-babel-eval-wipe-error-buffer)
1173 (org-save-outline-visibility t
1174 (org-babel-map-executables nil
1175 (if (looking-at org-babel-lob-one-liner-regexp
)
1176 (org-babel-lob-execute-maybe)
1177 (org-babel-execute-src-block arg
)))))
1180 (defun org-babel-execute-subtree (&optional arg
)
1181 "Execute source code blocks in a subtree.
1182 Call `org-babel-execute-src-block' on every source block in
1183 the current subtree."
1187 (org-narrow-to-subtree)
1188 (org-babel-execute-buffer arg
)
1192 (defun org-babel-sha1-hash (&optional info
)
1193 "Generate an sha1 hash based on the value of info."
1195 (let ((print-level nil
)
1196 (info (or info
(org-babel-get-src-block-info))))
1198 (sort (copy-sequence (nth 2 info
))
1199 (lambda (a b
) (string< (car a
) (car b
)))))
1200 (let* ((rm (lambda (lst)
1201 (dolist (p '("replace" "silent" "none"
1202 "append" "prepend"))
1203 (setq lst
(remove p lst
)))
1206 (let ((v (if (and (listp (cdr arg
)) (null (cddr arg
)))
1207 (copy-sequence (cdr arg
))
1209 (when (and v
(not (and (sequencep v
)
1213 ((and (listp v
) ; lists are sorted
1214 (member (car arg
) '(:result-params
)))
1215 (sort (funcall rm v
) #'string
<))
1216 ((and (stringp v
) ; strings are sorted
1217 (member (car arg
) '(:results
:exports
)))
1218 (mapconcat #'identity
(sort (funcall rm
(split-string v
))
1221 (let* ((it (format "%s-%s"
1224 (delq nil
(mapcar (lambda (arg)
1225 (let ((normalized (funcall norm arg
)))
1227 (format "%S" normalized
))))
1231 (when (org-called-interactively-p 'interactive
) (message hash
))
1234 (defun org-babel-current-result-hash ()
1235 "Return the current in-buffer hash."
1236 (org-babel-where-is-src-block-result)
1237 (org-no-properties (match-string 5)))
1239 (defun org-babel-set-current-result-hash (hash)
1240 "Set the current in-buffer hash to HASH."
1241 (org-babel-where-is-src-block-result)
1242 (save-excursion (goto-char (match-beginning 5))
1243 (mapc #'delete-overlay
(overlays-at (point)))
1244 (forward-char org-babel-hash-show
)
1245 (mapc #'delete-overlay
(overlays-at (point)))
1246 (replace-match hash nil nil nil
5)
1247 (goto-char (point-at-bol))
1248 (org-babel-hide-hash)))
1250 (defun org-babel-hide-hash ()
1251 "Hide the hash in the current results line.
1252 Only the initial `org-babel-hash-show' characters of the hash
1253 will remain visible."
1254 (add-to-invisibility-spec '(org-babel-hide-hash . t
))
1256 (when (and (re-search-forward org-babel-result-regexp nil t
)
1258 (let* ((start (match-beginning 5))
1259 (hide-start (+ org-babel-hash-show start
))
1261 (hash (match-string 5))
1263 (setq ov1
(make-overlay start hide-start
))
1264 (setq ov2
(make-overlay hide-start end
))
1265 (overlay-put ov2
'invisible
'org-babel-hide-hash
)
1266 (overlay-put ov1
'babel-hash hash
)))))
1268 (defun org-babel-hide-all-hashes ()
1269 "Hide the hash in the current buffer.
1270 Only the initial `org-babel-hash-show' characters of each hash
1271 will remain visible. This function should be called as part of
1272 the `org-mode-hook'."
1274 (while (and (not org-babel-hash-show-time
)
1275 (re-search-forward org-babel-result-regexp nil t
))
1276 (goto-char (match-beginning 0))
1277 (org-babel-hide-hash)
1278 (goto-char (match-end 0)))))
1279 (add-hook 'org-mode-hook
'org-babel-hide-all-hashes
)
1281 (defun org-babel-hash-at-point (&optional point
)
1282 "Return the value of the hash at POINT.
1283 The hash is also added as the last element of the kill ring.
1284 This can be called with C-c C-c."
1286 (let ((hash (car (delq nil
(mapcar
1287 (lambda (ol) (overlay-get ol
'babel-hash
))
1288 (overlays-at (or point
(point))))))))
1289 (when hash
(kill-new hash
) (message hash
))))
1290 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-hash-at-point
)
1292 (defun org-babel-result-hide-spec ()
1293 "Hide portions of results lines.
1294 Add `org-babel-hide-result' as an invisibility spec for hiding
1295 portions of results lines."
1296 (add-to-invisibility-spec '(org-babel-hide-result . t
)))
1297 (add-hook 'org-mode-hook
'org-babel-result-hide-spec
)
1299 (defvar org-babel-hide-result-overlays nil
1300 "Overlays hiding results.")
1302 (defun org-babel-result-hide-all ()
1303 "Fold all results in the current buffer."
1305 (org-babel-show-result-all)
1307 (while (re-search-forward org-babel-result-regexp nil t
)
1308 (save-excursion (goto-char (match-beginning 0))
1309 (org-babel-hide-result-toggle-maybe)))))
1311 (defun org-babel-show-result-all ()
1312 "Unfold all results in the current buffer."
1313 (mapc 'delete-overlay org-babel-hide-result-overlays
)
1314 (setq org-babel-hide-result-overlays nil
))
1317 (defun org-babel-hide-result-toggle-maybe ()
1318 "Toggle visibility of result at point."
1320 (let ((case-fold-search t
))
1322 (beginning-of-line 1)
1323 (looking-at org-babel-result-regexp
))
1324 (progn (org-babel-hide-result-toggle)
1325 t
) ;; to signal that we took action
1326 nil
))) ;; to signal that we did not
1328 (defun org-babel-hide-result-toggle (&optional force
)
1329 "Toggle the visibility of the current result."
1333 (if (re-search-forward org-babel-result-regexp nil t
)
1334 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
1336 (while (looking-at org-babel-multi-line-header-regexp
)
1338 (goto-char (- (org-babel-result-end) 1)) (point)))
1340 (if (memq t
(mapcar (lambda (overlay)
1341 (eq (overlay-get overlay
'invisible
)
1342 'org-babel-hide-result
))
1343 (overlays-at start
)))
1344 (if (or (not force
) (eq force
'off
))
1346 (when (member ov org-babel-hide-result-overlays
)
1347 (setq org-babel-hide-result-overlays
1348 (delq ov org-babel-hide-result-overlays
)))
1349 (when (eq (overlay-get ov
'invisible
)
1350 'org-babel-hide-result
)
1351 (delete-overlay ov
)))
1352 (overlays-at start
)))
1353 (setq ov
(make-overlay start end
))
1354 (overlay-put ov
'invisible
'org-babel-hide-result
)
1355 ;; make the block accessible to isearch
1357 ov
'isearch-open-invisible
1359 (when (member ov org-babel-hide-result-overlays
)
1360 (setq org-babel-hide-result-overlays
1361 (delq ov org-babel-hide-result-overlays
)))
1362 (when (eq (overlay-get ov
'invisible
)
1363 'org-babel-hide-result
)
1364 (delete-overlay ov
))))
1365 (push ov org-babel-hide-result-overlays
)))
1366 (error "Not looking at a result line"))))
1368 ;; org-tab-after-check-for-cycling-hook
1369 (add-hook 'org-tab-first-hook
'org-babel-hide-result-toggle-maybe
)
1370 ;; Remove overlays when changing major mode
1371 (add-hook 'org-mode-hook
1372 (lambda () (org-add-hook 'change-major-mode-hook
1373 'org-babel-show-result-all
'append
'local
)))
1375 (defvar org-file-properties
)
1376 (defun org-babel-params-from-properties (&optional lang
)
1377 "Retrieve parameters specified as properties.
1378 Return a list of association lists of source block params
1379 specified in the properties of the current outline entry."
1382 ;; DEPRECATED header arguments specified as separate property at
1383 ;; point of definition
1385 (org-babel-parse-multiple-vars
1388 (lambda (header-arg)
1389 (and (setq val
(org-entry-get (point) header-arg t
))
1390 (cons (intern (concat ":" header-arg
))
1391 (org-babel-read val
))))
1396 (org-babel-combine-header-arg-lists
1397 org-babel-common-header-args-w-values
1399 (setq sym
(intern (concat "org-babel-header-args:" lang
)))
1400 (and (boundp sym
) (eval sym
))))))))))
1401 ;; header arguments specified with the header-args property at
1403 (org-babel-parse-header-arguments
1404 (org-entry-get org-babel-current-src-block-location
1405 "header-args" 'inherit
))
1406 (when lang
;; language-specific header arguments at point of call
1407 (org-babel-parse-header-arguments
1408 (org-entry-get org-babel-current-src-block-location
1409 (concat "header-args:" lang
) 'inherit
))))))
1411 (defvar org-src-preserve-indentation
)
1412 (defun org-babel-parse-src-block-match ()
1413 "Parse the results from a match of the `org-babel-src-block-regexp'."
1414 (let* ((block-indentation (length (match-string 1)))
1415 (lang (org-no-properties (match-string 2)))
1416 (lang-headers (intern (concat "org-babel-default-header-args:" lang
)))
1417 (switches (match-string 3))
1418 (body (org-no-properties
1419 (let* ((body (match-string 5))
1420 (sub-length (- (length body
) 1)))
1421 (if (and (> sub-length
0)
1422 (string= "\n" (substring body sub-length
)))
1423 (substring body
0 sub-length
)
1425 (preserve-indentation (or org-src-preserve-indentation
1427 (string-match "-i\\>" switches
)))))
1429 ;; get block body less properties, protective commas, and indentation
1432 (insert (org-unescape-code-in-string body
))
1433 (unless preserve-indentation
(org-do-remove-indentation))
1435 (apply #'org-babel-merge-params
1436 org-babel-default-header-args
1437 (when (boundp lang-headers
) (eval lang-headers
))
1439 (org-babel-params-from-properties lang
)
1440 (list (org-babel-parse-header-arguments
1441 (org-no-properties (or (match-string 4) ""))))))
1443 block-indentation
)))
1445 (defun org-babel-parse-inline-src-block-match ()
1446 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
1447 (let* ((lang (org-no-properties (match-string 2)))
1448 (lang-headers (intern (concat "org-babel-default-header-args:" lang
))))
1450 (org-unescape-code-in-string (org-no-properties (match-string 5)))
1451 (apply #'org-babel-merge-params
1452 org-babel-default-inline-header-args
1453 (if (boundp lang-headers
) (eval lang-headers
) nil
)
1455 (org-babel-params-from-properties lang
)
1456 (list (org-babel-parse-header-arguments
1457 (org-no-properties (or (match-string 4) ""))))))
1460 (defun org-babel-balanced-split (string alts
)
1461 "Split STRING on instances of ALTS.
1462 ALTS is a cons of two character options where each option may be
1463 either the numeric code of a single character or a list of
1464 character alternatives. For example to split on balanced
1465 instances of \"[ \t]:\" set ALTS to '((32 9) . 58)."
1466 (let* ((matches (lambda (ch spec
) (if (listp spec
) (member ch spec
) (equal spec ch
))))
1467 (matched (lambda (ch last
)
1469 (and (funcall matches ch
(cdr alts
))
1470 (funcall matches last
(car alts
)))
1471 (funcall matches ch alts
))))
1472 (balance 0) (last 0)
1474 (mapc (lambda (ch) ; split on [], (), "" balanced instances of [ \t]:
1475 (setq balance
(+ balance
1476 (cond ((or (equal 91 ch
) (equal 40 ch
)) 1)
1477 ((or (equal 93 ch
) (equal 41 ch
)) -
1)
1479 (when (and (equal 34 ch
) (not (equal 92 last
)))
1480 (setq quote
(not quote
)))
1481 (setq partial
(cons ch partial
))
1482 (when (and (= balance
0) (not quote
) (funcall matched ch last
))
1483 (setq lst
(cons (apply #'string
(nreverse
1490 (string-to-list string
))
1491 (nreverse (cons (apply #'string
(nreverse partial
)) lst
))))
1493 (defun org-babel-join-splits-near-ch (ch list
)
1494 "Join splits where \"=\" is on either end of the split."
1495 (let ((last= (lambda (str) (= ch
(aref str
(1- (length str
))))))
1496 (first= (lambda (str) (= ch
(aref str
0)))))
1498 (org-reduce (lambda (acc el
)
1499 (let ((head (car acc
)))
1500 (if (and head
(or (funcall last
= head
) (funcall first
= el
)))
1501 (cons (concat head el
) (cdr acc
))
1503 list
:initial-value nil
))))
1505 (defun org-babel-parse-header-arguments (arg-string)
1506 "Parse a string of header arguments returning an alist."
1507 (when (> (length arg-string
) 0)
1508 (org-babel-parse-multiple-vars
1513 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1515 (cons (intern (match-string 1 arg
))
1516 (org-babel-read (org-babel-chomp (match-string 2 arg
))))
1517 (cons (intern (org-babel-chomp arg
)) nil
)))
1518 (let ((raw (org-babel-balanced-split arg-string
'((32 9) .
58))))
1519 (cons (car raw
) (mapcar (lambda (r) (concat ":" r
)) (cdr raw
)))))))))
1521 (defun org-babel-parse-multiple-vars (header-arguments)
1522 "Expand multiple variable assignments behind a single :var keyword.
1524 This allows expression of multiple variables with one :var as
1527 #+PROPERTY: var foo=1, bar=2"
1529 (mapc (lambda (pair)
1530 (if (eq (car pair
) :var
)
1531 (mapcar (lambda (v) (push (cons :var
(org-babel-trim v
)) results
))
1532 (org-babel-join-splits-near-ch
1533 61 (org-babel-balanced-split (cdr pair
) 32)))
1534 (push pair results
)))
1536 (nreverse results
)))
1538 (defun org-babel-process-params (params)
1539 "Expand variables in PARAMS and add summary parameters."
1540 (let* ((processed-vars (mapcar (lambda (el)
1541 (if (consp (cdr el
))
1543 (org-babel-ref-parse (cdr el
))))
1544 (org-babel-get-header params
:var
)))
1545 (vars-and-names (if (and (assoc :colname-names params
)
1546 (assoc :rowname-names params
))
1547 (list processed-vars
)
1548 (org-babel-disassemble-tables
1550 (cdr (assoc :hlines params
))
1551 (cdr (assoc :colnames params
))
1552 (cdr (assoc :rownames params
)))))
1553 (raw-result (or (cdr (assoc :results params
)) ""))
1554 (result-params (append
1555 (split-string (if (stringp raw-result
)
1558 (cdr (assoc :result-params params
)))))
1560 (mapcar (lambda (var) (cons :var var
)) (car vars-and-names
))
1562 (cons :colname-names
(or (cdr (assoc :colname-names params
))
1563 (cadr vars-and-names
)))
1564 (cons :rowname-names
(or (cdr (assoc :rowname-names params
))
1565 (caddr vars-and-names
)))
1566 (cons :result-params result-params
)
1567 (cons :result-type
(cond ((member "output" result-params
) 'output
)
1568 ((member "value" result-params
) 'value
)
1570 (org-babel-get-header params
:var
'other
))))
1572 ;; row and column names
1573 (defun org-babel-del-hlines (table)
1574 "Remove all 'hlines from TABLE."
1575 (remove 'hline table
))
1577 (defun org-babel-get-colnames (table)
1578 "Return the column names of TABLE.
1579 Return a cons cell, the `car' of which contains the TABLE less
1580 colnames, and the `cdr' of which contains a list of the column
1582 (if (equal 'hline
(nth 1 table
))
1583 (cons (cddr table
) (car table
))
1584 (cons (cdr table
) (car table
))))
1586 (defun org-babel-get-rownames (table)
1587 "Return the row names of TABLE.
1588 Return a cons cell, the `car' of which contains the TABLE less
1589 rownames, and the `cdr' of which contains a list of the rownames.
1590 Note: this function removes any hlines in TABLE."
1591 (let* ((table (org-babel-del-hlines table
))
1592 (rownames (funcall (lambda ()
1598 (setq tp
(cdr tp
))))
1600 (cons table rownames
)))
1602 (defun org-babel-put-colnames (table colnames
)
1603 "Add COLNAMES to TABLE if they exist."
1604 (if colnames
(apply 'list colnames
'hline table
) table
))
1606 (defun org-babel-put-rownames (table rownames
)
1607 "Add ROWNAMES to TABLE if they exist."
1609 (mapcar (lambda (row)
1611 (cons (or (pop rownames
) "") row
)
1615 (defun org-babel-pick-name (names selector
)
1616 "Select one out of an alist of row or column names.
1617 SELECTOR can be either a list of names in which case those names
1618 will be returned directly, or an index into the list NAMES in
1619 which case the indexed names will be return."
1620 (if (listp selector
)
1623 (if (and selector
(symbolp selector
) (not (equal t selector
)))
1624 (cdr (assoc selector names
))
1625 (if (integerp selector
)
1626 (nth (- selector
1) names
)
1627 (cdr (car (last names
))))))))
1629 (defun org-babel-disassemble-tables (vars hlines colnames rownames
)
1630 "Parse tables for further processing.
1631 Process the variables in VARS according to the HLINES,
1632 ROWNAMES and COLNAMES header arguments. Return a list consisting
1633 of the vars, cnames and rnames."
1634 (let (cnames rnames
)
1638 (when (listp (cdr var
))
1639 (when (and (not (equal colnames
"no"))
1640 (or colnames
(and (equal (nth 1 (cdr var
)) 'hline
)
1641 (not (member 'hline
(cddr (cdr var
)))))))
1642 (let ((both (org-babel-get-colnames (cdr var
))))
1643 (setq cnames
(cons (cons (car var
) (cdr both
))
1645 (setq var
(cons (car var
) (car both
)))))
1646 (when (and rownames
(not (equal rownames
"no")))
1647 (let ((both (org-babel-get-rownames (cdr var
))))
1648 (setq rnames
(cons (cons (car var
) (cdr both
))
1650 (setq var
(cons (car var
) (car both
)))))
1651 (when (and hlines
(not (equal hlines
"yes")))
1652 (setq var
(cons (car var
) (org-babel-del-hlines (cdr var
))))))
1655 (reverse cnames
) (reverse rnames
))))
1657 (defun org-babel-reassemble-table (table colnames rownames
)
1658 "Add column and row names to a table.
1659 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1660 to the table for reinsertion to org-mode."
1662 (let ((table (if (and rownames
(= (length table
) (length rownames
)))
1663 (org-babel-put-rownames table rownames
) table
)))
1664 (if (and colnames
(listp (car table
)) (= (length (car table
))
1666 (org-babel-put-colnames table colnames
) table
))
1669 (defun org-babel-where-is-src-block-head ()
1670 "Find where the current source block begins.
1671 Return the point at the beginning of the current source
1672 block. Specifically at the beginning of the #+BEGIN_SRC line.
1673 If the point is not on a source block then return nil."
1674 (let ((initial (point)) (case-fold-search t
) top bottom
)
1676 (save-excursion ;; on a source name line or a #+header line
1677 (beginning-of-line 1)
1678 (and (or (looking-at org-babel-src-name-regexp
)
1679 (looking-at org-babel-multi-line-header-regexp
))
1681 (while (and (forward-line 1)
1682 (or (looking-at org-babel-src-name-regexp
)
1683 (looking-at org-babel-multi-line-header-regexp
))))
1684 (looking-at org-babel-src-block-regexp
))
1686 (save-excursion ;; on a #+begin_src line
1687 (beginning-of-line 1)
1688 (and (looking-at org-babel-src-block-regexp
)
1690 (save-excursion ;; inside a src block
1692 (re-search-backward "^[ \t]*#\\+begin_src" nil t
) (setq top
(point))
1693 (re-search-forward "^[ \t]*#\\+end_src" nil t
) (setq bottom
(point))
1694 (< top initial
) (< initial bottom
)
1695 (progn (goto-char top
) (beginning-of-line 1)
1696 (looking-at org-babel-src-block-regexp
))
1700 (defun org-babel-goto-src-block-head ()
1701 "Go to the beginning of the current code block."
1703 (let ((head (org-babel-where-is-src-block-head)))
1704 (if head
(goto-char head
) (error "Not currently in a code block"))))
1707 (defun org-babel-goto-named-src-block (name)
1708 "Go to a named source-code block."
1710 (let ((completion-ignore-case t
)
1711 (case-fold-search t
)
1712 (under-point (thing-at-point 'line
)))
1713 (list (org-icompleting-read
1714 "source-block name: " (org-babel-src-block-names) nil t
1717 ((string-match (org-babel-noweb-wrap) under-point
)
1718 (let ((block-name (match-string 1 under-point
)))
1719 (string-match "[^(]*" block-name
)
1720 (match-string 0 block-name
)))
1722 ((string-match org-babel-lob-one-liner-regexp under-point
)
1723 (let ((source-info (car (org-babel-lob-get-info))))
1724 (if (string-match "^\\([^\\[]+?\\)\\(\\[.*\\]\\)?(" source-info
)
1725 (let ((source-name (match-string 1 source-info
)))
1728 ((string-match (concat "#\\+" org-babel-results-keyword
1729 "\\:\s+\\([^\\(]*\\)") under-point
)
1730 (match-string 1 under-point
))
1732 ((and (thing-at-point 'symbol
))
1733 (org-babel-find-named-block (thing-at-point 'symbol
))
1734 (thing-at-point 'symbol
))
1736 (let ((point (org-babel-find-named-block name
)))
1738 ;; taken from `org-open-at-point'
1739 (progn (org-mark-ring-push) (goto-char point
) (org-show-context))
1740 (message "source-code block '%s' not found in this buffer" name
))))
1742 (defun org-babel-find-named-block (name)
1743 "Find a named source-code block.
1744 Return the location of the source block identified by source
1745 NAME, or nil if no such block exists. Set match data according to
1746 org-babel-named-src-block-regexp."
1748 (let ((case-fold-search t
)
1749 (regexp (org-babel-named-src-block-regexp-for-name name
)) msg
)
1750 (goto-char (point-min))
1751 (when (or (re-search-forward regexp nil t
)
1752 (re-search-backward regexp nil t
))
1753 (match-beginning 0)))))
1755 (defun org-babel-src-block-names (&optional file
)
1756 "Returns the names of source blocks in FILE or the current buffer."
1758 (when file
(find-file file
)) (goto-char (point-min))
1759 (let ((case-fold-search t
) names
)
1760 (while (re-search-forward org-babel-src-name-w-name-regexp nil t
)
1761 (setq names
(cons (match-string 3) names
)))
1765 (defun org-babel-goto-named-result (name)
1766 "Go to a named result."
1768 (let ((completion-ignore-case t
))
1769 (list (org-icompleting-read "source-block name: "
1770 (org-babel-result-names) nil t
))))
1771 (let ((point (org-babel-find-named-result name
)))
1773 ;; taken from `org-open-at-point'
1774 (progn (goto-char point
) (org-show-context))
1775 (message "result '%s' not found in this buffer" name
))))
1777 (defun org-babel-find-named-result (name &optional point
)
1778 "Find a named result.
1779 Return the location of the result named NAME in the current
1780 buffer or nil if no such result exists."
1782 (let ((case-fold-search t
))
1783 (goto-char (or point
(point-min)))
1784 (catch 'is-a-code-block
1785 (when (re-search-forward
1786 (concat org-babel-result-regexp
1787 "[ \t]" (regexp-quote name
) "[ \t]*[\n\f\v\r]") nil t
)
1788 (when (and (string= "name" (downcase (match-string 1)))
1789 (or (beginning-of-line 1)
1790 (looking-at org-babel-src-block-regexp
)
1791 (looking-at org-babel-multi-line-header-regexp
)
1792 (looking-at org-babel-lob-one-liner-regexp
)))
1793 (throw 'is-a-code-block
(org-babel-find-named-result name
(point))))
1794 (beginning-of-line 0) (point))))))
1796 (defun org-babel-result-names (&optional file
)
1797 "Returns the names of results in FILE or the current buffer."
1799 (when file
(find-file file
)) (goto-char (point-min))
1800 (let ((case-fold-search t
) names
)
1801 (while (re-search-forward org-babel-result-w-name-regexp nil t
)
1802 (setq names
(cons (match-string 4) names
)))
1806 (defun org-babel-next-src-block (&optional arg
)
1807 "Jump to the next source block.
1808 With optional prefix argument ARG, jump forward ARG many source blocks."
1810 (org-next-block arg nil org-babel-src-block-regexp
))
1813 (defun org-babel-previous-src-block (&optional arg
)
1814 "Jump to the previous source block.
1815 With optional prefix argument ARG, jump backward ARG many source blocks."
1817 (org-previous-block arg org-babel-src-block-regexp
))
1819 (defvar org-babel-load-languages
)
1822 (defun org-babel-mark-block ()
1823 "Mark current src block."
1825 (let ((head (org-babel-where-is-src-block-head)))
1829 (looking-at org-babel-src-block-regexp
))
1830 (push-mark (match-end 5) nil t
)
1831 (goto-char (match-beginning 5)))))
1833 (defun org-babel-demarcate-block (&optional arg
)
1834 "Wrap or split the code in the region or on the point.
1835 When called from inside of a code block the current block is
1836 split. When called from outside of a code block a new code block
1837 is created. In both cases if the region is demarcated and if the
1838 region is not active then the point is demarcated."
1840 (let ((info (org-babel-get-src-block-info 'light
))
1841 (headers (progn (org-babel-where-is-src-block-head)
1843 (stars (concat (make-string (or (org-current-level) 1) ?
*) " ")))
1849 (let ((lang (nth 0 info
))
1850 (indent (make-string (nth 5 info
) ?
)))
1851 (when (string-match "^[[:space:]]*$"
1852 (buffer-substring (point-at-bol)
1854 (delete-region (point-at-bol) (point-at-eol)))
1856 (if (looking-at "^") "" "\n")
1857 indent
"#+end_src\n"
1858 (if arg stars indent
) "\n"
1859 indent
"#+begin_src " lang
1860 (if (> (length headers
) 1)
1861 (concat " " headers
) headers
)
1862 (if (looking-at "[\n\r]")
1864 (concat "\n" (make-string (current-column) ?
)))))))
1865 (move-end-of-line 2))
1866 (sort (if (org-region-active-p) (list (mark) (point)) (list (point))) #'>))
1867 (let ((start (point))
1868 (lang (org-icompleting-read
1870 (mapcar #'symbol-name
1872 (append (mapcar #'car org-babel-load-languages
)
1873 (mapcar (lambda (el) (intern (car el
)))
1874 org-src-lang-modes
))))))
1875 (body (delete-and-extract-region
1876 (if (org-region-active-p) (mark) (point)) (point))))
1877 (insert (concat (if (looking-at "^") "" "\n")
1878 (if arg
(concat stars
"\n") "")
1879 "#+begin_src " lang
"\n"
1881 (if (or (= (length body
) 0)
1882 (string-match "[\r\n]$" body
)) "" "\n")
1884 (goto-char start
) (move-end-of-line 1)))))
1886 (defvar org-babel-lob-one-liner-regexp
)
1887 (defun org-babel-where-is-src-block-result (&optional insert info hash indent
)
1888 "Find where the current source block results begin.
1889 Return the point at the beginning of the result of the current
1890 source block. Specifically at the beginning of the results line.
1891 If no result exists for this block then create a results line
1892 following the source block."
1894 (let* ((case-fold-search t
)
1895 (on-lob-line (save-excursion
1896 (beginning-of-line 1)
1897 (looking-at org-babel-lob-one-liner-regexp
)))
1898 (inlinep (when (org-babel-get-inline-src-block-matches)
1900 (name (nth 4 (or info
(org-babel-get-src-block-info 'light
))))
1901 (head (unless on-lob-line
(org-babel-where-is-src-block-head)))
1903 (when head
(goto-char head
))
1904 (org-with-wide-buffer
1906 found
;; was there a result (before we potentially insert one)
1911 ;; - return t if it is found, else return nil
1912 ;; - if it does not need to be rebuilt, then don't set end
1913 ;; - if it does need to be rebuilt then do set end
1914 name
(setq beg
(org-babel-find-named-result name
))
1916 (when (and hash
(not (string= hash
(match-string 5))))
1917 (goto-char beg
) (setq end beg
) ;; beginning of result
1919 (delete-region end
(org-babel-result-end)) nil
)))
1922 ;; - return t if it is found, else return nil
1923 ;; - if it is found, and the hash doesn't match, delete and set end
1924 (or on-lob-line
(re-search-forward "^[ \t]*#\\+end_src" nil t
))
1925 (progn (end-of-line 1)
1926 (if (eobp) (insert "\n") (forward-char 1))
1930 (progn ;; unnamed results line already exists
1932 (while (re-search-forward "[^ \f\t\n\r\v]" nil t
)
1933 (beginning-of-line 1)
1935 ((looking-at (concat org-babel-result-regexp
"\n"))
1936 (throw 'non-comment t
))
1937 ((and (looking-at "^[ \t]*#")
1939 org-babel-lob-one-liner-regexp
)))
1941 (t (throw 'non-comment nil
))))))
1942 (let ((this-hash (match-string 5)))
1944 ;; must remove and rebuild if hash!=old-hash
1945 (if (and hash
(not (string= hash this-hash
)))
1949 end
(org-babel-result-end)))
1950 (setq end nil
)))))))))))
1951 (if (not (and insert end
)) found
1954 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1956 (when (wholenump indent
) (make-string indent ?
))
1957 "#+" org-babel-results-keyword
1959 (if org-babel-hash-show-time
1961 "["(format-time-string "<%Y-%m-%d %H:%M:%S>")" "hash
"]")
1962 (concat "["hash
"]")))
1964 (when name
(concat " " name
)) "\n"))
1965 (unless beg
(insert "\n") (backward-char))
1966 (beginning-of-line 0)
1967 (if hash
(org-babel-hide-hash))
1970 (defvar org-block-regexp
)
1971 (defun org-babel-read-result ()
1972 "Read the result at `point' into emacs-lisp."
1973 (let ((case-fold-search t
) result-string
)
1975 ((org-at-table-p) (org-babel-read-table))
1976 ((org-at-item-p) (org-babel-read-list))
1977 ((looking-at org-bracket-link-regexp
) (org-babel-read-link))
1978 ((looking-at org-block-regexp
) (org-babel-trim (match-string 4)))
1979 ((or (looking-at "^[ \t]*: ") (looking-at "^[ \t]*:$"))
1982 (mapconcat (lambda (line)
1983 (or (and (> (length line
) 1)
1984 (string-match "^[ \t]*: ?\\(.+\\)" line
)
1985 (match-string 1 line
))
1989 (point) (org-babel-result-end)) "[\r\n]+")
1991 (or (org-babel-number-p result-string
) result-string
))
1992 ((looking-at org-babel-result-regexp
)
1993 (save-excursion (forward-line 1) (org-babel-read-result))))))
1995 (defun org-babel-read-table ()
1996 "Read the table at `point' into emacs-lisp."
1997 (mapcar (lambda (row)
1998 (if (and (symbolp row
) (equal row
'hline
)) row
1999 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
)) row
)))
2000 (org-table-to-lisp)))
2002 (defun org-babel-read-list ()
2003 "Read the list at `point' into emacs-lisp."
2004 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
))
2005 (mapcar #'cadr
(cdr (org-list-parse-list)))))
2007 (defvar org-link-types-re
)
2008 (defun org-babel-read-link ()
2009 "Read the link at `point' into emacs-lisp.
2010 If the path of the link is a file path it is expanded using
2011 `expand-file-name'."
2012 (let* ((case-fold-search t
)
2013 (raw (and (looking-at org-bracket-link-regexp
)
2014 (org-no-properties (match-string 1))))
2015 (type (and (string-match org-link-types-re raw
)
2016 (match-string 1 raw
))))
2018 ((not type
) (expand-file-name raw
))
2019 ((string= type
"file")
2020 (and (string-match "file\\(.*\\):\\(.+\\)" raw
)
2021 (expand-file-name (match-string 2 raw
))))
2024 (defun org-babel-format-result (result &optional sep
)
2025 "Format RESULT for writing to file."
2026 (let ((echo-res (lambda (r) (if (stringp r
) r
(format "%S" r
)))))
2030 result
(list :sep
(or sep
"\t") :fmt echo-res
))
2032 (funcall echo-res result
))))
2034 (defun org-babel-insert-result
2035 (result &optional result-params info hash indent lang
)
2036 "Insert RESULT into the current buffer.
2037 By default RESULT is inserted after the end of the
2038 current source block. With optional argument RESULT-PARAMS
2039 controls insertion of results in the org-mode file.
2040 RESULT-PARAMS can take the following values:
2042 replace - (default option) insert results after the source block
2043 replacing any previously inserted results
2045 silent -- no results are inserted into the Org-mode buffer but
2046 the results are echoed to the minibuffer and are
2047 ingested by Emacs (a potentially time consuming
2050 file ---- the results are interpreted as a file path, and are
2051 inserted into the buffer using the Org-mode file syntax
2053 list ---- the results are interpreted as an Org-mode list.
2055 raw ----- results are added directly to the Org-mode file. This
2056 is a good option if you code block will output org-mode
2059 drawer -- results are added directly to the Org-mode file as with
2060 \"raw\", but are wrapped in a RESULTS drawer, allowing
2061 them to later be replaced or removed automatically.
2063 org ----- results are added inside of a \"#+BEGIN_SRC org\" block.
2064 They are not comma-escaped when inserted, but Org syntax
2065 here will be discarded when exporting the file.
2067 html ---- results are added inside of a #+BEGIN_HTML block. This
2068 is a good option if you code block will output html
2071 latex --- results are added inside of a #+BEGIN_LATEX block.
2072 This is a good option if you code block will output
2073 latex formatted text.
2075 code ---- the results are extracted in the syntax of the source
2076 code of the language being evaluated and are added
2077 inside of a #+BEGIN_SRC block with the source-code
2078 language set appropriately. Note this relies on the
2079 optional LANG argument."
2080 (if (stringp result
)
2082 (setq result
(org-no-properties result
))
2083 (when (member "file" result-params
)
2084 (setq result
(org-babel-result-to-file
2085 result
(when (assoc :file-desc
(nth 2 info
))
2086 (or (cdr (assoc :file-desc
(nth 2 info
)))
2088 (unless (listp result
) (setq result
(format "%S" result
))))
2089 (if (and result-params
(member "silent" result-params
))
2091 (message (replace-regexp-in-string "%" "%%" (format "%S" result
)))
2096 (when (or (org-babel-get-inline-src-block-matches)
2097 (org-babel-get-lob-one-liner-matches))
2098 (goto-char (match-end 0))
2099 (insert (if (listp result
) "\n" " "))
2101 (existing-result (unless inlinep
2102 (org-babel-where-is-src-block-result
2103 t info hash indent
)))
2105 (cdr (assoc :results_switches
(nth 2 info
))))
2106 (visible-beg (copy-marker (point-min)))
2107 (visible-end (copy-marker (point-max)))
2108 ;; When results exist outside of the current visible
2109 ;; region of the buffer, be sure to widen buffer to
2111 (outside-scope-p (and existing-result
2112 (or (> visible-beg existing-result
)
2113 (<= visible-end existing-result
))))
2115 (when (and (stringp result
) ; ensure results end in a newline
2117 (> (length result
) 0)
2118 (not (or (string-equal (substring result -
1) "\n")
2119 (string-equal (substring result -
1) "\r"))))
2120 (setq result
(concat result
"\n")))
2123 (when outside-scope-p
(widen))
2124 (if (not existing-result
)
2125 (setq beg
(or inlinep
(point)))
2126 (goto-char existing-result
)
2128 (re-search-forward "#" nil t
)
2129 (setq indent
(- (current-column) 1)))
2133 ((member "replace" result-params
)
2134 (delete-region (point) (org-babel-result-end)))
2135 ((member "append" result-params
)
2136 (goto-char (org-babel-result-end)) (setq beg
(point-marker)))
2137 ((member "prepend" result-params
)))) ; already there
2138 (setq results-switches
2139 (if results-switches
(concat " " results-switches
) ""))
2140 (let ((wrap (lambda (start finish
&optional no-escape
)
2141 (goto-char end
) (insert (concat finish
"\n"))
2142 (goto-char beg
) (insert (concat start
"\n"))
2144 (org-escape-code-in-region (min (point) end
) end
))
2145 (goto-char end
) (goto-char (point-at-eol))
2146 (setq end
(point-marker))))
2147 (proper-list-p (lambda (it) (and (listp it
) (null (cdr (last it
)))))))
2148 ;; insert results based on type
2150 ;; do nothing for an empty result
2152 ;; insert a list if preferred
2153 ((member "list" result-params
)
2156 (org-list-to-generic
2159 (lambda (el) (list nil
(if (stringp el
) el
(format "%S" el
))))
2160 (if (listp result
) result
(split-string result
"\n" t
))))
2161 '(:splicep nil
:istart
"- " :iend
"\n")))
2163 ;; assume the result is a table if it's not a string
2164 ((funcall proper-list-p result
)
2166 (insert (concat (orgtbl-to-orgtbl
2167 (if (or (eq 'hline
(car result
))
2168 (and (listp (car result
))
2169 (listp (cdr (car result
)))))
2170 result
(list result
))
2171 '(:fmt
(lambda (cell) (format "%s" cell
)))) "\n"))
2172 (goto-char beg
) (when (org-at-table-p) (org-table-align)))
2173 ((and (listp result
) (not (funcall proper-list-p result
)))
2174 (insert (format "%s\n" result
)))
2175 ((member "file" result-params
)
2176 (when inlinep
(goto-char inlinep
))
2178 (t (goto-char beg
) (insert result
)))
2179 (when (funcall proper-list-p result
) (goto-char (org-table-end)))
2180 (setq end
(point-marker))
2181 ;; possibly wrap result
2183 ((assoc :wrap
(nth 2 info
))
2184 (let ((name (or (cdr (assoc :wrap
(nth 2 info
))) "RESULTS")))
2185 (funcall wrap
(concat "#+BEGIN_" name
)
2186 (concat "#+END_" (car (org-split-string name
))))))
2187 ((member "html" result-params
)
2188 (funcall wrap
"#+BEGIN_HTML" "#+END_HTML"))
2189 ((member "latex" result-params
)
2190 (funcall wrap
"#+BEGIN_LaTeX" "#+END_LaTeX"))
2191 ((member "org" result-params
)
2192 (goto-char beg
) (if (org-at-table-p) (org-cycle))
2193 (funcall wrap
"#+BEGIN_SRC org" "#+END_SRC"))
2194 ((member "code" result-params
)
2195 (funcall wrap
(format "#+BEGIN_SRC %s%s" (or lang
"none") results-switches
)
2197 ((member "raw" result-params
)
2198 (goto-char beg
) (if (org-at-table-p) (org-cycle)))
2199 ((or (member "drawer" result-params
)
2200 ;; Stay backward compatible with <7.9.2
2201 (member "wrap" result-params
))
2202 (goto-char beg
) (if (org-at-table-p) (org-cycle))
2203 (funcall wrap
":RESULTS:" ":END:" 'no-escape
))
2204 ((and (not (funcall proper-list-p result
))
2205 (not (member "file" result-params
)))
2206 (org-babel-examplize-region beg end results-switches
)
2207 (setq end
(point)))))
2208 ;; possibly indent the results to match the #+results line
2209 (when (and (not inlinep
) (numberp indent
) indent
(> indent
0)
2210 ;; in this case `table-align' does the work for us
2211 (not (and (listp result
)
2212 (member "append" result-params
))))
2213 (indent-rigidly beg end indent
))
2215 (if (member "value" result-params
)
2216 (message "Code block returned no value.")
2217 (message "Code block produced no output."))
2218 (message "Code block evaluation complete.")))
2219 (when outside-scope-p
(narrow-to-region visible-beg visible-end
))
2220 (set-marker visible-beg nil
)
2221 (set-marker visible-end nil
))))))
2223 (defun org-babel-remove-result (&optional info keep-keyword
)
2224 "Remove the result of the current source block."
2226 (let ((location (org-babel-where-is-src-block-result nil info
)))
2229 (goto-char location
)
2230 (when (looking-at (concat org-babel-result-regexp
".*$"))
2232 (if keep-keyword
(1+ (match-end 0)) (1- (match-beginning 0)))
2233 (progn (forward-line 1) (org-babel-result-end))))))))
2235 (defun org-babel-result-end ()
2236 "Return the point at the end of the current set of results."
2239 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
2240 ((org-at-item-p) (let* ((struct (org-list-struct))
2241 (prvs (org-list-prevs-alist struct
)))
2242 (org-list-get-list-end (point-at-bol) struct prvs
)))
2243 ((let ((case-fold-search t
)) (looking-at "^\\([ \t]*\\):results:"))
2244 (progn (re-search-forward (concat "^" (match-string 1) ":END:"))
2245 (forward-char 1) (point)))
2247 (let ((case-fold-search t
))
2248 (if (looking-at (concat "[ \t]*#\\+begin_\\([^ \t\n\r]+\\)"))
2249 (progn (re-search-forward (concat "[ \t]*#\\+end_" (match-string 1))
2252 (while (looking-at "[ \t]*\\(: \\|:$\\|\\[\\[\\)")
2256 (defun org-babel-result-to-file (result &optional description
)
2257 "Convert RESULT into an `org-mode' link with optional DESCRIPTION.
2258 If the `default-directory' is different from the containing
2259 file's directory then expand relative links."
2260 (when (stringp result
)
2261 (format "[[file:%s]%s]"
2262 (if (and default-directory
2264 (not (string= (expand-file-name default-directory
)
2266 (file-name-directory buffer-file-name
)))))
2267 (expand-file-name result default-directory
)
2269 (if description
(concat "[" description
"]") ""))))
2271 (defvar org-babel-capitalize-examplize-region-markers nil
2272 "Make true to capitalize begin/end example markers inserted by code blocks.")
2274 (defun org-babel-examplize-region (beg end
&optional results-switches
)
2275 "Comment out region using the inline '==' or ': ' org example quote."
2277 (let ((chars-between (lambda (b e
)
2278 (not (string-match "^[\\s]*$" (buffer-substring b e
)))))
2279 (maybe-cap (lambda (str) (if org-babel-capitalize-examplize-region-markers
2280 (upcase str
) str
))))
2281 (if (or (funcall chars-between
(save-excursion (goto-char beg
) (point-at-bol)) beg
)
2282 (funcall chars-between end
(save-excursion (goto-char end
) (point-at-eol))))
2285 (insert (format org-babel-inline-result-wrap
2286 (prog1 (buffer-substring beg end
)
2287 (delete-region beg end
)))))
2288 (let ((size (count-lines beg end
)))
2290 (cond ((= size
0)) ; do nothing for an empty result
2291 ((< size org-babel-min-lines-for-block-output
)
2294 (beginning-of-line 1) (insert ": ") (forward-line 1)))
2297 (insert (if results-switches
2299 (funcall maybe-cap
"#+begin_example")
2301 (funcall maybe-cap
"#+begin_example\n")))
2302 (if (markerp end
) (goto-char end
) (forward-char (- end beg
)))
2303 (insert (funcall maybe-cap
"#+end_example\n")))))))))
2305 (defun org-babel-update-block-body (new-body)
2306 "Update the body of the current code block to NEW-BODY."
2307 (if (not (org-babel-where-is-src-block-head))
2308 (error "Not in a source block")
2310 (replace-match (concat (org-babel-trim new-body
) "\n") nil t nil
5))
2311 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
2313 (defun org-babel-merge-params (&rest plists
)
2314 "Combine all parameter association lists in PLISTS.
2315 Later elements of PLISTS override the values of previous elements.
2316 This takes into account some special considerations for certain
2317 parameters when merging lists."
2318 (let* ((results-exclusive-groups
2319 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2320 (cdr (assoc 'results org-babel-common-header-args-w-values
))))
2321 (exports-exclusive-groups
2322 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2323 (cdr (assoc 'exports org-babel-common-header-args-w-values
))))
2325 (e-merge (lambda (exclusive-groups &rest result-params
)
2326 ;; maintain exclusivity of mutually exclusive parameters
2328 (mapc (lambda (new-params)
2329 (mapc (lambda (new-param)
2330 (mapc (lambda (exclusive-group)
2331 (when (member new-param exclusive-group
)
2332 (mapcar (lambda (excluded-param)
2339 (setq output
(org-uniquify
2340 (cons new-param output
))))
2344 params results exports tangle noweb cache vars shebang comments padline
2353 (let ((name (if (listp (cdr pair
))
2355 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
2357 (intern (match-string 1 (cdr pair
)))))))
2361 (if (member name
(mapcar #'car vars
))
2363 (push name clearnames
)
2367 (unless (equal (car p
) name
) p
))
2370 (list (cons name pair
))))
2371 ;; if no name is given and we already have named variables
2372 ;; then assign to named variables in order
2373 (if (and vars
(nth variable-index vars
))
2374 (let ((name (car (nth variable-index vars
))))
2375 (push name clearnames
) ; clear out colnames
2378 (prog1 (setf (cddr (nth variable-index vars
))
2379 (concat (symbol-name name
) "=" (cdr pair
)))
2380 (incf variable-index
)))
2381 (error "Variable \"%s\" must be assigned a default value"
2384 (setq results
(funcall e-merge results-exclusive-groups
2387 (let ((r (cdr pair
)))
2388 (if (stringp r
) r
(eval r
)))))))
2391 (setq results
(funcall e-merge results-exclusive-groups
2393 (unless (or (member "both" exports
)
2394 (member "none" exports
)
2395 (member "code" exports
))
2396 (setq exports
(funcall e-merge exports-exclusive-groups
2397 exports
'("results"))))
2398 (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))
2400 (setq exports
(funcall e-merge exports-exclusive-groups
2401 exports
(split-string (cdr pair
)))))
2402 (:tangle
;; take the latest -- always overwrite
2403 (setq tangle
(or (list (cdr pair
)) tangle
)))
2405 (setq noweb
(funcall e-merge
2406 '(("yes" "no" "tangle" "no-export"
2407 "strip-export" "eval"))
2409 (split-string (or (cdr pair
) "")))))
2411 (setq cache
(funcall e-merge
'(("yes" "no")) cache
2412 (split-string (or (cdr pair
) "")))))
2414 (setq padline
(funcall e-merge
'(("yes" "no")) padline
2415 (split-string (or (cdr pair
) "")))))
2416 (:shebang
;; take the latest -- always overwrite
2417 (setq shebang
(or (list (cdr pair
)) shebang
)))
2419 (setq comments
(funcall e-merge
'(("yes" "no")) comments
2420 (split-string (or (cdr pair
) "")))))
2421 (t ;; replace: this covers e.g. :session
2422 (setq params
(cons pair
(assq-delete-all (car pair
) params
))))))
2425 (setq vars
(reverse vars
))
2426 (while vars
(setq params
(cons (cons :var
(cddr (pop vars
))) params
)))
2427 ;; clear out col-names and row-names for replaced variables
2432 (when (assoc param params
)
2433 (setf (cdr (assoc param params
))
2434 (org-remove-if (lambda (pair) (equal (car pair
) name
))
2435 (cdr (assoc param params
))))
2436 (setf params
(org-remove-if (lambda (pair) (and (equal (car pair
) param
)
2439 (list :colname-names
:rowname-names
)))
2443 (let ((key (intern (concat ":" (symbol-name hd
))))
2445 (setf params
(cons (cons key
(mapconcat 'identity val
" ")) params
))))
2446 '(results exports tangle noweb padline cache shebang comments
))
2449 (defvar org-babel-use-quick-and-dirty-noweb-expansion nil
2450 "Set to true to use regular expressions to expand noweb references.
2451 This results in much faster noweb reference expansion but does
2452 not properly allow code blocks to inherit the \":noweb-ref\"
2453 header argument from buffer or subtree wide properties.")
2455 (defun org-babel-noweb-p (params context
)
2456 "Check if PARAMS require expansion in CONTEXT.
2457 CONTEXT may be one of :tangle, :export or :eval."
2459 (intersect (lambda (as bs
)
2461 (if (member (car as
) bs
)
2463 (funcall intersect
(cdr as
) bs
))))))
2464 (funcall intersect
(case context
2465 (:tangle
'("yes" "tangle" "no-export" "strip-export"))
2466 (:eval
'("yes" "no-export" "strip-export" "eval"))
2468 (split-string (or (cdr (assoc :noweb params
)) "")))))
2470 (defun org-babel-expand-noweb-references (&optional info parent-buffer
)
2471 "Expand Noweb references in the body of the current source code block.
2473 For example the following reference would be replaced with the
2474 body of the source-code block named 'example-block'.
2478 Note that any text preceding the <<foo>> construct on a line will
2479 be interposed between the lines of the replacement text. So for
2480 example if <<foo>> is placed behind a comment, then the entire
2481 replacement text will also be commented.
2483 This function must be called from inside of the buffer containing
2484 the source-code block which holds BODY.
2486 In addition the following syntax can be used to insert the
2487 results of evaluating the source-code block named 'example-block'.
2491 Any optional arguments can be passed to example-block by placing
2492 the arguments inside the parenthesis following the convention
2493 defined by `org-babel-lob'. For example
2495 <<example-block(a=9)>>
2497 would set the value of argument \"a\" equal to \"9\". Note that
2498 these arguments are not evaluated in the current source-code
2499 block but are passed literally to the \"example-block\"."
2500 (let* ((parent-buffer (or parent-buffer
(current-buffer)))
2501 (info (or info
(org-babel-get-src-block-info 'light
)))
2504 (ob-nww-start org-babel-noweb-wrap-start
)
2505 (ob-nww-end org-babel-noweb-wrap-end
)
2506 (comment (string= "noweb" (cdr (assoc :comments
(nth 2 info
)))))
2507 (rx-prefix (concat "\\(" org-babel-src-name-regexp
"\\|"
2508 ":noweb-ref[ \t]+" "\\)"))
2510 (nb-add (lambda (text) (setq new-body
(concat new-body text
))))
2511 (c-wrap (lambda (text)
2513 (funcall (intern (concat lang
"-mode")))
2514 (comment-region (point) (progn (insert text
) (point)))
2515 (org-babel-trim (buffer-string)))))
2516 index source-name evaluate prefix
)
2518 (org-set-local 'org-babel-noweb-wrap-start ob-nww-start
)
2519 (org-set-local 'org-babel-noweb-wrap-end ob-nww-end
)
2520 (insert body
) (goto-char (point-min))
2521 (setq index
(point))
2522 (while (and (re-search-forward (org-babel-noweb-wrap) nil t
))
2523 (save-match-data (setf source-name
(match-string 1)))
2524 (save-match-data (setq evaluate
(string-match "\(.*\)" source-name
)))
2527 (buffer-substring (match-beginning 0)
2529 (beginning-of-line 1) (point)))))
2530 ;; add interval to new-body (removing noweb reference)
2531 (goto-char (match-beginning 0))
2532 (funcall nb-add
(buffer-substring index
(point)))
2533 (goto-char (match-end 0))
2534 (setq index
(point))
2537 (with-current-buffer parent-buffer
2540 (mapconcat ;; Interpose PREFIX between every line.
2544 (let ((raw (org-babel-ref-resolve source-name
)))
2545 (if (stringp raw
) raw
(format "%S" raw
)))
2547 ;; Retrieve from the library of babel.
2548 (nth 2 (assoc (intern source-name
)
2549 org-babel-library-of-babel
))
2550 ;; Return the contents of headlines literally.
2552 (when (org-babel-ref-goto-headline-id source-name
)
2553 (org-babel-ref-headline-body)))
2554 ;; Find the expansion of reference in this buffer.
2555 (let ((rx (concat rx-prefix source-name
"[ \t\n]"))
2558 (goto-char (point-min))
2559 (if org-babel-use-quick-and-dirty-noweb-expansion
2560 (while (re-search-forward rx nil t
)
2561 (let* ((i (org-babel-get-src-block-info 'light
))
2562 (body (org-babel-expand-noweb-references i
))
2563 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2566 (let ((cs (org-babel-tangle-comment-links i
)))
2567 (concat (funcall c-wrap
(car cs
)) "\n"
2569 (funcall c-wrap
(cadr cs
))))
2571 (setq expansion
(cons sep
(cons full expansion
)))))
2572 (org-babel-map-src-blocks nil
2573 (let ((i (org-babel-get-src-block-info 'light
)))
2574 (when (equal (or (cdr (assoc :noweb-ref
(nth 2 i
)))
2577 (let* ((body (org-babel-expand-noweb-references i
))
2578 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2581 (let ((cs (org-babel-tangle-comment-links i
)))
2582 (concat (funcall c-wrap
(car cs
)) "\n"
2584 (funcall c-wrap
(cadr cs
))))
2587 (cons sep
(cons full expansion
)))))))))
2589 (mapconcat #'identity
(nreverse (cdr expansion
)) "")))
2590 ;; Possibly raise an error if named block doesn't exist.
2591 (if (member lang org-babel-noweb-error-langs
)
2593 (org-babel-noweb-wrap source-name
)
2594 "could not be resolved (see "
2595 "`org-babel-noweb-error-langs')"))
2597 "[\n\r]") (concat "\n" prefix
))))))
2598 (funcall nb-add
(buffer-substring index
(point-max))))
2601 (defun org-babel-script-escape (str &optional force
)
2602 "Safely convert tables into elisp lists."
2607 (or (and (string-equal "[" (substring str
0 1))
2608 (string-equal "]" (substring str -
1)))
2609 (and (string-equal "{" (substring str
0 1))
2610 (string-equal "}" (substring str -
1)))
2611 (and (string-equal "(" (substring str
0 1))
2612 (string-equal ")" (substring str -
1))))))
2616 (let (in-single in-double out
)
2622 (91 (if (or in-double in-single
) ; [
2625 (93 (if (or in-double in-single
) ; ]
2628 (123 (if (or in-double in-single
) ; {
2631 (125 (if (or in-double in-single
) ; }
2634 (44 (if (or in-double in-single
) ; ,
2635 (cons 44 out
) (cons 32 out
)))
2636 (39 (if in-double
; '
2638 (setq in-single
(not in-single
)) (cons 34 out
)))
2639 (34 (if in-single
; "
2640 (append (list 34 32) out
)
2641 (setq in-double
(not in-double
)) (cons 34 out
)))
2642 (t (cons ch out
)))))
2643 (string-to-list str
))
2644 (apply #'string
(reverse out
)))))
2646 (condition-case nil
(org-babel-read escaped
) (error escaped
))))
2648 (defun org-babel-read (cell &optional inhibit-lisp-eval
)
2649 "Convert the string value of CELL to a number if appropriate.
2650 Otherwise if cell looks like lisp (meaning it starts with a
2651 \"(\", \"'\", \"`\" or a \"[\") then read it as lisp,
2652 otherwise return it unmodified as a string. Optional argument
2653 NO-LISP-EVAL inhibits lisp evaluation for situations in which is
2654 it not appropriate."
2655 (if (and (stringp cell
) (not (equal cell
"")))
2656 (or (org-babel-number-p cell
)
2657 (if (and (not inhibit-lisp-eval
)
2658 (or (member (substring cell
0 1) '("(" "'" "`" "["))
2659 (string= cell
"*this*")))
2661 (if (string= (substring cell
0 1) "\"")
2663 (progn (set-text-properties 0 (length cell
) nil cell
) cell
))))
2666 (defun org-babel-number-p (string)
2667 "If STRING represents a number return its value."
2668 (if (and (string-match "[0-9]+" string
)
2669 (string-match "^-?[0-9]*\\.?[0-9]*$" string
)
2670 (= (length (substring string
(match-beginning 0)
2673 (string-to-number string
)))
2675 (defun org-babel-import-elisp-from-file (file-name &optional separator
)
2676 "Read the results located at FILE-NAME into an elisp table.
2677 If the table is trivial, then return it as a scalar."
2679 (save-window-excursion
2683 (org-table-import file-name separator
)
2684 (delete-file file-name
)
2685 (setq result
(mapcar (lambda (row)
2686 (mapcar #'org-babel-string-read row
))
2687 (org-table-to-lisp))))
2688 (error (message "Error reading results: %s" err
) nil
)))
2689 (if (null (cdr result
)) ;; if result is trivial vector, then scalarize it
2690 (if (consp (car result
))
2691 (if (null (cdr (car result
)))
2697 (defun org-babel-string-read (cell)
2698 "Strip nested \"s from around strings."
2699 (org-babel-read (or (and (stringp cell
)
2700 (string-match "\\\"\\(.+\\)\\\"" cell
)
2701 (match-string 1 cell
))
2704 (defun org-babel-chomp (string &optional regexp
)
2705 "Strip trailing spaces and carriage returns from STRING.
2706 Default regexp used is \"[ \f\t\n\r\v]\" but can be
2707 overwritten by specifying a regexp as a second argument."
2708 (let ((regexp (or regexp
"[ \f\t\n\r\v]")))
2709 (while (and (> (length string
) 0)
2710 (string-match regexp
(substring string -
1)))
2711 (setq string
(substring string
0 -
1)))
2714 (defun org-babel-trim (string &optional regexp
)
2715 "Strip leading and trailing spaces and carriage returns from STRING.
2716 Like `org-babel-chomp' only it runs on both the front and back
2718 (org-babel-chomp (org-reverse-string
2719 (org-babel-chomp (org-reverse-string string
) regexp
))
2722 (defun org-babel-tramp-handle-call-process-region
2723 (start end program
&optional delete buffer display
&rest args
)
2724 "Use Tramp to handle `call-process-region'.
2725 Fixes a bug in `tramp-handle-call-process-region'."
2726 (if (and (featurep 'tramp
) (file-remote-p default-directory
))
2727 (let ((tmpfile (tramp-compat-make-temp-file "")))
2728 (write-region start end tmpfile
)
2729 (when delete
(delete-region start end
))
2731 ;; (apply 'call-process program tmpfile buffer display args)
2733 (apply 'process-file program tmpfile buffer display args
)
2734 (delete-file tmpfile
)))
2735 ;; org-babel-call-process-region-original is the original emacs
2736 ;; definition. It is in scope from the let binding in
2737 ;; org-babel-execute-src-block
2738 (apply org-babel-call-process-region-original
2739 start end program delete buffer display args
)))
2741 (defun org-babel-local-file-name (file)
2742 "Return the local name component of FILE."
2743 (or (file-remote-p file
'localname
) file
))
2745 (defun org-babel-process-file-name (name &optional no-quote-p
)
2746 "Prepare NAME to be used in an external process.
2747 If NAME specifies a remote location, the remote portion of the
2748 name is removed, since in that case the process will be executing
2749 remotely. The file name is then processed by `expand-file-name'.
2750 Unless second argument NO-QUOTE-P is non-nil, the file name is
2751 additionally processed by `shell-quote-argument'"
2752 (let ((f (org-babel-local-file-name (expand-file-name name
))))
2753 (if no-quote-p f
(shell-quote-argument f
))))
2755 (defvar org-babel-temporary-directory
)
2756 (unless (or noninteractive
(boundp 'org-babel-temporary-directory
))
2757 (defvar org-babel-temporary-directory
2758 (or (and (boundp 'org-babel-temporary-directory
)
2759 (file-exists-p org-babel-temporary-directory
)
2760 org-babel-temporary-directory
)
2761 (make-temp-file "babel-" t
))
2762 "Directory to hold temporary files created to execute code blocks.
2763 Used by `org-babel-temp-file'. This directory will be removed on
2766 (defcustom org-babel-remote-temporary-directory
"/tmp/"
2767 "Directory to hold temporary files on remote hosts."
2771 (defmacro org-babel-result-cond
(result-params scalar-form
&rest table-forms
)
2772 "Call the code to parse raw string results according to RESULT-PARAMS."
2774 (debug (form form
&rest form
)))
2775 (org-with-gensyms (params)
2776 `(let ((,params
,result-params
))
2777 (unless (member "none" ,params
)
2778 (if (or (member "scalar" ,params
)
2779 (member "verbatim" ,params
)
2780 (member "html" ,params
)
2781 (member "code" ,params
)
2782 (member "pp" ,params
)
2783 (and (or (member "output" ,params
)
2784 (member "raw" ,params
)
2785 (member "org" ,params
)
2786 (member "drawer" ,params
))
2787 (not (member "table" ,params
))))
2790 (def-edebug-spec org-babel-result-cond
(form form body
))
2792 (defun org-babel-temp-file (prefix &optional suffix
)
2793 "Create a temporary file in the `org-babel-temporary-directory'.
2794 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2795 value of `temporary-file-directory' temporarily set to the value
2796 of `org-babel-temporary-directory'."
2797 (if (file-remote-p default-directory
)
2799 (concat (file-remote-p default-directory
)
2801 prefix org-babel-remote-temporary-directory
))))
2802 (make-temp-file prefix nil suffix
))
2803 (let ((temporary-file-directory
2804 (or (and (boundp 'org-babel-temporary-directory
)
2805 (file-exists-p org-babel-temporary-directory
)
2806 org-babel-temporary-directory
)
2807 temporary-file-directory
)))
2808 (make-temp-file prefix nil suffix
))))
2810 (defun org-babel-remove-temporary-directory ()
2811 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2812 (when (and (boundp 'org-babel-temporary-directory
)
2813 (file-exists-p org-babel-temporary-directory
))
2814 ;; taken from `delete-directory' in files.el
2817 (mapc (lambda (file)
2818 ;; This test is equivalent to
2819 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2820 ;; but more efficient
2821 (if (eq t
(car (file-attributes file
)))
2822 (delete-directory file
)
2823 (delete-file file
)))
2824 ;; We do not want to delete "." and "..".
2825 (directory-files org-babel-temporary-directory
'full
2826 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2827 (delete-directory org-babel-temporary-directory
))
2829 (message "Failed to remove temporary Org-babel directory %s"
2830 (if (boundp 'org-babel-temporary-directory
)
2831 org-babel-temporary-directory
2832 "[directory not defined]"))))))
2834 (add-hook 'kill-emacs-hook
'org-babel-remove-temporary-directory
)
2836 (defun org-babel-one-header-arg-safe-p (pair safe-list
)
2837 "Determine if the PAIR is a safe babel header arg according to SAFE-LIST.
2839 For the format of SAFE-LIST, see `org-babel-safe-header-args'."
2841 (keywordp (car pair
))
2842 (stringp (cdr pair
))
2844 (memq (car pair
) safe-list
)
2845 (let ((entry (assq (car pair
) safe-list
)))
2848 (cond ((functionp (cdr entry
))
2849 (funcall (cdr entry
) (cdr pair
)))
2850 ((listp (cdr entry
))
2851 (member (cdr pair
) (cdr entry
)))
2857 ;; generated-autoload-file: "org-loaddefs.el"
2860 ;;; ob-core.el ends here