1 ;;; ob-core.el --- working with code blocks in org-mode
3 ;; Copyright (C) 2009-2014 Free Software Foundation, Inc.
5 ;; Authors: Eric Schulte
7 ;; Keywords: literate programming, reproducible research
8 ;; Homepage: http://orgmode.org
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
32 (defconst org-babel-exeext
33 (if (memq system-type
'(windows-nt cygwin
))
36 ;; dynamically scoped for tramp
37 (defvar org-babel-call-process-region-original nil
)
38 (defvar org-src-lang-modes
)
39 (defvar org-babel-library-of-babel
)
40 (declare-function show-all
"outline" ())
41 (declare-function org-every
"org" (pred seq
))
42 (declare-function org-remove-indentation
"org" (code &optional n
))
43 (declare-function org-reduce
"org" (CL-FUNC CL-SEQ
&rest CL-KEYS
))
44 (declare-function org-mark-ring-push
"org" (&optional pos buffer
))
45 (declare-function tramp-compat-make-temp-file
"tramp-compat"
46 (filename &optional dir-flag
))
47 (declare-function tramp-dissect-file-name
"tramp" (name &optional nodefault
))
48 (declare-function tramp-file-name-user
"tramp" (vec))
49 (declare-function tramp-file-name-host
"tramp" (vec))
50 (declare-function with-parsed-tramp-file-name
"tramp" (filename var
&rest body
))
51 (declare-function org-icompleting-read
"org" (&rest args
))
52 (declare-function org-edit-src-code
"org-src"
53 (&optional context code edit-buffer-name quietp
))
54 (declare-function org-edit-src-exit
"org-src" (&optional context
))
55 (declare-function org-open-at-point
"org" (&optional in-emacs reference-buffer
))
56 (declare-function org-save-outline-visibility
"org-macs" (use-markers &rest body
))
57 (declare-function org-outline-overlay-data
"org" (&optional use-markers
))
58 (declare-function org-set-outline-overlay-data
"org" (data))
59 (declare-function org-narrow-to-subtree
"org" ())
60 (declare-function org-split-string
"org" (string &optional separators
))
61 (declare-function org-entry-get
"org"
62 (pom property
&optional inherit literal-nil
))
63 (declare-function org-make-options-regexp
"org" (kwds &optional extra
))
64 (declare-function org-do-remove-indentation
"org" (&optional n
))
65 (declare-function org-next-block
"org" (arg &optional backward block-regexp
))
66 (declare-function org-previous-block
"org" (arg &optional block-regexp
))
67 (declare-function org-show-context
"org" (&optional key
))
68 (declare-function org-at-table-p
"org" (&optional table-type
))
69 (declare-function org-cycle
"org" (&optional arg
))
70 (declare-function org-uniquify
"org" (list))
71 (declare-function org-current-level
"org" ())
72 (declare-function org-table-import
"org-table" (file arg
))
73 (declare-function org-add-hook
"org-compat"
74 (hook function
&optional append local
))
75 (declare-function org-table-align
"org-table" ())
76 (declare-function org-table-end
"org-table" (&optional table-type
))
77 (declare-function orgtbl-to-generic
"org-table" (table params
))
78 (declare-function orgtbl-to-orgtbl
"org-table" (table params
))
79 (declare-function org-babel-tangle-comment-links
"ob-tangle" (&optional info
))
80 (declare-function org-babel-lob-get-info
"ob-lob" nil
)
81 (declare-function org-babel-ref-split-args
"ob-ref" (arg-string))
82 (declare-function org-babel-ref-parse
"ob-ref" (assignment))
83 (declare-function org-babel-ref-resolve
"ob-ref" (ref))
84 (declare-function org-babel-ref-goto-headline-id
"ob-ref" (id))
85 (declare-function org-babel-ref-headline-body
"ob-ref" ())
86 (declare-function org-babel-lob-execute-maybe
"ob-lob" ())
87 (declare-function org-number-sequence
"org-compat" (from &optional to inc
))
88 (declare-function org-at-item-p
"org-list" ())
89 (declare-function org-list-parse-list
"org-list" (&optional delete
))
90 (declare-function org-list-to-generic
"org-list" (LIST PARAMS
))
91 (declare-function org-list-struct
"org-list" ())
92 (declare-function org-list-prevs-alist
"org-list" (struct))
93 (declare-function org-list-get-list-end
"org-list" (item struct prevs
))
94 (declare-function org-remove-if
"org" (predicate seq
))
95 (declare-function org-completing-read
"org" (&rest args
))
96 (declare-function org-escape-code-in-region
"org-src" (beg end
))
97 (declare-function org-unescape-code-in-string
"org-src" (s))
98 (declare-function org-table-to-lisp
"org-table" (&optional txt
))
99 (declare-function org-reverse-string
"org" (string))
100 (declare-function org-element-context
"org-element" (&optional ELEMENT
))
101 (declare-function org-every
"org" (pred seq
))
103 (defgroup org-babel nil
104 "Code block evaluation and management in `org-mode' documents."
108 (defcustom org-confirm-babel-evaluate t
109 "Confirm before evaluation.
110 Require confirmation before interactively evaluating code
111 blocks in Org-mode buffers. The default value of this variable
112 is t, meaning confirmation is required for any code block
113 evaluation. This variable can be set to nil to inhibit any
114 future confirmation requests. This variable can also be set to a
115 function which takes two arguments the language of the code block
116 and the body of the code block. Such a function should then
117 return a non-nil value if the user should be prompted for
118 execution or nil if no prompt is required.
120 Warning: Disabling confirmation may result in accidental
121 evaluation of potentially harmful code. It may be advisable
122 remove code block execution from C-c C-c as further protection
123 against accidental code block evaluation. The
124 `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
125 remove code block execution from the C-c C-c keybinding."
128 :type
'(choice boolean function
))
129 ;; don't allow this variable to be changed through file settings
130 (put 'org-confirm-babel-evaluate
'safe-local-variable
(lambda (x) (eq x t
)))
132 (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
133 "Remove code block evaluation from the C-c C-c key binding."
138 (defcustom org-babel-results-keyword
"RESULTS"
139 "Keyword used to name results generated by code blocks.
140 Should be either RESULTS or NAME however any capitalization may
144 :package-version
'(Org .
"8.0")
147 (defcustom org-babel-noweb-wrap-start
"<<"
148 "String used to begin a noweb reference in a code block.
149 See also `org-babel-noweb-wrap-end'."
153 (defcustom org-babel-noweb-wrap-end
">>"
154 "String used to end a noweb reference in a code block.
155 See also `org-babel-noweb-wrap-start'."
159 (defcustom org-babel-inline-result-wrap
"=%s="
160 "Format string used to wrap inline results.
161 This string must include a \"%s\" which will be replaced by the results."
164 (put 'org-babel-inline-result-wrap
168 (string-match-p "%s" value
))))
170 (defun org-babel-noweb-wrap (&optional regexp
)
171 (concat org-babel-noweb-wrap-start
172 (or regexp
"\\([^ \t\n].+?[^ \t]\\|[^ \t\n]\\)")
173 org-babel-noweb-wrap-end
))
175 (defvar org-babel-src-name-regexp
176 "^[ \t]*#\\+name:[ \t]*"
177 "Regular expression used to match a source name line.")
179 (defvar org-babel-multi-line-header-regexp
180 "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
181 "Regular expression used to match multi-line header arguments.")
183 (defvar org-babel-src-name-w-name-regexp
184 (concat org-babel-src-name-regexp
186 org-babel-multi-line-header-regexp
188 "\\([^ ()\f\t\n\r\v]+\\)")
189 "Regular expression matching source name lines with a name.")
191 (defvar org-babel-src-block-regexp
193 ;; (1) indentation (2) lang
194 "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
196 "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
197 ;; (4) header arguments
200 "\\([^\000]*?\n\\)??[ \t]*#\\+end_src")
201 "Regexp used to identify code blocks.")
203 (defvar org-babel-inline-src-block-regexp
205 ;; (1) replacement target (2) lang
206 "\\(?:^\\|[^-[:alnum:]]\\)\\(src_\\([^ \f\t\n\r\v]+\\)"
207 ;; (3,4) (unused, headers)
208 "\\(\\|\\[\\(.*?\\)\\]\\)"
210 "{\\([^\f\n\r\v]+?\\)}\\)")
211 "Regexp used to identify inline src-blocks.")
213 (defun org-babel-get-header (params key
&optional others
)
214 "Select only header argument of type KEY from a list.
215 Optional argument OTHERS indicates that only the header that do
216 not match KEY should be returned."
219 (lambda (p) (when (funcall (if others
#'not
#'identity
) (eq (car p
) key
)) p
))
222 (defun org-babel-get-inline-src-block-matches ()
223 "Set match data if within body of an inline source block.
224 Returns non-nil if match-data set"
225 (let ((src-at-0-p (save-excursion
226 (beginning-of-line 1)
227 (string= "src" (thing-at-point 'word
))))
228 (first-line-p (= (line-beginning-position) (point-min)))
230 (let ((search-for (cond ((and src-at-0-p first-line-p
"src_"))
231 (first-line-p "[[:punct:] \t]src_")
232 (t "[[:punct:] \f\t\n\r\v]src_")))
233 (lower-limit (if first-line-p
235 (- (point-at-bol) 1))))
237 (when (or (and src-at-0-p
(bobp))
238 (and (re-search-forward "}" (point-at-eol) t
)
239 (re-search-backward search-for lower-limit t
)
241 (when (looking-at org-babel-inline-src-block-regexp
)
244 (defvar org-babel-inline-lob-one-liner-regexp
)
245 (defun org-babel-get-lob-one-liner-matches ()
246 "Set match data if on line of an lob one liner.
247 Returns non-nil if match-data set"
249 (unless (= (point) (point-at-bol)) ;; move before inline block
250 (re-search-backward "[ \f\t\n\r\v]" nil t
))
251 (if (looking-at org-babel-inline-lob-one-liner-regexp
)
255 (defun org-babel-get-src-block-info (&optional light
)
256 "Get information on the current source block.
258 Optional argument LIGHT does not resolve remote variable
259 references; a process which could likely result in the execution
260 of other code blocks.
263 (language body header-arguments-alist switches name indent block-head)."
264 (let ((case-fold-search t
) head info name indent
)
266 (if (setq head
(org-babel-where-is-src-block-head))
269 (setq info
(org-babel-parse-src-block-match))
270 (setq indent
(car (last info
)))
271 (setq info
(butlast info
))
272 (while (and (forward-line -
1)
273 (looking-at org-babel-multi-line-header-regexp
))
275 (org-babel-merge-params
277 (org-babel-parse-header-arguments (match-string 1)))))
278 (when (looking-at org-babel-src-name-w-name-regexp
)
279 (setq name
(org-no-properties (match-string 3)))))
280 ;; inline source block
281 (when (org-babel-get-inline-src-block-matches)
282 (setq head
(match-beginning 0))
283 (setq info
(org-babel-parse-inline-src-block-match))))
284 ;; resolve variable references and add summary parameters
285 (when (and info
(not light
))
286 (setf (nth 2 info
) (org-babel-process-params (nth 2 info
))))
288 (setf (nth 2 info
) (org-babel-generate-file-param name
(nth 2 info
))))
289 (when info
(append info
(list name indent head
)))))
291 (defvar org-babel-exp-reference-buffer nil
292 "Buffer containing original contents of the exported buffer.
293 This is used by Babel to resolve references in source blocks.
294 Its value is dynamically bound during export.")
296 (defmacro org-babel-check-confirm-evaluate
(info &rest body
)
297 "Evaluate BODY with special execution confirmation variables set.
299 Specifically; NOEVAL will indicate if evaluation is allowed,
300 QUERY will indicate if a user query is required, CODE-BLOCK will
301 hold the language of the code block, and BLOCK-NAME will hold the
302 name of the code block."
303 (declare (indent defun
))
305 (lang block-body headers name head eval eval-no export eval-no-export
)
306 `(let* ((,lang
(nth 0 ,info
))
307 (,block-body
(nth 1 ,info
))
308 (,headers
(nth 2 ,info
))
309 (,name
(nth 4 ,info
))
310 (,head
(nth 6 ,info
))
311 (,eval
(or (cdr (assoc :eval
,headers
))
312 (when (assoc :noeval
,headers
) "no")))
313 (,eval-no
(or (equal ,eval
"no")
314 (equal ,eval
"never")))
315 (,export org-babel-exp-reference-buffer
)
316 (,eval-no-export
(and ,export
(or (equal ,eval
"no-export")
317 (equal ,eval
"never-export"))))
318 (noeval (or ,eval-no
,eval-no-export
))
319 (query (or (equal ,eval
"query")
320 (and ,export
(equal ,eval
"query-export"))
321 (if (functionp org-confirm-babel-evaluate
)
324 (funcall org-confirm-babel-evaluate
326 org-confirm-babel-evaluate
)))
327 (code-block (if ,info
(format " %s " ,lang
) " "))
328 (block-name (if ,name
(format " (%s) " ,name
) " ")))
331 (defsubst org-babel-check-evaluate
(info)
332 "Check if code block INFO should be evaluated.
333 Do not query the user."
334 (org-babel-check-confirm-evaluate info
336 (message (format "Evaluation of this%scode-block%sis disabled."
337 code-block block-name
))))))
339 ;; dynamically scoped for asynchronous export
340 (defvar org-babel-confirm-evaluate-answer-no
)
342 (defsubst org-babel-confirm-evaluate
(info)
343 "Confirm evaluation of the code block INFO.
345 If the variable `org-babel-confirm-evaluate-answer-no' is bound
346 to a non-nil value, auto-answer with \"no\".
348 This query can also be suppressed by setting the value of
349 `org-confirm-babel-evaluate' to nil, in which case all future
350 interactive code block evaluations will proceed without any
351 confirmation from the user.
353 Note disabling confirmation may result in accidental evaluation
354 of potentially harmful code."
355 (org-babel-check-confirm-evaluate info
358 (and (not (org-bound-and-true-p
359 org-babel-confirm-evaluate-answer-no
))
361 (format "Evaluate this%scode block%son your system? "
362 code-block block-name
)))
363 (message (format "Evaluation of this%scode-block%sis aborted."
364 code-block block-name
)))))))
367 (defun org-babel-execute-safely-maybe ()
368 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
369 (org-babel-execute-maybe)))
371 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-execute-safely-maybe
)
374 (defun org-babel-execute-maybe ()
376 (or (org-babel-execute-src-block-maybe)
377 (org-babel-lob-execute-maybe)))
379 (defmacro org-babel-when-in-src-block
(&rest body
)
380 "Execute BODY if point is in a source block and return t.
382 Otherwise do nothing and return nil."
383 `(if (or (org-babel-where-is-src-block-head)
384 (org-babel-get-inline-src-block-matches))
390 (defun org-babel-execute-src-block-maybe ()
391 "Conditionally execute a source block.
392 Detect if this is context for a Babel src-block and if so
393 then run `org-babel-execute-src-block'."
395 (org-babel-when-in-src-block
396 (org-babel-eval-wipe-error-buffer)
397 (org-babel-execute-src-block current-prefix-arg
)))
400 (defun org-babel-view-src-block-info ()
401 "Display information on the current source block.
402 This includes header arguments, language and name, and is largely
403 a window into the `org-babel-get-src-block-info' function."
405 (let ((info (org-babel-get-src-block-info 'light
))
406 (full (lambda (it) (> (length it
) 0)))
407 (printf (lambda (fmt &rest args
) (princ (apply #'format fmt args
)))))
409 (with-help-window (help-buffer)
410 (let ((name (nth 4 info
))
412 (switches (nth 3 info
))
413 (header-args (nth 2 info
)))
414 (when name
(funcall printf
"Name: %s\n" name
))
415 (when lang
(funcall printf
"Lang: %s\n" lang
))
416 (when (funcall full switches
) (funcall printf
"Switches: %s\n" switches
))
417 (funcall printf
"Header Arguments:\n")
418 (dolist (pair (sort header-args
419 (lambda (a b
) (string< (symbol-name (car a
))
420 (symbol-name (car b
))))))
421 (when (funcall full
(cdr pair
))
422 (funcall printf
"\t%S%s\t%s\n"
424 (if (> (length (format "%S" (car pair
))) 7) "" "\t")
428 (defun org-babel-expand-src-block-maybe ()
429 "Conditionally expand a source block.
430 Detect if this is context for a org-babel src-block and if so
431 then run `org-babel-expand-src-block'."
433 (org-babel-when-in-src-block
434 (org-babel-expand-src-block current-prefix-arg
)))
437 (defun org-babel-load-in-session-maybe ()
438 "Conditionally load a source block in a session.
439 Detect if this is context for a org-babel src-block and if so
440 then run `org-babel-load-in-session'."
442 (org-babel-when-in-src-block
443 (org-babel-load-in-session current-prefix-arg
)))
445 (add-hook 'org-metaup-hook
'org-babel-load-in-session-maybe
)
448 (defun org-babel-pop-to-session-maybe ()
449 "Conditionally pop to a session.
450 Detect if this is context for a org-babel src-block and if so
451 then run `org-babel-switch-to-session'."
453 (org-babel-when-in-src-block
454 (org-babel-switch-to-session current-prefix-arg
)))
456 (add-hook 'org-metadown-hook
'org-babel-pop-to-session-maybe
)
458 (defconst org-babel-common-header-args-w-values
459 '((cache .
((no yes
)))
461 (colnames .
((nil no yes
)))
462 (comments .
((no link yes org both noweb
)))
464 (eval .
((never query
)))
465 (exports .
((code results both none
)))
469 (hlines .
((no yes
)))
470 (mkdirp .
((yes no
)))
473 (noweb .
((yes no tangle no-export strip-export
)))
476 (padline .
((yes no
)))
479 (results .
((file list vector table scalar verbatim
)
480 (raw html latex org code pp drawer
)
481 (replace silent none append prepend
)
483 (rownames .
((no yes
)))
487 (tangle .
((tangle yes no
:any
)))
488 (tangle-mode .
((#o755
#o555
#o444
:any
)))
492 (defconst org-babel-header-arg-names
493 (mapcar #'car org-babel-common-header-args-w-values
)
494 "Common header arguments used by org-babel.
495 Note that individual languages may define their own language
496 specific header arguments as well.")
498 (defconst org-babel-safe-header-args
499 '(:cache
:colnames
:comments
:exports
:epilogue
:hlines
:noeval
500 :noweb
:noweb-ref
:noweb-sep
:padline
:prologue
:rownames
501 :sep
:session
:tangle
:wrap
502 (:eval .
("never" "query"))
503 (:results .
(lambda (str) (not (string-match "file" str
)))))
504 "A list of safe header arguments for babel source blocks.
506 The list can have entries of the following forms:
507 - :ARG -> :ARG is always a safe header arg
508 - (:ARG . (VAL1 VAL2 ...)) -> :ARG is safe as a header arg if it is
509 `equal' to one of the VALs.
510 - (:ARG . FN) -> :ARG is safe as a header arg if the function FN
511 returns non-nil. FN is passed one
512 argument, the value of the header arg
515 (defmacro org-babel-header-args-safe-fn
(safe-list)
516 "Return a function that determines whether a list of header args are safe.
519 \(put 'org-babel-default-header-args 'safe-local-variable
520 (org-babel-header-args-safe-p org-babel-safe-header-args)
522 This allows org-babel languages to extend the list of safe values for
523 their `org-babel-default-header-args:foo' variable.
525 For the format of SAFE-LIST, see `org-babel-safe-header-args'."
531 (org-babel-one-header-arg-safe-p pair
,safe-list
)))
534 (defvar org-babel-default-header-args
535 '((:session .
"none") (:results .
"replace") (:exports .
"code")
536 (:cache .
"no") (:noweb .
"no") (:hlines .
"no") (:tangle .
"no"))
537 "Default arguments to use when evaluating a source block.")
538 (put 'org-babel-default-header-args
'safe-local-variable
539 (org-babel-header-args-safe-fn org-babel-safe-header-args
))
541 (defvar org-babel-default-inline-header-args
542 '((:session .
"none") (:results .
"replace")
543 (:exports .
"results") (:hlines .
"yes"))
544 "Default arguments to use when evaluating an inline source block.")
545 (put 'org-babel-default-inline-header-args
'safe-local-variable
546 (org-babel-header-args-safe-fn org-babel-safe-header-args
))
548 (defvar org-babel-data-names
'("tblname" "results" "name"))
550 (defvar org-babel-result-regexp
551 (concat "^[ \t]*#\\+"
552 (regexp-opt org-babel-data-names t
)
554 ;; FIXME The string below is `org-ts-regexp'
555 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
556 " \\)?\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*")
557 "Regular expression used to match result lines.
558 If the results are associated with a hash key then the hash will
559 be saved in the second match data.")
561 (defvar org-babel-result-w-name-regexp
562 (concat org-babel-result-regexp
563 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
565 (defvar org-babel-min-lines-for-block-output
10
566 "The minimum number of lines for block output.
567 If number of lines of output is equal to or exceeds this
568 value, the output is placed in a #+begin_example...#+end_example
569 block. Otherwise the output is marked as literal by inserting
570 colons at the starts of the lines. This variable only takes
571 effect if the :results output option is in effect.")
573 (defvar org-babel-noweb-error-langs nil
574 "Languages for which Babel will raise literate programming errors.
575 List of languages for which errors should be raised when the
576 source code block satisfying a noweb reference in this language
577 can not be resolved.")
579 (defvar org-babel-hash-show
4
580 "Number of initial characters to show of a hidden results hash.")
582 (defvar org-babel-hash-show-time nil
583 "Non-nil means show the time the code block was evaluated in the result hash.")
585 (defvar org-babel-after-execute-hook nil
586 "Hook for functions to be called after `org-babel-execute-src-block'")
588 (defun org-babel-named-src-block-regexp-for-name (name)
589 "This generates a regexp used to match a src block named NAME."
590 (concat org-babel-src-name-regexp
(regexp-quote name
)
591 "[ \t(]*[\r\n]\\(?:^[[:space:]]*#.*[\r\n]\\)*"
592 (substring org-babel-src-block-regexp
1)))
594 (defun org-babel-named-data-regexp-for-name (name)
595 "This generates a regexp used to match data named NAME."
596 (concat org-babel-result-regexp
(regexp-quote name
) "\\([ \t]\\|$\\)"))
599 (defvar call-process-region
)
600 (defvar org-babel-current-src-block-location nil
601 "Marker pointing to the src block currently being executed.
602 This may also point to a call line or an inline code block. If
603 multiple blocks are being executed (e.g., in chained execution
604 through use of the :var header argument) this marker points to
605 the outer-most code block.")
608 (defun org-babel-execute-src-block (&optional arg info params
)
609 "Execute the current source code block.
610 Insert the results of execution into the buffer. Source code
611 execution and the collection and formatting of results can be
612 controlled through a variety of header arguments.
614 With prefix argument ARG, force re-execution even if an existing
615 result cached in the buffer would otherwise have been returned.
617 Optionally supply a value for INFO in the form returned by
618 `org-babel-get-src-block-info'.
620 Optionally supply a value for PARAMS which will be merged with
621 the header arguments specified at the front of the source code
624 (let* ((org-babel-current-src-block-location
625 (or org-babel-current-src-block-location
627 (org-babel-where-is-src-block-head)
629 (and (org-babel-get-inline-src-block-matches)
630 (match-beginning 0))))
633 (org-babel-get-src-block-info)))
634 (merged-params (org-babel-merge-params (nth 2 info
) params
)))
635 (when (org-babel-check-evaluate
636 (let ((i info
)) (setf (nth 2 i
) merged-params
) i
))
637 (let* ((params (if params
638 (org-babel-process-params merged-params
)
640 (cachep (and (not arg
) (cdr (assoc :cache params
))
641 (string= "yes" (cdr (assoc :cache params
)))))
642 (new-hash (when cachep
(org-babel-sha1-hash info
)))
643 (old-hash (when cachep
(org-babel-current-result-hash)))
644 (cache-current-p (and (not arg
) new-hash
645 (equal new-hash old-hash
))))
648 (save-excursion ;; return cached result
649 (goto-char (org-babel-where-is-src-block-result nil info
))
650 (end-of-line 1) (forward-char 1)
651 (let ((result (org-babel-read-result)))
652 (message (replace-regexp-in-string
653 "%" "%%" (format "%S" result
))) result
)))
654 ((org-babel-confirm-evaluate
655 (let ((i info
)) (setf (nth 2 i
) merged-params
) i
))
656 (let* ((lang (nth 0 info
))
657 (result-params (cdr (assoc :result-params params
)))
658 (body (setf (nth 1 info
)
659 (if (org-babel-noweb-p params
:eval
)
660 (org-babel-expand-noweb-references info
)
662 (dir (cdr (assoc :dir params
)))
664 (or (and dir
(file-name-as-directory (expand-file-name dir
)))
666 (org-babel-call-process-region-original ;; for tramp handler
667 (or (org-bound-and-true-p
668 org-babel-call-process-region-original
)
669 (symbol-function 'call-process-region
)))
670 (indent (nth 5 info
))
673 (let ((call-process-region
675 (apply 'org-babel-tramp-handle-call-process-region
679 (let ((f (intern (concat "org-babel-execute:" f
))))
680 (when (fboundp f
) f
)))))
682 (or (funcall lang-check lang
)
685 (cdr (assoc lang org-src-lang-modes
))))
686 (error "No org-babel-execute function for %s!"
688 (message "executing %s code block%s..."
690 (if (nth 4 info
) (format " (%s)" (nth 4 info
)) ""))
691 (if (member "none" result-params
)
693 (funcall cmd body params
)
694 (message "result silenced")
697 (let ((result (funcall cmd body params
)))
698 (if (and (eq (cdr (assoc :result-type params
))
700 (or (member "vector" result-params
)
701 (member "table" result-params
))
702 (not (listp result
)))
703 (list (list result
)) result
)))
704 ;; If non-empty result and :file then write to :file.
705 (when (cdr (assoc :file params
))
707 (with-temp-file (cdr (assoc :file params
))
709 (org-babel-format-result
710 result
(cdr (assoc :sep
(nth 2 info
)))))))
711 (setq result
(cdr (assoc :file params
))))
712 ;; Possibly perform post process provided its appropriate.
713 (when (cdr (assoc :post params
))
714 (let ((*this
* (if (cdr (assoc :file params
))
715 (org-babel-result-to-file
716 (cdr (assoc :file params
))
717 (when (assoc :file-desc params
)
718 (or (cdr (assoc :file-desc params
))
721 (setq result
(org-babel-ref-resolve
722 (cdr (assoc :post params
))))
723 (when (cdr (assoc :file params
))
725 (remove "file" result-params
)))))
726 (org-babel-insert-result
727 result result-params info new-hash indent lang
))
728 (run-hooks 'org-babel-after-execute-hook
)
730 (setq call-process-region
731 'org-babel-call-process-region-original
)))))))))
733 (defun org-babel-expand-body:generic
(body params
&optional var-lines
)
734 "Expand BODY with PARAMS.
735 Expand a block of code with org-babel according to its header
736 arguments. This generic implementation of body expansion is
737 called for languages which have not defined their own specific
738 org-babel-expand-body:lang function."
739 (let ((pro (cdr (assoc :prologue params
)))
740 (epi (cdr (assoc :epilogue params
))))
741 (mapconcat #'identity
742 (append (when pro
(list pro
))
745 (when epi
(list epi
)))
749 (defun org-babel-expand-src-block (&optional arg info params
)
750 "Expand the current source code block.
751 Expand according to the source code block's header
752 arguments and pop open the results in a preview buffer."
754 (let* ((info (or info
(org-babel-get-src-block-info)))
756 (params (setf (nth 2 info
)
757 (sort (org-babel-merge-params (nth 2 info
) params
)
758 (lambda (el1 el2
) (string< (symbol-name (car el1
))
759 (symbol-name (car el2
)))))))
760 (body (setf (nth 1 info
)
761 (if (org-babel-noweb-p params
:eval
)
762 (org-babel-expand-noweb-references info
) (nth 1 info
))))
763 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
764 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
767 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
768 (org-babel-expand-body:generic
769 body params
(and (fboundp assignments-cmd
)
770 (funcall assignments-cmd params
))))))
771 (if (org-called-interactively-p 'any
)
774 (concat "*Org-Babel Preview " (buffer-name) "[ " lang
" ]*"))
777 (defun org-babel-edit-distance (s1 s2
)
778 "Return the edit (levenshtein) distance between strings S1 S2."
779 (let* ((l1 (length s1
))
781 (dist (vconcat (mapcar (lambda (_) (make-vector (1+ l2
) nil
))
782 (number-sequence 1 (1+ l1
)))))
783 (in (lambda (i j
) (aref (aref dist i
) j
))))
784 (setf (aref (aref dist
0) 0) 0)
785 (dolist (j (number-sequence 1 l2
))
786 (setf (aref (aref dist
0) j
) j
))
787 (dolist (i (number-sequence 1 l1
))
788 (setf (aref (aref dist i
) 0) i
)
789 (dolist (j (number-sequence 1 l2
))
790 (setf (aref (aref dist i
) j
)
792 (1+ (funcall in
(1- i
) j
))
793 (1+ (funcall in i
(1- j
)))
794 (+ (if (equal (aref s1
(1- i
)) (aref s2
(1- j
))) 0 1)
795 (funcall in
(1- i
) (1- j
)))))))
798 (defun org-babel-combine-header-arg-lists (original &rest others
)
799 "Combine a number of lists of header argument names and arguments."
800 (let ((results (copy-sequence original
)))
801 (dolist (new-list others
)
802 (dolist (arg-pair new-list
)
803 (let ((header (car arg-pair
))
804 (args (cdr arg-pair
)))
806 (cons arg-pair
(org-remove-if
807 (lambda (pair) (equal header
(car pair
)))
812 (defun org-babel-check-src-block ()
813 "Check for misspelled header arguments in the current code block."
815 ;; TODO: report malformed code block
816 ;; TODO: report incompatible combinations of header arguments
817 ;; TODO: report uninitialized variables
818 (let ((too-close 2) ;; <- control closeness to report potential match
819 (names (mapcar #'symbol-name org-babel-header-arg-names
)))
820 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg
)) 1))
821 (and (org-babel-where-is-src-block-head)
822 (org-babel-parse-header-arguments
824 (match-string 4))))))
826 (when (and (not (string= header name
))
827 (<= (org-babel-edit-distance header name
) too-close
)
828 (not (member header names
)))
829 (error "Supplied header \"%S\" is suspiciously close to \"%S\""
831 (message "No suspicious header arguments found.")))
834 (defun org-babel-insert-header-arg (&optional header-arg value
)
835 "Insert a header argument selecting from lists of common args and values."
837 (let* ((info (org-babel-get-src-block-info 'light
))
840 (lang-headers (intern (concat "org-babel-header-args:" lang
)))
841 (headers (org-babel-combine-header-arg-lists
842 org-babel-common-header-args-w-values
843 (when (boundp lang-headers
) (eval lang-headers
))))
844 (header-arg (or header-arg
845 (org-icompleting-read
848 (lambda (header-spec) (symbol-name (car header-spec
)))
850 (vals (cdr (assoc (intern header-arg
) headers
)))
854 (read-from-minibuffer "value: "))
858 (let ((arg (org-icompleting-read
861 (mapcar #'symbol-name group
)))))
862 (if (and arg
(not (string= "default" arg
)))
868 (goto-char (point-at-eol))
869 (unless (= (char-before (point)) ?\
) (insert " "))
870 (insert ":" header-arg
) (when value
(insert " " value
)))))
872 ;; Add support for completing-read insertion of header arguments after ":"
873 (defun org-babel-header-arg-expand ()
874 "Call `org-babel-enter-header-arg-w-completion' in appropriate contexts."
875 (when (and (equal (char-before) ?\
:) (org-babel-where-is-src-block-head))
876 (org-babel-enter-header-arg-w-completion (match-string 2))))
878 (defun org-babel-enter-header-arg-w-completion (&optional lang
)
879 "Insert header argument appropriate for LANG with completion."
880 (let* ((lang-headers-var (intern (concat "org-babel-header-args:" lang
)))
881 (lang-headers (when (boundp lang-headers-var
) (eval lang-headers-var
)))
882 (headers-w-values (org-babel-combine-header-arg-lists
883 org-babel-common-header-args-w-values lang-headers
))
884 (headers (mapcar #'symbol-name
(mapcar #'car headers-w-values
)))
885 (header (org-completing-read "Header Arg: " headers
))
886 (args (cdr (assoc (intern header
) headers-w-values
)))
887 (arg (when (and args
(listp args
))
889 (format "%s: " header
)
890 (mapcar #'symbol-name
(apply #'append args
))))))
891 (insert (concat header
" " (or arg
"")))
894 (add-hook 'org-tab-first-hook
'org-babel-header-arg-expand
)
897 (defun org-babel-load-in-session (&optional arg info
)
898 "Load the body of the current source-code block.
899 Evaluate the header arguments for the source block before
900 entering the session. After loading the body this pops open the
903 (let* ((info (or info
(org-babel-get-src-block-info)))
905 (params (nth 2 info
))
907 (user-error "No src code block at point")
909 (if (org-babel-noweb-p params
:eval
)
910 (org-babel-expand-noweb-references info
)
912 (session (cdr (assoc :session params
)))
913 (dir (cdr (assoc :dir params
)))
915 (or (and dir
(file-name-as-directory dir
)) default-directory
))
916 (cmd (intern (concat "org-babel-load-session:" lang
))))
917 (unless (fboundp cmd
)
918 (error "No org-babel-load-session function for %s!" lang
))
919 (pop-to-buffer (funcall cmd session body params
))
923 (defun org-babel-initiate-session (&optional arg info
)
924 "Initiate session for current code block.
925 If called with a prefix argument then resolve any variable
926 references in the header arguments and assign these variables in
927 the session. Copy the body of the code block to the kill ring."
929 (let* ((info (or info
(org-babel-get-src-block-info (not arg
))))
932 (params (nth 2 info
))
933 (session (cdr (assoc :session params
)))
934 (dir (cdr (assoc :dir params
)))
936 (or (and dir
(file-name-as-directory dir
)) default-directory
))
937 (init-cmd (intern (format "org-babel-%s-initiate-session" lang
)))
938 (prep-cmd (intern (concat "org-babel-prep-session:" lang
))))
939 (if (and (stringp session
) (string= session
"none"))
940 (error "This block is not using a session!"))
941 (unless (fboundp init-cmd
)
942 (error "No org-babel-initiate-session function for %s!" lang
))
943 (with-temp-buffer (insert (org-babel-trim body
))
944 (copy-region-as-kill (point-min) (point-max)))
946 (unless (fboundp prep-cmd
)
947 (error "No org-babel-prep-session function for %s!" lang
))
948 (funcall prep-cmd session params
))
949 (funcall init-cmd session params
)))
952 (defun org-babel-switch-to-session (&optional arg info
)
953 "Switch to the session of the current code block.
954 Uses `org-babel-initiate-session' to start the session. If called
955 with a prefix argument then this is passed on to
956 `org-babel-initiate-session'."
958 (pop-to-buffer (org-babel-initiate-session arg info
))
961 (defalias 'org-babel-pop-to-session
'org-babel-switch-to-session
)
963 (defvar org-src-window-setup
)
966 (defun org-babel-switch-to-session-with-code (&optional arg info
)
967 "Switch to code buffer and display session."
971 (let ((other-window-buffer (window-buffer (next-window))))
972 (set-window-buffer (next-window) (current-buffer))
973 (set-window-buffer (selected-window) other-window-buffer
))
975 (info (org-babel-get-src-block-info))
976 (org-src-window-setup 'reorganize-frame
))
978 (org-babel-switch-to-session arg info
))
980 (funcall swap-windows
)))
983 (defmacro org-babel-do-in-edit-buffer
(&rest body
)
984 "Evaluate BODY in edit buffer if there is a code block at point.
985 Return t if a code block was found at point, nil otherwise."
986 `(let ((org-src-window-setup 'switch-invisibly
))
987 (when (and (org-babel-where-is-src-block-head)
989 (unwind-protect (progn ,@body
)
990 (if (org-bound-and-true-p org-edit-src-from-org-mode
)
991 (org-edit-src-exit)))
993 (def-edebug-spec org-babel-do-in-edit-buffer
(body))
995 (defun org-babel-do-key-sequence-in-edit-buffer (key)
996 "Read key sequence and execute the command in edit buffer.
997 Enter a key sequence to be executed in the language major-mode
998 edit buffer. For example, TAB will alter the contents of the
999 Org-mode code block according to the effect of TAB in the
1000 language major-mode buffer. For languages that support
1001 interactive sessions, this can be used to send code from the Org
1002 buffer to the session for evaluation using the native major-mode
1003 evaluation mechanisms."
1004 (interactive "kEnter key-sequence to execute in edit buffer: ")
1005 (org-babel-do-in-edit-buffer
1007 (key-binding (or key
(read-key-sequence nil
))))))
1009 (defvar org-bracket-link-regexp
)
1011 (defun org-babel-active-location-p ()
1012 (memq (car (save-match-data (org-element-context)))
1013 '(babel-call inline-babel-call inline-src-block src-block
)))
1016 (defun org-babel-open-src-block-result (&optional re-run
)
1017 "If `point' is on a src block then open the results of the
1018 source code block, otherwise return nil. With optional prefix
1019 argument RE-RUN the source-code block is evaluated even if
1020 results already exist."
1022 (let ((info (org-babel-get-src-block-info 'light
)))
1025 ;; go to the results, if there aren't any then run the block
1026 (goto-char (or (and (not re-run
) (org-babel-where-is-src-block-result))
1027 (progn (org-babel-execute-src-block)
1028 (org-babel-where-is-src-block-result))))
1030 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
1032 (if (looking-at org-bracket-link-regexp
)
1035 (let ((r (org-babel-format-result
1036 (org-babel-read-result) (cdr (assoc :sep
(nth 2 info
))))))
1037 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
1038 (delete-region (point-min) (point-max))
1043 (defmacro org-babel-map-src-blocks
(file &rest body
)
1044 "Evaluate BODY forms on each source-block in FILE.
1045 If FILE is nil evaluate BODY forms on source blocks in current
1046 buffer. During evaluation of BODY the following local variables
1047 are set relative to the currently matched code block.
1049 full-block ------- string holding the entirety of the code block
1050 beg-block -------- point at the beginning of the code block
1051 end-block -------- point at the end of the matched code block
1052 lang ------------- string holding the language of the code block
1053 beg-lang --------- point at the beginning of the lang
1054 end-lang --------- point at the end of the lang
1055 switches --------- string holding the switches
1056 beg-switches ----- point at the beginning of the switches
1057 end-switches ----- point at the end of the switches
1058 header-args ------ string holding the header-args
1059 beg-header-args -- point at the beginning of the header-args
1060 end-header-args -- point at the end of the header-args
1061 body ------------- string holding the body of the code block
1062 beg-body --------- point at the beginning of the body
1063 end-body --------- point at the end of the body"
1064 (declare (indent 1))
1065 (let ((tempvar (make-symbol "file")))
1066 `(let* ((,tempvar
,file
)
1067 (visited-p (or (null ,tempvar
)
1068 (get-file-buffer (expand-file-name ,tempvar
))))
1069 (point (point)) to-be-removed
)
1070 (save-window-excursion
1071 (when ,tempvar
(find-file ,tempvar
))
1072 (setq to-be-removed
(current-buffer))
1073 (goto-char (point-min))
1074 (while (re-search-forward org-babel-src-block-regexp nil t
)
1075 (when (org-babel-active-location-p)
1076 (goto-char (match-beginning 0))
1077 (let ((full-block (match-string 0))
1078 (beg-block (match-beginning 0))
1079 (end-block (match-end 0))
1080 (lang (match-string 2))
1081 (beg-lang (match-beginning 2))
1082 (end-lang (match-end 2))
1083 (switches (match-string 3))
1084 (beg-switches (match-beginning 3))
1085 (end-switches (match-end 3))
1086 (header-args (match-string 4))
1087 (beg-header-args (match-beginning 4))
1088 (end-header-args (match-end 4))
1089 (body (match-string 5))
1090 (beg-body (match-beginning 5))
1091 (end-body (match-end 5)))
1093 (goto-char end-block
)))))
1094 (unless visited-p
(kill-buffer to-be-removed
))
1095 (goto-char point
))))
1096 (def-edebug-spec org-babel-map-src-blocks
(form body
))
1099 (defmacro org-babel-map-inline-src-blocks
(file &rest body
)
1100 "Evaluate BODY forms on each inline source-block in FILE.
1101 If FILE is nil evaluate BODY forms on source blocks in current
1103 (declare (indent 1))
1104 (let ((tempvar (make-symbol "file")))
1105 `(let* ((,tempvar
,file
)
1106 (visited-p (or (null ,tempvar
)
1107 (get-file-buffer (expand-file-name ,tempvar
))))
1108 (point (point)) to-be-removed
)
1109 (save-window-excursion
1110 (when ,tempvar
(find-file ,tempvar
))
1111 (setq to-be-removed
(current-buffer))
1112 (goto-char (point-min))
1113 (while (re-search-forward org-babel-inline-src-block-regexp nil t
)
1114 (when (org-babel-active-location-p)
1115 (goto-char (match-beginning 1))
1116 (save-match-data ,@body
))
1117 (goto-char (match-end 0))))
1118 (unless visited-p
(kill-buffer to-be-removed
))
1119 (goto-char point
))))
1120 (def-edebug-spec org-babel-map-inline-src-blocks
(form body
))
1122 (defvar org-babel-lob-one-liner-regexp
)
1125 (defmacro org-babel-map-call-lines
(file &rest body
)
1126 "Evaluate BODY forms on each call line in FILE.
1127 If FILE is nil evaluate BODY forms on source blocks in current
1129 (declare (indent 1))
1130 (let ((tempvar (make-symbol "file")))
1131 `(let* ((,tempvar
,file
)
1132 (visited-p (or (null ,tempvar
)
1133 (get-file-buffer (expand-file-name ,tempvar
))))
1134 (point (point)) to-be-removed
)
1135 (save-window-excursion
1136 (when ,tempvar
(find-file ,tempvar
))
1137 (setq to-be-removed
(current-buffer))
1138 (goto-char (point-min))
1139 (while (re-search-forward org-babel-lob-one-liner-regexp nil t
)
1140 (when (org-babel-active-location-p)
1141 (goto-char (match-beginning 1))
1142 (save-match-data ,@body
))
1143 (goto-char (match-end 0))))
1144 (unless visited-p
(kill-buffer to-be-removed
))
1145 (goto-char point
))))
1146 (def-edebug-spec org-babel-map-call-lines
(form body
))
1149 (defmacro org-babel-map-executables
(file &rest body
)
1150 (declare (indent 1))
1151 (let ((tempvar (make-symbol "file"))
1152 (rx (make-symbol "rx")))
1153 `(let* ((,tempvar
,file
)
1154 (,rx
(concat "\\(" org-babel-src-block-regexp
1155 "\\|" org-babel-inline-src-block-regexp
1156 "\\|" org-babel-lob-one-liner-regexp
"\\)"))
1157 (visited-p (or (null ,tempvar
)
1158 (get-file-buffer (expand-file-name ,tempvar
))))
1159 (point (point)) to-be-removed
)
1160 (save-window-excursion
1161 (when ,tempvar
(find-file ,tempvar
))
1162 (setq to-be-removed
(current-buffer))
1163 (goto-char (point-min))
1164 (while (re-search-forward ,rx nil t
)
1165 (when (org-babel-active-location-p)
1166 (goto-char (match-beginning 1))
1167 (when (looking-at org-babel-inline-src-block-regexp
)
1169 (save-match-data ,@body
))
1170 (goto-char (match-end 0))))
1171 (unless visited-p
(kill-buffer to-be-removed
))
1172 (goto-char point
))))
1173 (def-edebug-spec org-babel-map-executables
(form body
))
1176 (defun org-babel-execute-buffer (&optional arg
)
1177 "Execute source code blocks in a buffer.
1178 Call `org-babel-execute-src-block' on every source block in
1179 the current buffer."
1181 (org-babel-eval-wipe-error-buffer)
1182 (org-save-outline-visibility t
1183 (org-babel-map-executables nil
1184 (if (looking-at org-babel-lob-one-liner-regexp
)
1185 (org-babel-lob-execute-maybe)
1186 (org-babel-execute-src-block arg
)))))
1189 (defun org-babel-execute-subtree (&optional arg
)
1190 "Execute source code blocks in a subtree.
1191 Call `org-babel-execute-src-block' on every source block in
1192 the current subtree."
1196 (org-narrow-to-subtree)
1197 (org-babel-execute-buffer arg
)
1201 (defun org-babel-sha1-hash (&optional info
)
1202 "Generate an sha1 hash based on the value of info."
1204 (let ((print-level nil
)
1205 (info (or info
(org-babel-get-src-block-info))))
1207 (sort (copy-sequence (nth 2 info
))
1208 (lambda (a b
) (string< (car a
) (car b
)))))
1209 (let* ((rm (lambda (lst)
1210 (dolist (p '("replace" "silent" "none"
1211 "append" "prepend"))
1212 (setq lst
(remove p lst
)))
1215 (let ((v (if (and (listp (cdr arg
)) (null (cddr arg
)))
1216 (copy-sequence (cdr arg
))
1218 (when (and v
(not (and (sequencep v
)
1222 ((and (listp v
) ; lists are sorted
1223 (member (car arg
) '(:result-params
)))
1224 (sort (funcall rm v
) #'string
<))
1225 ((and (stringp v
) ; strings are sorted
1226 (member (car arg
) '(:results
:exports
)))
1227 (mapconcat #'identity
(sort (funcall rm
(split-string v
))
1232 (params (nth 2 info
))
1233 (body (if (org-babel-noweb-p params
:eval
)
1234 (org-babel-expand-noweb-references info
) (nth 1 info
)))
1235 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
1236 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
1239 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
1240 (org-babel-expand-body:generic
1241 body params
(and (fboundp assignments-cmd
)
1242 (funcall assignments-cmd params
))))))
1243 (let* ((it (format "%s-%s"
1246 (delq nil
(mapcar (lambda (arg)
1247 (let ((normalized (funcall norm arg
)))
1249 (format "%S" normalized
))))
1253 (when (org-called-interactively-p 'interactive
) (message hash
))
1256 (defun org-babel-current-result-hash (&optional info
)
1257 "Return the current in-buffer hash."
1258 (org-babel-where-is-src-block-result nil info
)
1259 (org-no-properties (match-string 5)))
1261 (defun org-babel-set-current-result-hash (hash info
)
1262 "Set the current in-buffer hash to HASH."
1263 (org-babel-where-is-src-block-result nil info
)
1264 (save-excursion (goto-char (match-beginning 5))
1265 (mapc #'delete-overlay
(overlays-at (point)))
1266 (forward-char org-babel-hash-show
)
1267 (mapc #'delete-overlay
(overlays-at (point)))
1268 (replace-match hash nil nil nil
5)
1269 (goto-char (point-at-bol))
1270 (org-babel-hide-hash)))
1272 (defun org-babel-hide-hash ()
1273 "Hide the hash in the current results line.
1274 Only the initial `org-babel-hash-show' characters of the hash
1275 will remain visible."
1276 (add-to-invisibility-spec '(org-babel-hide-hash . t
))
1278 (when (and (re-search-forward org-babel-result-regexp nil t
)
1280 (let* ((start (match-beginning 5))
1281 (hide-start (+ org-babel-hash-show start
))
1283 (hash (match-string 5))
1285 (setq ov1
(make-overlay start hide-start
))
1286 (setq ov2
(make-overlay hide-start end
))
1287 (overlay-put ov2
'invisible
'org-babel-hide-hash
)
1288 (overlay-put ov1
'babel-hash hash
)))))
1290 (defun org-babel-hide-all-hashes ()
1291 "Hide the hash in the current buffer.
1292 Only the initial `org-babel-hash-show' characters of each hash
1293 will remain visible. This function should be called as part of
1294 the `org-mode-hook'."
1296 (while (and (not org-babel-hash-show-time
)
1297 (re-search-forward org-babel-result-regexp nil t
))
1298 (goto-char (match-beginning 0))
1299 (org-babel-hide-hash)
1300 (goto-char (match-end 0)))))
1301 (add-hook 'org-mode-hook
'org-babel-hide-all-hashes
)
1303 (defun org-babel-hash-at-point (&optional point
)
1304 "Return the value of the hash at POINT.
1305 The hash is also added as the last element of the kill ring.
1306 This can be called with C-c C-c."
1308 (let ((hash (car (delq nil
(mapcar
1309 (lambda (ol) (overlay-get ol
'babel-hash
))
1310 (overlays-at (or point
(point))))))))
1311 (when hash
(kill-new hash
) (message hash
))))
1312 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-hash-at-point
)
1314 (defun org-babel-result-hide-spec ()
1315 "Hide portions of results lines.
1316 Add `org-babel-hide-result' as an invisibility spec for hiding
1317 portions of results lines."
1318 (add-to-invisibility-spec '(org-babel-hide-result . t
)))
1319 (add-hook 'org-mode-hook
'org-babel-result-hide-spec
)
1321 (defvar org-babel-hide-result-overlays nil
1322 "Overlays hiding results.")
1324 (defun org-babel-result-hide-all ()
1325 "Fold all results in the current buffer."
1327 (org-babel-show-result-all)
1329 (while (re-search-forward org-babel-result-regexp nil t
)
1330 (save-excursion (goto-char (match-beginning 0))
1331 (org-babel-hide-result-toggle-maybe)))))
1333 (defun org-babel-show-result-all ()
1334 "Unfold all results in the current buffer."
1335 (mapc 'delete-overlay org-babel-hide-result-overlays
)
1336 (setq org-babel-hide-result-overlays nil
))
1339 (defun org-babel-hide-result-toggle-maybe ()
1340 "Toggle visibility of result at point."
1342 (let ((case-fold-search t
))
1344 (beginning-of-line 1)
1345 (looking-at org-babel-result-regexp
))
1346 (progn (org-babel-hide-result-toggle)
1347 t
) ;; to signal that we took action
1348 nil
))) ;; to signal that we did not
1350 (defun org-babel-hide-result-toggle (&optional force
)
1351 "Toggle the visibility of the current result."
1355 (if (re-search-forward org-babel-result-regexp nil t
)
1356 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
1358 (while (looking-at org-babel-multi-line-header-regexp
)
1360 (goto-char (- (org-babel-result-end) 1)) (point)))
1362 (if (memq t
(mapcar (lambda (overlay)
1363 (eq (overlay-get overlay
'invisible
)
1364 'org-babel-hide-result
))
1365 (overlays-at start
)))
1366 (if (or (not force
) (eq force
'off
))
1368 (when (member ov org-babel-hide-result-overlays
)
1369 (setq org-babel-hide-result-overlays
1370 (delq ov org-babel-hide-result-overlays
)))
1371 (when (eq (overlay-get ov
'invisible
)
1372 'org-babel-hide-result
)
1373 (delete-overlay ov
)))
1374 (overlays-at start
)))
1375 (setq ov
(make-overlay start end
))
1376 (overlay-put ov
'invisible
'org-babel-hide-result
)
1377 ;; make the block accessible to isearch
1379 ov
'isearch-open-invisible
1381 (when (member ov org-babel-hide-result-overlays
)
1382 (setq org-babel-hide-result-overlays
1383 (delq ov org-babel-hide-result-overlays
)))
1384 (when (eq (overlay-get ov
'invisible
)
1385 'org-babel-hide-result
)
1386 (delete-overlay ov
))))
1387 (push ov org-babel-hide-result-overlays
)))
1388 (error "Not looking at a result line"))))
1390 ;; org-tab-after-check-for-cycling-hook
1391 (add-hook 'org-tab-first-hook
'org-babel-hide-result-toggle-maybe
)
1392 ;; Remove overlays when changing major mode
1393 (add-hook 'org-mode-hook
1394 (lambda () (org-add-hook 'change-major-mode-hook
1395 'org-babel-show-result-all
'append
'local
)))
1397 (defvar org-file-properties
)
1398 (defun org-babel-params-from-properties (&optional lang
)
1399 "Retrieve parameters specified as properties.
1400 Return a list of association lists of source block params
1401 specified in the properties of the current outline entry."
1404 ;; DEPRECATED header arguments specified as separate property at
1405 ;; point of definition
1407 (org-babel-parse-multiple-vars
1410 (lambda (header-arg)
1411 (and (setq val
(org-entry-get (point) header-arg t
))
1412 (cons (intern (concat ":" header-arg
))
1413 (org-babel-read val
))))
1418 (org-babel-combine-header-arg-lists
1419 org-babel-common-header-args-w-values
1421 (setq sym
(intern (concat "org-babel-header-args:" lang
)))
1422 (and (boundp sym
) (eval sym
))))))))))
1423 ;; header arguments specified with the header-args property at
1425 (org-babel-parse-header-arguments
1426 (org-entry-get org-babel-current-src-block-location
1427 "header-args" 'inherit
))
1428 (when lang
;; language-specific header arguments at point of call
1429 (org-babel-parse-header-arguments
1430 (org-entry-get org-babel-current-src-block-location
1431 (concat "header-args:" lang
) 'inherit
))))))
1433 (defvar org-src-preserve-indentation
) ;; declare defcustom from org-src
1434 (defun org-babel-parse-src-block-match ()
1435 "Parse the results from a match of the `org-babel-src-block-regexp'."
1436 (let* ((block-indentation (length (match-string 1)))
1437 (lang (org-no-properties (match-string 2)))
1438 (lang-headers (intern (concat "org-babel-default-header-args:" lang
)))
1439 (switches (match-string 3))
1440 (body (org-no-properties
1441 (let* ((body (match-string 5))
1442 (sub-length (- (length body
) 1)))
1443 (if (and (> sub-length
0)
1444 (string= "\n" (substring body sub-length
)))
1445 (substring body
0 sub-length
)
1447 (preserve-indentation (or org-src-preserve-indentation
1449 (string-match "-i\\>" switches
)))))
1451 ;; get block body less properties, protective commas, and indentation
1454 (insert (org-unescape-code-in-string body
))
1455 (unless preserve-indentation
(org-do-remove-indentation))
1457 (apply #'org-babel-merge-params
1458 org-babel-default-header-args
1459 (when (boundp lang-headers
) (eval lang-headers
))
1461 (org-babel-params-from-properties lang
)
1462 (list (org-babel-parse-header-arguments
1463 (org-no-properties (or (match-string 4) ""))))))
1465 block-indentation
)))
1467 (defun org-babel-parse-inline-src-block-match ()
1468 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
1469 (let* ((lang (org-no-properties (match-string 2)))
1470 (lang-headers (intern (concat "org-babel-default-header-args:" lang
))))
1472 (org-unescape-code-in-string (org-no-properties (match-string 5)))
1473 (apply #'org-babel-merge-params
1474 org-babel-default-inline-header-args
1475 (if (boundp lang-headers
) (eval lang-headers
) nil
)
1477 (org-babel-params-from-properties lang
)
1478 (list (org-babel-parse-header-arguments
1479 (org-no-properties (or (match-string 4) ""))))))
1482 (defun org-babel-balanced-split (string alts
)
1483 "Split STRING on instances of ALTS.
1484 ALTS is a cons of two character options where each option may be
1485 either the numeric code of a single character or a list of
1486 character alternatives. For example to split on balanced
1487 instances of \"[ \t]:\" set ALTS to '((32 9) . 58)."
1488 (let* ((matches (lambda (ch spec
) (if (listp spec
) (member ch spec
) (equal spec ch
))))
1489 (matched (lambda (ch last
)
1491 (and (funcall matches ch
(cdr alts
))
1492 (funcall matches last
(car alts
)))
1493 (funcall matches ch alts
))))
1494 (balance 0) (last 0)
1496 (mapc (lambda (ch) ; split on [], (), "" balanced instances of [ \t]:
1497 (setq balance
(+ balance
1498 (cond ((or (equal 91 ch
) (equal 40 ch
)) 1)
1499 ((or (equal 93 ch
) (equal 41 ch
)) -
1)
1501 (when (and (equal 34 ch
) (not (equal 92 last
)))
1502 (setq quote
(not quote
)))
1503 (setq partial
(cons ch partial
))
1504 (when (and (= balance
0) (not quote
) (funcall matched ch last
))
1505 (setq lst
(cons (apply #'string
(nreverse
1512 (string-to-list string
))
1513 (nreverse (cons (apply #'string
(nreverse partial
)) lst
))))
1515 (defun org-babel-join-splits-near-ch (ch list
)
1516 "Join splits where \"=\" is on either end of the split."
1517 (let ((last= (lambda (str) (= ch
(aref str
(1- (length str
))))))
1518 (first= (lambda (str) (= ch
(aref str
0)))))
1520 (org-reduce (lambda (acc el
)
1521 (let ((head (car acc
)))
1522 (if (and head
(or (funcall last
= head
) (funcall first
= el
)))
1523 (cons (concat head el
) (cdr acc
))
1525 list
:initial-value nil
))))
1527 (defun org-babel-parse-header-arguments (arg-string)
1528 "Parse a string of header arguments returning an alist."
1529 (when (> (length arg-string
) 0)
1530 (org-babel-parse-multiple-vars
1535 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1537 (cons (intern (match-string 1 arg
))
1538 (org-babel-read (org-babel-chomp (match-string 2 arg
))))
1539 (cons (intern (org-babel-chomp arg
)) nil
)))
1540 (let ((raw (org-babel-balanced-split arg-string
'((32 9) .
58))))
1541 (cons (car raw
) (mapcar (lambda (r) (concat ":" r
)) (cdr raw
)))))))))
1543 (defun org-babel-parse-multiple-vars (header-arguments)
1544 "Expand multiple variable assignments behind a single :var keyword.
1546 This allows expression of multiple variables with one :var as
1549 #+PROPERTY: var foo=1, bar=2"
1551 (mapc (lambda (pair)
1552 (if (eq (car pair
) :var
)
1553 (mapcar (lambda (v) (push (cons :var
(org-babel-trim v
)) results
))
1554 (org-babel-join-splits-near-ch
1555 61 (org-babel-balanced-split (cdr pair
) 32)))
1556 (push pair results
)))
1558 (nreverse results
)))
1560 (defun org-babel-process-params (params)
1561 "Expand variables in PARAMS and add summary parameters."
1562 (let* ((processed-vars (mapcar (lambda (el)
1563 (if (consp (cdr el
))
1565 (org-babel-ref-parse (cdr el
))))
1566 (org-babel-get-header params
:var
)))
1567 (vars-and-names (if (and (assoc :colname-names params
)
1568 (assoc :rowname-names params
))
1569 (list processed-vars
)
1570 (org-babel-disassemble-tables
1572 (cdr (assoc :hlines params
))
1573 (cdr (assoc :colnames params
))
1574 (cdr (assoc :rownames params
)))))
1575 (raw-result (or (cdr (assoc :results params
)) ""))
1576 (result-params (append
1577 (split-string (if (stringp raw-result
)
1580 (cdr (assoc :result-params params
)))))
1582 (mapcar (lambda (var) (cons :var var
)) (car vars-and-names
))
1584 (cons :colname-names
(or (cdr (assoc :colname-names params
))
1585 (cadr vars-and-names
)))
1586 (cons :rowname-names
(or (cdr (assoc :rowname-names params
))
1587 (caddr vars-and-names
)))
1588 (cons :result-params result-params
)
1589 (cons :result-type
(cond ((member "output" result-params
) 'output
)
1590 ((member "value" result-params
) 'value
)
1592 (org-babel-get-header params
:var
'other
))))
1594 ;; row and column names
1595 (defun org-babel-del-hlines (table)
1596 "Remove all 'hlines from TABLE."
1597 (remq 'hline table
))
1599 (defun org-babel-get-colnames (table)
1600 "Return the column names of TABLE.
1601 Return a cons cell, the `car' of which contains the TABLE less
1602 colnames, and the `cdr' of which contains a list of the column
1604 (if (equal 'hline
(nth 1 table
))
1605 (cons (cddr table
) (car table
))
1606 (cons (cdr table
) (car table
))))
1608 (defun org-babel-get-rownames (table)
1609 "Return the row names of TABLE.
1610 Return a cons cell, the `car' of which contains the TABLE less
1611 rownames, and the `cdr' of which contains a list of the rownames.
1612 Note: this function removes any hlines in TABLE."
1613 (let* ((table (org-babel-del-hlines table
))
1614 (rownames (funcall (lambda ()
1620 (setq tp
(cdr tp
))))
1622 (cons table rownames
)))
1624 (defun org-babel-put-colnames (table colnames
)
1625 "Add COLNAMES to TABLE if they exist."
1626 (if colnames
(apply 'list colnames
'hline table
) table
))
1628 (defun org-babel-put-rownames (table rownames
)
1629 "Add ROWNAMES to TABLE if they exist."
1631 (mapcar (lambda (row)
1633 (cons (or (pop rownames
) "") row
)
1637 (defun org-babel-pick-name (names selector
)
1638 "Select one out of an alist of row or column names.
1639 SELECTOR can be either a list of names in which case those names
1640 will be returned directly, or an index into the list NAMES in
1641 which case the indexed names will be return."
1642 (if (listp selector
)
1645 (if (and selector
(symbolp selector
) (not (equal t selector
)))
1646 (cdr (assoc selector names
))
1647 (if (integerp selector
)
1648 (nth (- selector
1) names
)
1649 (cdr (car (last names
))))))))
1651 (defun org-babel-disassemble-tables (vars hlines colnames rownames
)
1652 "Parse tables for further processing.
1653 Process the variables in VARS according to the HLINES,
1654 ROWNAMES and COLNAMES header arguments. Return a list consisting
1655 of the vars, cnames and rnames."
1656 (let (cnames rnames
)
1660 (when (listp (cdr var
))
1661 (when (and (not (equal colnames
"no"))
1662 (or colnames
(and (equal (nth 1 (cdr var
)) 'hline
)
1663 (not (member 'hline
(cddr (cdr var
)))))))
1664 (let ((both (org-babel-get-colnames (cdr var
))))
1665 (setq cnames
(cons (cons (car var
) (cdr both
))
1667 (setq var
(cons (car var
) (car both
)))))
1668 (when (and rownames
(not (equal rownames
"no")))
1669 (let ((both (org-babel-get-rownames (cdr var
))))
1670 (setq rnames
(cons (cons (car var
) (cdr both
))
1672 (setq var
(cons (car var
) (car both
)))))
1673 (when (and hlines
(not (equal hlines
"yes")))
1674 (setq var
(cons (car var
) (org-babel-del-hlines (cdr var
))))))
1677 (reverse cnames
) (reverse rnames
))))
1679 (defun org-babel-reassemble-table (table colnames rownames
)
1680 "Add column and row names to a table.
1681 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1682 to the table for reinsertion to org-mode."
1684 (let ((table (if (and rownames
(= (length table
) (length rownames
)))
1685 (org-babel-put-rownames table rownames
) table
)))
1686 (if (and colnames
(listp (car table
)) (= (length (car table
))
1688 (org-babel-put-colnames table colnames
) table
))
1691 (defun org-babel-where-is-src-block-head ()
1692 "Find where the current source block begins.
1693 Return the point at the beginning of the current source
1694 block. Specifically at the beginning of the #+BEGIN_SRC line.
1695 If the point is not on a source block then return nil."
1696 (let ((initial (point)) (case-fold-search t
) top bottom
)
1698 (save-excursion ;; on a source name line or a #+header line
1699 (beginning-of-line 1)
1700 (and (or (looking-at org-babel-src-name-regexp
)
1701 (looking-at org-babel-multi-line-header-regexp
))
1703 (while (and (forward-line 1)
1704 (or (looking-at org-babel-src-name-regexp
)
1705 (looking-at org-babel-multi-line-header-regexp
))))
1706 (looking-at org-babel-src-block-regexp
))
1708 (save-excursion ;; on a #+begin_src line
1709 (beginning-of-line 1)
1710 (and (looking-at org-babel-src-block-regexp
)
1712 (save-excursion ;; inside a src block
1714 (re-search-backward "^[ \t]*#\\+begin_src" nil t
) (setq top
(point))
1715 (re-search-forward "^[ \t]*#\\+end_src" nil t
) (setq bottom
(point))
1716 (< top initial
) (< initial bottom
)
1717 (progn (goto-char top
) (beginning-of-line 1)
1718 (looking-at org-babel-src-block-regexp
))
1722 (defun org-babel-goto-src-block-head ()
1723 "Go to the beginning of the current code block."
1725 (let ((head (org-babel-where-is-src-block-head)))
1726 (if head
(goto-char head
) (error "Not currently in a code block"))))
1729 (defun org-babel-goto-named-src-block (name)
1730 "Go to a named source-code block."
1732 (let ((completion-ignore-case t
)
1733 (case-fold-search t
)
1734 (under-point (thing-at-point 'line
)))
1735 (list (org-icompleting-read
1736 "source-block name: " (org-babel-src-block-names) nil t
1739 ((string-match (org-babel-noweb-wrap) under-point
)
1740 (let ((block-name (match-string 1 under-point
)))
1741 (string-match "[^(]*" block-name
)
1742 (match-string 0 block-name
)))
1744 ((string-match org-babel-lob-one-liner-regexp under-point
)
1745 (let ((source-info (car (org-babel-lob-get-info))))
1746 (if (string-match "^\\([^\\[]+?\\)\\(\\[.*\\]\\)?(" source-info
)
1747 (let ((source-name (match-string 1 source-info
)))
1750 ((string-match (concat "#\\+" org-babel-results-keyword
1751 "\\:\s+\\([^\\(]*\\)") under-point
)
1752 (match-string 1 under-point
))
1754 ((and (thing-at-point 'symbol
))
1755 (org-babel-find-named-block (thing-at-point 'symbol
))
1756 (thing-at-point 'symbol
))
1758 (let ((point (org-babel-find-named-block name
)))
1760 ;; taken from `org-open-at-point'
1761 (progn (org-mark-ring-push) (goto-char point
) (org-show-context))
1762 (message "source-code block '%s' not found in this buffer" name
))))
1764 (defun org-babel-find-named-block (name)
1765 "Find a named source-code block.
1766 Return the location of the source block identified by source
1767 NAME, or nil if no such block exists. Set match data according to
1768 org-babel-named-src-block-regexp."
1770 (let ((case-fold-search t
)
1771 (regexp (org-babel-named-src-block-regexp-for-name name
)) msg
)
1772 (goto-char (point-min))
1773 (when (or (re-search-forward regexp nil t
)
1774 (re-search-backward regexp nil t
))
1775 (match-beginning 0)))))
1777 (defun org-babel-src-block-names (&optional file
)
1778 "Returns the names of source blocks in FILE or the current buffer."
1780 (when file
(find-file file
)) (goto-char (point-min))
1781 (let ((case-fold-search t
) names
)
1782 (while (re-search-forward org-babel-src-name-w-name-regexp nil t
)
1783 (setq names
(cons (match-string 3) names
)))
1787 (defun org-babel-goto-named-result (name)
1788 "Go to a named result."
1790 (let ((completion-ignore-case t
))
1791 (list (org-icompleting-read "source-block name: "
1792 (org-babel-result-names) nil t
))))
1793 (let ((point (org-babel-find-named-result name
)))
1795 ;; taken from `org-open-at-point'
1796 (progn (goto-char point
) (org-show-context))
1797 (message "result '%s' not found in this buffer" name
))))
1799 (defun org-babel-find-named-result (name &optional point
)
1800 "Find a named result.
1801 Return the location of the result named NAME in the current
1802 buffer or nil if no such result exists."
1804 (let ((case-fold-search t
))
1805 (goto-char (or point
(point-min)))
1806 (catch 'is-a-code-block
1807 (when (re-search-forward
1808 (concat org-babel-result-regexp
1809 "[ \t]" (regexp-quote name
) "[ \t]*[\n\f\v\r]") nil t
)
1810 (when (and (string= "name" (downcase (match-string 1)))
1811 (or (beginning-of-line 1)
1812 (looking-at org-babel-src-block-regexp
)
1813 (looking-at org-babel-multi-line-header-regexp
)
1814 (looking-at org-babel-lob-one-liner-regexp
)))
1815 (throw 'is-a-code-block
(org-babel-find-named-result name
(point))))
1816 (beginning-of-line 0) (point))))))
1818 (defun org-babel-result-names (&optional file
)
1819 "Returns the names of results in FILE or the current buffer."
1821 (when file
(find-file file
)) (goto-char (point-min))
1822 (let ((case-fold-search t
) names
)
1823 (while (re-search-forward org-babel-result-w-name-regexp nil t
)
1824 (setq names
(cons (match-string 4) names
)))
1828 (defun org-babel-next-src-block (&optional arg
)
1829 "Jump to the next source block.
1830 With optional prefix argument ARG, jump forward ARG many source blocks."
1832 (org-next-block arg nil org-babel-src-block-regexp
))
1835 (defun org-babel-previous-src-block (&optional arg
)
1836 "Jump to the previous source block.
1837 With optional prefix argument ARG, jump backward ARG many source blocks."
1839 (org-previous-block arg org-babel-src-block-regexp
))
1841 (defvar org-babel-load-languages
)
1844 (defun org-babel-mark-block ()
1845 "Mark current src block."
1847 (let ((head (org-babel-where-is-src-block-head)))
1851 (looking-at org-babel-src-block-regexp
))
1852 (push-mark (match-end 5) nil t
)
1853 (goto-char (match-beginning 5)))))
1855 (defun org-babel-demarcate-block (&optional arg
)
1856 "Wrap or split the code in the region or on the point.
1857 When called from inside of a code block the current block is
1858 split. When called from outside of a code block a new code block
1859 is created. In both cases if the region is demarcated and if the
1860 region is not active then the point is demarcated."
1862 (let* ((info (org-babel-get-src-block-info 'light
))
1863 (block (progn (org-babel-where-is-src-block-head) (match-string 0)))
1864 (headers (progn (org-babel-where-is-src-block-head) (match-string 4)))
1865 (stars (concat (make-string (or (org-current-level) 1) ?
*) " "))
1867 (if (let (case-fold-search) (string-match "#\\+begin_src" block
))
1868 (setq lower-case-p t
))
1874 (let ((lang (nth 0 info
))
1875 (indent (make-string (nth 5 info
) ?
)))
1876 (when (string-match "^[[:space:]]*$"
1877 (buffer-substring (point-at-bol)
1879 (delete-region (point-at-bol) (point-at-eol)))
1881 (if (looking-at "^") "" "\n")
1882 indent
(funcall (if lower-case-p
'downcase
'upcase
) "#+end_src\n")
1883 (if arg stars indent
) "\n"
1884 indent
(funcall (if lower-case-p
'downcase
'upcase
) "#+begin_src ")
1886 (if (> (length headers
) 1)
1887 (concat " " headers
) headers
)
1888 (if (looking-at "[\n\r]")
1890 (concat "\n" (make-string (current-column) ?
)))))))
1891 (move-end-of-line 2))
1892 (sort (if (org-region-active-p) (list (mark) (point)) (list (point))) #'>))
1893 (let ((start (point))
1894 (lang (org-icompleting-read
1896 (mapcar #'symbol-name
1898 (append (mapcar #'car org-babel-load-languages
)
1899 (mapcar (lambda (el) (intern (car el
)))
1900 org-src-lang-modes
))))))
1901 (body (delete-and-extract-region
1902 (if (org-region-active-p) (mark) (point)) (point))))
1903 (insert (concat (if (looking-at "^") "" "\n")
1904 (if arg
(concat stars
"\n") "")
1905 (funcall (if lower-case-p
'downcase
'upcase
) "#+begin_src ")
1908 (if (or (= (length body
) 0)
1909 (string-match "[\r\n]$" body
)) "" "\n")
1910 (funcall (if lower-case-p
'downcase
'upcase
) "#+end_src\n")))
1911 (goto-char start
) (move-end-of-line 1)))))
1913 (defvar org-babel-lob-one-liner-regexp
)
1914 (defun org-babel-where-is-src-block-result (&optional insert info hash indent
)
1915 "Find where the current source block results begin.
1916 Return the point at the beginning of the result of the current
1917 source block. Specifically at the beginning of the results line.
1918 If no result exists for this block then create a results line
1919 following the source block."
1921 (let* ((case-fold-search t
)
1922 (on-lob-line (save-excursion
1923 (beginning-of-line 1)
1924 (looking-at org-babel-lob-one-liner-regexp
)))
1925 (inlinep (when (org-babel-get-inline-src-block-matches)
1927 (name (nth 4 (or info
(org-babel-get-src-block-info 'light
))))
1928 (head (unless on-lob-line
(org-babel-where-is-src-block-head)))
1930 (when head
(goto-char head
))
1931 (org-with-wide-buffer
1933 found
;; was there a result (before we potentially insert one)
1938 ;; - return t if it is found, else return nil
1939 ;; - if it does not need to be rebuilt, then don't set end
1940 ;; - if it does need to be rebuilt then do set end
1941 name
(setq beg
(org-babel-find-named-result name
))
1943 (when (and hash
(not (string= hash
(match-string 5))))
1944 (goto-char beg
) (setq end beg
) ;; beginning of result
1946 (delete-region end
(org-babel-result-end)) nil
)))
1949 ;; - return t if it is found, else return nil
1950 ;; - if it is found, and the hash doesn't match, delete and set end
1951 (or on-lob-line
(re-search-forward "^[ \t]*#\\+end_src" nil t
))
1952 (progn (end-of-line 1)
1953 (if (eobp) (insert "\n") (forward-char 1))
1957 (progn ;; unnamed results line already exists
1959 (while (re-search-forward "[^ \f\t\n\r\v]" nil t
)
1960 (beginning-of-line 1)
1962 ((looking-at (concat org-babel-result-regexp
"\n"))
1963 (throw 'non-comment t
))
1964 ((and (looking-at "^[ \t]*#")
1966 org-babel-lob-one-liner-regexp
)))
1968 (t (throw 'non-comment nil
))))))
1969 (let ((this-hash (match-string 5)))
1971 ;; must remove and rebuild if hash!=old-hash
1972 (if (and hash
(not (string= hash this-hash
)))
1974 (setq end
(point-at-bol))
1976 (delete-region end
(org-babel-result-end))
1978 (setq end nil
))))))))))
1979 (if (not (and insert end
)) found
1982 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1984 (when (wholenump indent
) (make-string indent ?
))
1985 "#+" org-babel-results-keyword
1987 (if org-babel-hash-show-time
1989 "["(format-time-string "<%Y-%m-%d %H:%M:%S>")" "hash
"]")
1990 (concat "["hash
"]")))
1992 (when name
(concat " " name
)) "\n"))
1993 (unless beg
(insert "\n") (backward-char))
1994 (beginning-of-line 0)
1995 (if hash
(org-babel-hide-hash))
1998 (defvar org-block-regexp
)
1999 (defun org-babel-read-result ()
2000 "Read the result at `point' into emacs-lisp."
2001 (let ((case-fold-search t
) result-string
)
2003 ((org-at-table-p) (org-babel-read-table))
2004 ((org-at-item-p) (org-babel-read-list))
2005 ((looking-at org-bracket-link-regexp
) (org-babel-read-link))
2006 ((looking-at org-block-regexp
) (org-remove-indentation (match-string 4)))
2007 ((or (looking-at "^[ \t]*: ") (looking-at "^[ \t]*:$"))
2010 (mapconcat (lambda (line)
2011 (or (and (> (length line
) 1)
2012 (string-match "^[ \t]*: ?\\(.+\\)" line
)
2013 (match-string 1 line
))
2017 (point) (org-babel-result-end)) "[\r\n]+")
2019 (or (org-babel-number-p result-string
) result-string
))
2020 ((looking-at org-babel-result-regexp
)
2021 (save-excursion (forward-line 1) (org-babel-read-result))))))
2023 (defun org-babel-read-table ()
2024 "Read the table at `point' into emacs-lisp."
2025 (mapcar (lambda (row)
2026 (if (and (symbolp row
) (equal row
'hline
)) row
2027 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
)) row
)))
2028 (org-table-to-lisp)))
2030 (defun org-babel-read-list ()
2031 "Read the list at `point' into emacs-lisp."
2032 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
))
2033 (mapcar #'cadr
(cdr (org-list-parse-list)))))
2035 (defvar org-link-types-re
)
2036 (defun org-babel-read-link ()
2037 "Read the link at `point' into emacs-lisp.
2038 If the path of the link is a file path it is expanded using
2039 `expand-file-name'."
2040 (let* ((case-fold-search t
)
2041 (raw (and (looking-at org-bracket-link-regexp
)
2042 (org-no-properties (match-string 1))))
2043 (type (and (string-match org-link-types-re raw
)
2044 (match-string 1 raw
))))
2046 ((not type
) (expand-file-name raw
))
2047 ((string= type
"file")
2048 (and (string-match "file\\(.*\\):\\(.+\\)" raw
)
2049 (expand-file-name (match-string 2 raw
))))
2052 (defun org-babel-format-result (result &optional sep
)
2053 "Format RESULT for writing to file."
2054 (let ((echo-res (lambda (r) (if (stringp r
) r
(format "%S" r
)))))
2058 result
(list :sep
(or sep
"\t") :fmt echo-res
))
2060 (funcall echo-res result
))))
2062 (defun org-babel-insert-result
2063 (result &optional result-params info hash indent lang
)
2064 "Insert RESULT into the current buffer.
2065 By default RESULT is inserted after the end of the
2066 current source block. With optional argument RESULT-PARAMS
2067 controls insertion of results in the org-mode file.
2068 RESULT-PARAMS can take the following values:
2070 replace - (default option) insert results after the source block
2071 replacing any previously inserted results
2073 silent -- no results are inserted into the Org-mode buffer but
2074 the results are echoed to the minibuffer and are
2075 ingested by Emacs (a potentially time consuming
2078 file ---- the results are interpreted as a file path, and are
2079 inserted into the buffer using the Org-mode file syntax
2081 list ---- the results are interpreted as an Org-mode list.
2083 raw ----- results are added directly to the Org-mode file. This
2084 is a good option if you code block will output org-mode
2087 drawer -- results are added directly to the Org-mode file as with
2088 \"raw\", but are wrapped in a RESULTS drawer, allowing
2089 them to later be replaced or removed automatically.
2091 org ----- results are added inside of a \"#+BEGIN_SRC org\" block.
2092 They are not comma-escaped when inserted, but Org syntax
2093 here will be discarded when exporting the file.
2095 html ---- results are added inside of a #+BEGIN_HTML block. This
2096 is a good option if you code block will output html
2099 latex --- results are added inside of a #+BEGIN_LATEX block.
2100 This is a good option if you code block will output
2101 latex formatted text.
2103 code ---- the results are extracted in the syntax of the source
2104 code of the language being evaluated and are added
2105 inside of a #+BEGIN_SRC block with the source-code
2106 language set appropriately. Note this relies on the
2107 optional LANG argument."
2108 (if (stringp result
)
2110 (setq result
(org-no-properties result
))
2111 (when (member "file" result-params
)
2112 (setq result
(org-babel-result-to-file
2113 result
(when (assoc :file-desc
(nth 2 info
))
2114 (or (cdr (assoc :file-desc
(nth 2 info
)))
2116 (unless (listp result
) (setq result
(format "%S" result
))))
2117 (if (and result-params
(member "silent" result-params
))
2119 (message (replace-regexp-in-string "%" "%%" (format "%S" result
)))
2124 (when (or (org-babel-get-inline-src-block-matches)
2125 (org-babel-get-lob-one-liner-matches))
2126 (goto-char (match-end 0))
2127 (insert (if (listp result
) "\n" " "))
2129 (existing-result (unless inlinep
2130 (org-babel-where-is-src-block-result
2131 t info hash indent
)))
2133 (cdr (assoc :results_switches
(nth 2 info
))))
2134 (visible-beg (copy-marker (point-min)))
2135 (visible-end (copy-marker (point-max)))
2136 ;; When results exist outside of the current visible
2137 ;; region of the buffer, be sure to widen buffer to
2139 (outside-scope-p (and existing-result
2140 (or (> visible-beg existing-result
)
2141 (<= visible-end existing-result
))))
2143 (when (and (stringp result
) ; ensure results end in a newline
2145 (> (length result
) 0)
2146 (not (or (string-equal (substring result -
1) "\n")
2147 (string-equal (substring result -
1) "\r"))))
2148 (setq result
(concat result
"\n")))
2151 (when outside-scope-p
(widen))
2152 (if (not existing-result
)
2153 (setq beg
(or inlinep
(point)))
2154 (goto-char existing-result
)
2156 (re-search-forward "#" nil t
)
2157 (setq indent
(- (current-column) 1)))
2161 ((member "replace" result-params
)
2162 (delete-region (point) (org-babel-result-end)))
2163 ((member "append" result-params
)
2164 (goto-char (org-babel-result-end)) (setq beg
(point-marker)))
2165 ((member "prepend" result-params
)))) ; already there
2166 (setq results-switches
2167 (if results-switches
(concat " " results-switches
) ""))
2168 (let ((wrap (lambda (start finish
&optional no-escape
)
2169 (goto-char end
) (insert (concat finish
"\n"))
2170 (goto-char beg
) (insert (concat start
"\n"))
2172 (org-escape-code-in-region (min (point) end
) end
))
2173 (goto-char end
) (goto-char (point-at-eol))
2174 (setq end
(point-marker))))
2175 (proper-list-p (lambda (it) (and (listp it
) (null (cdr (last it
)))))))
2176 ;; insert results based on type
2178 ;; do nothing for an empty result
2180 ;; insert a list if preferred
2181 ((member "list" result-params
)
2184 (org-list-to-generic
2187 (lambda (el) (list nil
(if (stringp el
) el
(format "%S" el
))))
2188 (if (listp result
) result
(split-string result
"\n" t
))))
2189 '(:splicep nil
:istart
"- " :iend
"\n")))
2191 ;; assume the result is a table if it's not a string
2192 ((funcall proper-list-p result
)
2194 (insert (concat (orgtbl-to-orgtbl
2196 (lambda (el) (or (listp el
) (eq el
'hline
)))
2198 result
(list result
))
2199 '(:fmt
(lambda (cell) (format "%s" cell
)))) "\n"))
2200 (goto-char beg
) (when (org-at-table-p) (org-table-align)))
2201 ((and (listp result
) (not (funcall proper-list-p result
)))
2202 (insert (format "%s\n" result
)))
2203 ((member "file" result-params
)
2204 (when inlinep
(goto-char inlinep
))
2206 (t (goto-char beg
) (insert result
)))
2207 (when (funcall proper-list-p result
) (goto-char (org-table-end)))
2208 (setq end
(point-marker))
2209 ;; possibly wrap result
2211 ((assoc :wrap
(nth 2 info
))
2212 (let ((name (or (cdr (assoc :wrap
(nth 2 info
))) "RESULTS")))
2213 (funcall wrap
(concat "#+BEGIN_" name
)
2214 (concat "#+END_" (car (org-split-string name
))))))
2215 ((member "html" result-params
)
2216 (funcall wrap
"#+BEGIN_HTML" "#+END_HTML"))
2217 ((member "latex" result-params
)
2218 (funcall wrap
"#+BEGIN_LaTeX" "#+END_LaTeX"))
2219 ((member "org" result-params
)
2220 (goto-char beg
) (if (org-at-table-p) (org-cycle))
2221 (funcall wrap
"#+BEGIN_SRC org" "#+END_SRC"))
2222 ((member "code" result-params
)
2223 (funcall wrap
(format "#+BEGIN_SRC %s%s" (or lang
"none") results-switches
)
2225 ((member "raw" result-params
)
2226 (goto-char beg
) (if (org-at-table-p) (org-cycle)))
2227 ((or (member "drawer" result-params
)
2228 ;; Stay backward compatible with <7.9.2
2229 (member "wrap" result-params
))
2230 (goto-char beg
) (if (org-at-table-p) (org-cycle))
2231 (funcall wrap
":RESULTS:" ":END:" 'no-escape
))
2232 ((and (not (funcall proper-list-p result
))
2233 (not (member "file" result-params
)))
2234 (org-babel-examplify-region beg end results-switches
)
2235 (setq end
(point)))))
2236 ;; possibly indent the results to match the #+results line
2237 (when (and (not inlinep
) (numberp indent
) indent
(> indent
0)
2238 ;; in this case `table-align' does the work for us
2239 (not (and (listp result
)
2240 (member "append" result-params
))))
2241 (indent-rigidly beg end indent
))
2243 (if (member "value" result-params
)
2244 (message "Code block returned no value.")
2245 (message "Code block produced no output."))
2246 (message "Code block evaluation complete.")))
2247 (when outside-scope-p
(narrow-to-region visible-beg visible-end
))
2248 (set-marker visible-beg nil
)
2249 (set-marker visible-end nil
))))))
2251 (defun org-babel-remove-result (&optional info keep-keyword
)
2252 "Remove the result of the current source block."
2254 (let ((location (org-babel-where-is-src-block-result nil info
)))
2257 (goto-char location
)
2258 (when (looking-at (concat org-babel-result-regexp
".*$"))
2260 (if keep-keyword
(1+ (match-end 0)) (1- (match-beginning 0)))
2261 (progn (forward-line 1) (org-babel-result-end))))))))
2263 (defun org-babel-remove-result-one-or-many (x)
2264 "Remove the result of the current source block.
2265 If called with a prefix argument, remove all result blocks
2269 (org-babel-map-src-blocks nil
(org-babel-remove-result))
2270 (org-babel-remove-result)))
2272 (defun org-babel-result-end ()
2273 "Return the point at the end of the current set of results."
2276 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
2277 ((org-at-item-p) (let* ((struct (org-list-struct))
2278 (prvs (org-list-prevs-alist struct
)))
2279 (org-list-get-list-end (point-at-bol) struct prvs
)))
2280 ((let ((case-fold-search t
)) (looking-at "^\\([ \t]*\\):results:"))
2281 (progn (re-search-forward (concat "^" (match-string 1) ":END:"))
2282 (forward-char 1) (point)))
2284 (let ((case-fold-search t
))
2285 (if (looking-at (concat "[ \t]*#\\+begin_\\([^ \t\n\r]+\\)"))
2286 (progn (re-search-forward (concat "[ \t]*#\\+end_" (match-string 1))
2289 (while (looking-at "[ \t]*\\(: \\|:$\\|\\[\\[\\)")
2293 (defun org-babel-result-to-file (result &optional description
)
2294 "Convert RESULT into an `org-mode' link with optional DESCRIPTION.
2295 If the `default-directory' is different from the containing
2296 file's directory then expand relative links."
2297 (when (stringp result
)
2298 (format "[[file:%s]%s]"
2299 (if (and default-directory
2301 (not (string= (expand-file-name default-directory
)
2303 (file-name-directory buffer-file-name
)))))
2304 (expand-file-name result default-directory
)
2306 (if description
(concat "[" description
"]") ""))))
2308 (defvar org-babel-capitalize-example-region-markers nil
2309 "Make true to capitalize begin/end example markers inserted by code blocks.")
2311 (define-obsolete-function-alias
2312 'org-babel-examplize-region
2313 'org-babel-examplify-region
"24.5")
2315 (defun org-babel-examplify-region (beg end
&optional results-switches
)
2316 "Comment out region using the inline '==' or ': ' org example quote."
2318 (let ((chars-between (lambda (b e
)
2319 (not (string-match "^[\\s]*$"
2320 (buffer-substring b e
)))))
2321 (maybe-cap (lambda (str) (if org-babel-capitalize-example-region-markers
2323 (beg-bol (save-excursion (goto-char beg
) (point-at-bol)))
2324 (end-bol (save-excursion (goto-char end
) (point-at-bol)))
2325 (end-eol (save-excursion (goto-char end
) (point-at-eol))))
2326 (if (and (not (= end end-bol
))
2327 (or (funcall chars-between beg-bol beg
)
2328 (funcall chars-between end end-eol
)))
2331 (insert (format org-babel-inline-result-wrap
2332 (prog1 (buffer-substring beg end
)
2333 (delete-region beg end
)))))
2334 (let ((size (count-lines beg end
)))
2336 (cond ((= size
0)) ; do nothing for an empty result
2337 ((< size org-babel-min-lines-for-block-output
)
2340 (beginning-of-line 1) (insert ": ") (forward-line 1)))
2343 (insert (if results-switches
2345 (funcall maybe-cap
"#+begin_example")
2347 (funcall maybe-cap
"#+begin_example\n")))
2348 (if (markerp end
) (goto-char end
) (forward-char (- end beg
)))
2349 (insert (funcall maybe-cap
"#+end_example\n")))))))))
2351 (defun org-babel-update-block-body (new-body)
2352 "Update the body of the current code block to NEW-BODY."
2353 (if (not (org-babel-where-is-src-block-head))
2354 (error "Not in a source block")
2356 (replace-match (concat (org-babel-trim (org-remove-indentation new-body
))
2358 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
2360 (defun org-babel-merge-params (&rest plists
)
2361 "Combine all parameter association lists in PLISTS.
2362 Later elements of PLISTS override the values of previous elements.
2363 This takes into account some special considerations for certain
2364 parameters when merging lists."
2365 (let* ((results-exclusive-groups
2366 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2367 (cdr (assoc 'results org-babel-common-header-args-w-values
))))
2368 (exports-exclusive-groups
2369 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2370 (cdr (assoc 'exports org-babel-common-header-args-w-values
))))
2372 (e-merge (lambda (exclusive-groups &rest result-params
)
2373 ;; maintain exclusivity of mutually exclusive parameters
2375 (mapc (lambda (new-params)
2376 (mapc (lambda (new-param)
2377 (mapc (lambda (exclusive-group)
2378 (when (member new-param exclusive-group
)
2379 (mapcar (lambda (excluded-param)
2386 (setq output
(org-uniquify
2387 (cons new-param output
))))
2391 params results exports tangle noweb cache vars shebang comments padline
2400 (let ((name (if (listp (cdr pair
))
2402 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
2404 (intern (match-string 1 (cdr pair
)))))))
2408 (if (member name
(mapcar #'car vars
))
2410 (push name clearnames
)
2414 (unless (equal (car p
) name
) p
))
2417 (list (cons name pair
))))
2418 ;; if no name is given and we already have named variables
2419 ;; then assign to named variables in order
2420 (if (and vars
(nth variable-index vars
))
2421 (let ((name (car (nth variable-index vars
))))
2422 (push name clearnames
) ; clear out colnames
2425 (prog1 (setf (cddr (nth variable-index vars
))
2426 (concat (symbol-name name
) "=" (cdr pair
)))
2427 (incf variable-index
)))
2428 (error "Variable \"%s\" must be assigned a default value"
2431 (setq results
(funcall e-merge results-exclusive-groups
2434 (let ((r (cdr pair
)))
2435 (if (stringp r
) r
(eval r
)))))))
2438 (setq results
(funcall e-merge results-exclusive-groups
2440 (unless (or (member "both" exports
)
2441 (member "none" exports
)
2442 (member "code" exports
))
2443 (setq exports
(funcall e-merge exports-exclusive-groups
2444 exports
'("results"))))
2445 (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))
2448 (setq results
(funcall e-merge results-exclusive-groups
2450 (unless (or (member "both" exports
)
2451 (member "none" exports
)
2452 (member "code" exports
))
2453 (setq exports
(funcall e-merge exports-exclusive-groups
2454 exports
'("results"))))
2455 (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))
2457 (setq exports
(funcall e-merge exports-exclusive-groups
2458 exports
(split-string (cdr pair
)))))
2459 (:tangle
;; take the latest -- always overwrite
2460 (setq tangle
(or (list (cdr pair
)) tangle
)))
2462 (setq noweb
(funcall e-merge
2463 '(("yes" "no" "tangle" "no-export"
2464 "strip-export" "eval"))
2466 (split-string (or (cdr pair
) "")))))
2468 (setq cache
(funcall e-merge
'(("yes" "no")) cache
2469 (split-string (or (cdr pair
) "")))))
2471 (setq padline
(funcall e-merge
'(("yes" "no")) padline
2472 (split-string (or (cdr pair
) "")))))
2473 (:shebang
;; take the latest -- always overwrite
2474 (setq shebang
(or (list (cdr pair
)) shebang
)))
2476 (setq comments
(funcall e-merge
'(("yes" "no")) comments
2477 (split-string (or (cdr pair
) "")))))
2478 (t ;; replace: this covers e.g. :session
2479 (setq params
(cons pair
(assq-delete-all (car pair
) params
))))))
2482 (setq vars
(reverse vars
))
2483 (while vars
(setq params
(cons (cons :var
(cddr (pop vars
))) params
)))
2484 ;; clear out col-names and row-names for replaced variables
2489 (when (assoc param params
)
2490 (setf (cdr (assoc param params
))
2491 (org-remove-if (lambda (pair) (equal (car pair
) name
))
2492 (cdr (assoc param params
))))
2493 (setf params
(org-remove-if (lambda (pair) (and (equal (car pair
) param
)
2496 (list :colname-names
:rowname-names
)))
2500 (let ((key (intern (concat ":" (symbol-name hd
))))
2502 (setf params
(cons (cons key
(mapconcat 'identity val
" ")) params
))))
2503 '(results exports tangle noweb padline cache shebang comments
))
2506 (defvar org-babel-use-quick-and-dirty-noweb-expansion nil
2507 "Set to true to use regular expressions to expand noweb references.
2508 This results in much faster noweb reference expansion but does
2509 not properly allow code blocks to inherit the \":noweb-ref\"
2510 header argument from buffer or subtree wide properties.")
2512 (defun org-babel-noweb-p (params context
)
2513 "Check if PARAMS require expansion in CONTEXT.
2514 CONTEXT may be one of :tangle, :export or :eval."
2516 (intersect (lambda (as bs
)
2518 (if (member (car as
) bs
)
2520 (funcall intersect
(cdr as
) bs
))))))
2521 (funcall intersect
(case context
2522 (:tangle
'("yes" "tangle" "no-export" "strip-export"))
2523 (:eval
'("yes" "no-export" "strip-export" "eval"))
2525 (split-string (or (cdr (assoc :noweb params
)) "")))))
2527 (defun org-babel-expand-noweb-references (&optional info parent-buffer
)
2528 "Expand Noweb references in the body of the current source code block.
2530 For example the following reference would be replaced with the
2531 body of the source-code block named 'example-block'.
2535 Note that any text preceding the <<foo>> construct on a line will
2536 be interposed between the lines of the replacement text. So for
2537 example if <<foo>> is placed behind a comment, then the entire
2538 replacement text will also be commented.
2540 This function must be called from inside of the buffer containing
2541 the source-code block which holds BODY.
2543 In addition the following syntax can be used to insert the
2544 results of evaluating the source-code block named 'example-block'.
2548 Any optional arguments can be passed to example-block by placing
2549 the arguments inside the parenthesis following the convention
2550 defined by `org-babel-lob'. For example
2552 <<example-block(a=9)>>
2554 would set the value of argument \"a\" equal to \"9\". Note that
2555 these arguments are not evaluated in the current source-code
2556 block but are passed literally to the \"example-block\"."
2557 (let* ((parent-buffer (or parent-buffer
(current-buffer)))
2558 (info (or info
(org-babel-get-src-block-info 'light
)))
2561 (ob-nww-start org-babel-noweb-wrap-start
)
2562 (ob-nww-end org-babel-noweb-wrap-end
)
2563 (comment (string= "noweb" (cdr (assoc :comments
(nth 2 info
)))))
2564 (rx-prefix (concat "\\(" org-babel-src-name-regexp
"\\|"
2565 ":noweb-ref[ \t]+" "\\)"))
2567 (nb-add (lambda (text) (setq new-body
(concat new-body text
))))
2568 (c-wrap (lambda (text)
2570 (funcall (intern (concat lang
"-mode")))
2571 (comment-region (point) (progn (insert text
) (point)))
2572 (org-babel-trim (buffer-string)))))
2573 index source-name evaluate prefix
)
2575 (org-set-local 'org-babel-noweb-wrap-start ob-nww-start
)
2576 (org-set-local 'org-babel-noweb-wrap-end ob-nww-end
)
2577 (insert body
) (goto-char (point-min))
2578 (setq index
(point))
2579 (while (and (re-search-forward (org-babel-noweb-wrap) nil t
))
2580 (save-match-data (setf source-name
(match-string 1)))
2581 (save-match-data (setq evaluate
(string-match "\(.*\)" source-name
)))
2584 (buffer-substring (match-beginning 0)
2586 (beginning-of-line 1) (point)))))
2587 ;; add interval to new-body (removing noweb reference)
2588 (goto-char (match-beginning 0))
2589 (funcall nb-add
(buffer-substring index
(point)))
2590 (goto-char (match-end 0))
2591 (setq index
(point))
2594 (with-current-buffer parent-buffer
2597 (mapconcat ;; Interpose PREFIX between every line.
2601 (let ((raw (org-babel-ref-resolve source-name
)))
2602 (if (stringp raw
) raw
(format "%S" raw
)))
2604 ;; Retrieve from the library of babel.
2605 (nth 2 (assoc (intern source-name
)
2606 org-babel-library-of-babel
))
2607 ;; Return the contents of headlines literally.
2609 (when (org-babel-ref-goto-headline-id source-name
)
2610 (org-babel-ref-headline-body)))
2611 ;; Find the expansion of reference in this buffer.
2612 (let ((rx (concat rx-prefix source-name
"[ \t\n]"))
2615 (goto-char (point-min))
2616 (if org-babel-use-quick-and-dirty-noweb-expansion
2617 (while (re-search-forward rx nil t
)
2618 (let* ((i (org-babel-get-src-block-info 'light
))
2619 (body (org-babel-expand-noweb-references i
))
2620 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2623 (let ((cs (org-babel-tangle-comment-links i
)))
2624 (concat (funcall c-wrap
(car cs
)) "\n"
2626 (funcall c-wrap
(cadr cs
))))
2628 (setq expansion
(cons sep
(cons full expansion
)))))
2629 (org-babel-map-src-blocks nil
2630 (let ((i (org-babel-get-src-block-info 'light
)))
2631 (when (equal (or (cdr (assoc :noweb-ref
(nth 2 i
)))
2634 (let* ((body (org-babel-expand-noweb-references i
))
2635 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2638 (let ((cs (org-babel-tangle-comment-links i
)))
2639 (concat (funcall c-wrap
(car cs
)) "\n"
2641 (funcall c-wrap
(cadr cs
))))
2644 (cons sep
(cons full expansion
)))))))))
2646 (mapconcat #'identity
(nreverse (cdr expansion
)) "")))
2647 ;; Possibly raise an error if named block doesn't exist.
2648 (if (member lang org-babel-noweb-error-langs
)
2650 (org-babel-noweb-wrap source-name
)
2651 "could not be resolved (see "
2652 "`org-babel-noweb-error-langs')"))
2654 "[\n\r]") (concat "\n" prefix
))))))
2655 (funcall nb-add
(buffer-substring index
(point-max))))
2658 (defun org-babel-script-escape (str &optional force
)
2659 "Safely convert tables into elisp lists."
2664 (or (and (string-equal "[" (substring str
0 1))
2665 (string-equal "]" (substring str -
1)))
2666 (and (string-equal "{" (substring str
0 1))
2667 (string-equal "}" (substring str -
1)))
2668 (and (string-equal "(" (substring str
0 1))
2669 (string-equal ")" (substring str -
1))))))
2673 (let (in-single in-double out
)
2679 (91 (if (or in-double in-single
) ; [
2682 (93 (if (or in-double in-single
) ; ]
2685 (123 (if (or in-double in-single
) ; {
2688 (125 (if (or in-double in-single
) ; }
2691 (44 (if (or in-double in-single
) ; ,
2692 (cons 44 out
) (cons 32 out
)))
2693 (39 (if in-double
; '
2695 (setq in-single
(not in-single
)) (cons 34 out
)))
2696 (34 (if in-single
; "
2697 (append (list 34 32) out
)
2698 (setq in-double
(not in-double
)) (cons 34 out
)))
2699 (t (cons ch out
)))))
2700 (string-to-list str
))
2701 (apply #'string
(reverse out
)))))
2703 (condition-case nil
(org-babel-read escaped
) (error escaped
))))
2705 (defun org-babel-read (cell &optional inhibit-lisp-eval
)
2706 "Convert the string value of CELL to a number if appropriate.
2707 Otherwise if cell looks like lisp (meaning it starts with a
2708 \"(\", \"'\", \"`\" or a \"[\") then read it as lisp,
2709 otherwise return it unmodified as a string. Optional argument
2710 NO-LISP-EVAL inhibits lisp evaluation for situations in which is
2711 it not appropriate."
2712 (if (and (stringp cell
) (not (equal cell
"")))
2713 (or (org-babel-number-p cell
)
2714 (if (and (not inhibit-lisp-eval
)
2715 (or (member (substring cell
0 1) '("(" "'" "`" "["))
2716 (string= cell
"*this*")))
2718 (if (string= (substring cell
0 1) "\"")
2720 (progn (set-text-properties 0 (length cell
) nil cell
) cell
))))
2723 (defun org-babel-number-p (string)
2724 "If STRING represents a number return its value."
2725 (if (and (string-match "[0-9]+" string
)
2726 (string-match "^-?[0-9]*\\.?[0-9]*$" string
)
2727 (= (length (substring string
(match-beginning 0)
2730 (string-to-number string
)))
2732 (defun org-babel-import-elisp-from-file (file-name &optional separator
)
2733 "Read the results located at FILE-NAME into an elisp table.
2734 If the table is trivial, then return it as a scalar."
2736 (save-window-excursion
2740 (org-table-import file-name separator
)
2741 (delete-file file-name
)
2742 (setq result
(mapcar (lambda (row)
2743 (mapcar #'org-babel-string-read row
))
2744 (org-table-to-lisp))))
2745 (error (message "Error reading results: %s" err
) nil
)))
2746 (if (null (cdr result
)) ;; if result is trivial vector, then scalarize it
2747 (if (consp (car result
))
2748 (if (null (cdr (car result
)))
2754 (defun org-babel-string-read (cell)
2755 "Strip nested \"s from around strings."
2756 (org-babel-read (or (and (stringp cell
)
2757 (string-match "\\\"\\(.+\\)\\\"" cell
)
2758 (match-string 1 cell
))
2761 (defun org-babel-chomp (string &optional regexp
)
2762 "Strip a trailing space or carriage return from STRING.
2763 The default regexp used is \"[ \\f\\t\\n\\r\\v]\" but another one
2764 can be specified as the REGEXP argument."
2765 (let ((regexp (or regexp
"[ \f\t\n\r\v]")))
2766 (while (and (> (length string
) 0)
2767 (string-match regexp
(substring string -
1)))
2768 (setq string
(substring string
0 -
1)))
2771 (defun org-babel-trim (string &optional regexp
)
2772 "Strip a leading and trailing space or carriage return from STRING.
2773 Like `org-babel-chomp', but run on both the first and last
2774 character of the string."
2777 (org-babel-chomp (org-reverse-string string
) regexp
)) regexp
))
2779 (defun org-babel-tramp-handle-call-process-region
2780 (start end program
&optional delete buffer display
&rest args
)
2781 "Use Tramp to handle `call-process-region'.
2782 Fixes a bug in `tramp-handle-call-process-region'."
2783 (if (and (featurep 'tramp
) (file-remote-p default-directory
))
2784 (let ((tmpfile (tramp-compat-make-temp-file "")))
2785 (write-region start end tmpfile
)
2786 (when delete
(delete-region start end
))
2788 ;; (apply 'call-process program tmpfile buffer display args)
2790 (apply 'process-file program tmpfile buffer display args
)
2791 (delete-file tmpfile
)))
2792 ;; org-babel-call-process-region-original is the original emacs
2793 ;; definition. It is in scope from the let binding in
2794 ;; org-babel-execute-src-block
2795 (apply org-babel-call-process-region-original
2796 start end program delete buffer display args
)))
2798 (defun org-babel-local-file-name (file)
2799 "Return the local name component of FILE."
2800 (or (file-remote-p file
'localname
) file
))
2802 (defun org-babel-process-file-name (name &optional no-quote-p
)
2803 "Prepare NAME to be used in an external process.
2804 If NAME specifies a remote location, the remote portion of the
2805 name is removed, since in that case the process will be executing
2806 remotely. The file name is then processed by `expand-file-name'.
2807 Unless second argument NO-QUOTE-P is non-nil, the file name is
2808 additionally processed by `shell-quote-argument'"
2809 (let ((f (org-babel-local-file-name (expand-file-name name
))))
2810 (if no-quote-p f
(shell-quote-argument f
))))
2812 (defvar org-babel-temporary-directory
)
2813 (unless (or noninteractive
(boundp 'org-babel-temporary-directory
))
2814 (defvar org-babel-temporary-directory
2815 (or (and (boundp 'org-babel-temporary-directory
)
2816 (file-exists-p org-babel-temporary-directory
)
2817 org-babel-temporary-directory
)
2818 (make-temp-file "babel-" t
))
2819 "Directory to hold temporary files created to execute code blocks.
2820 Used by `org-babel-temp-file'. This directory will be removed on
2823 (defcustom org-babel-remote-temporary-directory
"/tmp/"
2824 "Directory to hold temporary files on remote hosts."
2828 (defmacro org-babel-result-cond
(result-params scalar-form
&rest table-forms
)
2829 "Call the code to parse raw string results according to RESULT-PARAMS."
2831 (debug (form form
&rest form
)))
2832 (org-with-gensyms (params)
2833 `(let ((,params
,result-params
))
2834 (unless (member "none" ,params
)
2835 (if (or (member "scalar" ,params
)
2836 (member "verbatim" ,params
)
2837 (member "html" ,params
)
2838 (member "code" ,params
)
2839 (member "pp" ,params
)
2840 (and (or (member "output" ,params
)
2841 (member "raw" ,params
)
2842 (member "org" ,params
)
2843 (member "drawer" ,params
))
2844 (not (member "table" ,params
))))
2847 (def-edebug-spec org-babel-result-cond
(form form body
))
2849 (defun org-babel-temp-file (prefix &optional suffix
)
2850 "Create a temporary file in the `org-babel-temporary-directory'.
2851 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2852 value of `temporary-file-directory' temporarily set to the value
2853 of `org-babel-temporary-directory'."
2854 (if (file-remote-p default-directory
)
2856 (concat (file-remote-p default-directory
)
2858 prefix org-babel-remote-temporary-directory
))))
2859 (make-temp-file prefix nil suffix
))
2860 (let ((temporary-file-directory
2861 (or (and (boundp 'org-babel-temporary-directory
)
2862 (file-exists-p org-babel-temporary-directory
)
2863 org-babel-temporary-directory
)
2864 temporary-file-directory
)))
2865 (make-temp-file prefix nil suffix
))))
2867 (defun org-babel-remove-temporary-directory ()
2868 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2869 (when (and (boundp 'org-babel-temporary-directory
)
2870 (file-exists-p org-babel-temporary-directory
))
2871 ;; taken from `delete-directory' in files.el
2874 (mapc (lambda (file)
2875 ;; This test is equivalent to
2876 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2877 ;; but more efficient
2878 (if (eq t
(car (file-attributes file
)))
2879 (delete-directory file
)
2880 (delete-file file
)))
2881 ;; We do not want to delete "." and "..".
2882 (directory-files org-babel-temporary-directory
'full
2883 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2884 (delete-directory org-babel-temporary-directory
))
2886 (message "Failed to remove temporary Org-babel directory %s"
2887 (if (boundp 'org-babel-temporary-directory
)
2888 org-babel-temporary-directory
2889 "[directory not defined]"))))))
2891 (add-hook 'kill-emacs-hook
'org-babel-remove-temporary-directory
)
2893 (defun org-babel-one-header-arg-safe-p (pair safe-list
)
2894 "Determine if the PAIR is a safe babel header arg according to SAFE-LIST.
2896 For the format of SAFE-LIST, see `org-babel-safe-header-args'."
2898 (keywordp (car pair
))
2899 (stringp (cdr pair
))
2901 (memq (car pair
) safe-list
)
2902 (let ((entry (assq (car pair
) safe-list
)))
2905 (cond ((functionp (cdr entry
))
2906 (funcall (cdr entry
) (cdr pair
)))
2907 ((listp (cdr entry
))
2908 (member (cdr pair
) (cdr entry
)))
2911 (defun org-babel-generate-file-param (src-name params
)
2912 "Calculate the filename for source block results.
2914 The directory is calculated from the :output-dir property of the
2915 source block; if not specified, use the current directory.
2917 If the source block has a #+NAME and the :file parameter does not
2918 contain any period characters, then the :file parameter is
2919 treated as an extension, and the output file name is the
2920 concatenation of the directory (as calculated above), the block
2921 name, a period, and the parameter value as a file extension.
2922 Otherwise, the :file parameter is treated as a full file name,
2923 and the output file name is the directory (as calculated above)
2924 plus the parameter value."
2925 (let* ((file-cons (assq :file params
))
2926 (file-ext-cons (assq :file-ext params
))
2927 (file-ext (cdr-safe file-ext-cons
))
2928 (dir (cdr-safe (assq :output-dir params
)))
2930 ;; create the output-dir if it does not exist
2932 (make-directory dir t
))
2934 ;; :file given; add :output-dir if given
2936 (setcdr file-cons
(concat (file-name-as-directory dir
) (cdr file-cons
))))
2937 ;; :file not given; compute from name and :file-ext if possible
2938 (when (and src-name file-ext
)
2940 (setq fname
(concat (file-name-as-directory (or dir
""))
2941 src-name
"." file-ext
))
2942 (setq fname
(concat src-name
"." file-ext
)))
2943 (setq params
(cons (cons :file fname
) params
))))
2946 ;;; Used by backends: R, Maxima, Octave.
2947 (defun org-babel-graphical-output-file (params)
2948 "File where a babel block should send graphical output, per PARAMS."
2949 (unless (assq :file params
)
2950 (if (assq :file-ext params
)
2951 (user-error ":file-ext given but no :file generated; did you forget to give a block a #+NAME?")
2952 (user-error "No :file header argument given; cannot create graphical result.")))
2953 (and (member "graphics" (cdr (assq :result-params params
)))
2954 (cdr (assq :file params
))))
2959 ;; generated-autoload-file: "org-loaddefs.el"
2962 ;;; ob-core.el ends here