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-reduce
"org" (CL-FUNC CL-SEQ
&rest CL-KEYS
))
43 (declare-function org-mark-ring-push
"org" (&optional pos buffer
))
44 (declare-function tramp-compat-make-temp-file
"tramp-compat"
45 (filename &optional dir-flag
))
46 (declare-function tramp-dissect-file-name
"tramp" (name &optional nodefault
))
47 (declare-function tramp-file-name-user
"tramp" (vec))
48 (declare-function tramp-file-name-host
"tramp" (vec))
49 (declare-function with-parsed-tramp-file-name
"tramp" (filename var
&rest body
))
50 (declare-function org-icompleting-read
"org" (&rest args
))
51 (declare-function org-edit-src-code
"org-src"
52 (&optional context code edit-buffer-name quietp
))
53 (declare-function org-edit-src-exit
"org-src" (&optional context
))
54 (declare-function org-open-at-point
"org" (&optional in-emacs reference-buffer
))
55 (declare-function org-save-outline-visibility
"org-macs" (use-markers &rest body
))
56 (declare-function org-outline-overlay-data
"org" (&optional use-markers
))
57 (declare-function org-set-outline-overlay-data
"org" (data))
58 (declare-function org-narrow-to-subtree
"org" ())
59 (declare-function org-split-string
"org" (string &optional separators
))
60 (declare-function org-entry-get
"org"
61 (pom property
&optional inherit literal-nil
))
62 (declare-function org-make-options-regexp
"org" (kwds &optional extra
))
63 (declare-function org-do-remove-indentation
"org" (&optional n
))
64 (declare-function org-next-block
"org" (arg &optional backward block-regexp
))
65 (declare-function org-previous-block
"org" (arg &optional block-regexp
))
66 (declare-function org-show-context
"org" (&optional key
))
67 (declare-function org-at-table-p
"org" (&optional table-type
))
68 (declare-function org-cycle
"org" (&optional arg
))
69 (declare-function org-uniquify
"org" (list))
70 (declare-function org-current-level
"org" ())
71 (declare-function org-table-import
"org-table" (file arg
))
72 (declare-function org-add-hook
"org-compat"
73 (hook function
&optional append local
))
74 (declare-function org-table-align
"org-table" ())
75 (declare-function org-table-end
"org-table" (&optional table-type
))
76 (declare-function orgtbl-to-generic
"org-table" (table params
))
77 (declare-function orgtbl-to-orgtbl
"org-table" (table params
))
78 (declare-function org-babel-tangle-comment-links
"ob-tangle" (&optional info
))
79 (declare-function org-babel-lob-get-info
"ob-lob" nil
)
80 (declare-function org-babel-ref-split-args
"ob-ref" (arg-string))
81 (declare-function org-babel-ref-parse
"ob-ref" (assignment))
82 (declare-function org-babel-ref-resolve
"ob-ref" (ref))
83 (declare-function org-babel-ref-goto-headline-id
"ob-ref" (id))
84 (declare-function org-babel-ref-headline-body
"ob-ref" ())
85 (declare-function org-babel-lob-execute-maybe
"ob-lob" ())
86 (declare-function org-number-sequence
"org-compat" (from &optional to inc
))
87 (declare-function org-at-item-p
"org-list" ())
88 (declare-function org-list-parse-list
"org-list" (&optional delete
))
89 (declare-function org-list-to-generic
"org-list" (LIST PARAMS
))
90 (declare-function org-list-struct
"org-list" ())
91 (declare-function org-list-prevs-alist
"org-list" (struct))
92 (declare-function org-list-get-list-end
"org-list" (item struct prevs
))
93 (declare-function org-remove-if
"org" (predicate seq
))
94 (declare-function org-completing-read
"org" (&rest args
))
95 (declare-function org-escape-code-in-region
"org-src" (beg end
))
96 (declare-function org-unescape-code-in-string
"org-src" (s))
97 (declare-function org-table-to-lisp
"org-table" (&optional txt
))
98 (declare-function org-reverse-string
"org" (string))
99 (declare-function org-element-context
"org-element" (&optional ELEMENT
))
101 (defgroup org-babel nil
102 "Code block evaluation and management in `org-mode' documents."
106 (defcustom org-confirm-babel-evaluate t
107 "Confirm before evaluation.
108 Require confirmation before interactively evaluating code
109 blocks in Org-mode buffers. The default value of this variable
110 is t, meaning confirmation is required for any code block
111 evaluation. This variable can be set to nil to inhibit any
112 future confirmation requests. This variable can also be set to a
113 function which takes two arguments the language of the code block
114 and the body of the code block. Such a function should then
115 return a non-nil value if the user should be prompted for
116 execution or nil if no prompt is required.
118 Warning: Disabling confirmation may result in accidental
119 evaluation of potentially harmful code. It may be advisable
120 remove code block execution from C-c C-c as further protection
121 against accidental code block evaluation. The
122 `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
123 remove code block execution from the C-c C-c keybinding."
126 :type
'(choice boolean function
))
127 ;; don't allow this variable to be changed through file settings
128 (put 'org-confirm-babel-evaluate
'safe-local-variable
(lambda (x) (eq x t
)))
130 (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
131 "Remove code block evaluation from the C-c C-c key binding."
136 (defcustom org-babel-results-keyword
"RESULTS"
137 "Keyword used to name results generated by code blocks.
138 Should be either RESULTS or NAME however any capitalization may
142 :package-version
'(Org .
"8.0")
145 (defcustom org-babel-noweb-wrap-start
"<<"
146 "String used to begin a noweb reference in a code block.
147 See also `org-babel-noweb-wrap-end'."
151 (defcustom org-babel-noweb-wrap-end
">>"
152 "String used to end a noweb reference in a code block.
153 See also `org-babel-noweb-wrap-start'."
157 (defcustom org-babel-inline-result-wrap
"=%s="
158 "Format string used to wrap inline results.
159 This string must include a \"%s\" which will be replaced by the results."
163 (defun org-babel-noweb-wrap (&optional regexp
)
164 (concat org-babel-noweb-wrap-start
165 (or regexp
"\\([^ \t\n].+?[^ \t]\\|[^ \t\n]\\)")
166 org-babel-noweb-wrap-end
))
168 (defvar org-babel-src-name-regexp
169 "^[ \t]*#\\+name:[ \t]*"
170 "Regular expression used to match a source name line.")
172 (defvar org-babel-multi-line-header-regexp
173 "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
174 "Regular expression used to match multi-line header arguments.")
176 (defvar org-babel-src-name-w-name-regexp
177 (concat org-babel-src-name-regexp
179 org-babel-multi-line-header-regexp
181 "\\([^ ()\f\t\n\r\v]+\\)")
182 "Regular expression matching source name lines with a name.")
184 (defvar org-babel-src-block-regexp
186 ;; (1) indentation (2) lang
187 "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
189 "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
190 ;; (4) header arguments
193 "\\([^\000]*?\n\\)??[ \t]*#\\+end_src")
194 "Regexp used to identify code blocks.")
196 (defvar org-babel-inline-src-block-regexp
198 ;; (1) replacement target (2) lang
199 "\\(?:^\\|[^-[:alnum:]]\\)\\(src_\\([^ \f\t\n\r\v]+\\)"
200 ;; (3,4) (unused, headers)
201 "\\(\\|\\[\\(.*?\\)\\]\\)"
203 "{\\([^\f\n\r\v]+?\\)}\\)")
204 "Regexp used to identify inline src-blocks.")
206 (defun org-babel-get-header (params key
&optional others
)
207 "Select only header argument of type KEY from a list.
208 Optional argument OTHERS indicates that only the header that do
209 not match KEY should be returned."
212 (lambda (p) (when (funcall (if others
#'not
#'identity
) (eq (car p
) key
)) p
))
215 (defun org-babel-get-inline-src-block-matches()
216 "Set match data if within body of an inline source block.
217 Returns non-nil if match-data set"
218 (let ((src-at-0-p (save-excursion
219 (beginning-of-line 1)
220 (string= "src" (thing-at-point 'word
))))
221 (first-line-p (= (line-beginning-position) (point-min)))
223 (let ((search-for (cond ((and src-at-0-p first-line-p
"src_"))
224 (first-line-p "[[:punct:] \t]src_")
225 (t "[[:punct:] \f\t\n\r\v]src_")))
226 (lower-limit (if first-line-p
228 (- (point-at-bol) 1))))
230 (when (or (and src-at-0-p
(bobp))
231 (and (re-search-forward "}" (point-at-eol) t
)
232 (re-search-backward search-for lower-limit t
)
234 (when (looking-at org-babel-inline-src-block-regexp
)
237 (defvar org-babel-inline-lob-one-liner-regexp
)
238 (defun org-babel-get-lob-one-liner-matches()
239 "Set match data if on line of an lob one liner.
240 Returns non-nil if match-data set"
242 (unless (= (point) (point-at-bol)) ;; move before inline block
243 (re-search-backward "[ \f\t\n\r\v]" nil t
))
244 (if (looking-at org-babel-inline-lob-one-liner-regexp
)
248 (defun org-babel-get-src-block-info (&optional light
)
249 "Get information on the current source block.
251 Optional argument LIGHT does not resolve remote variable
252 references; a process which could likely result in the execution
253 of other code blocks.
256 (language body header-arguments-alist switches name indent block-head)."
257 (let ((case-fold-search t
) head info name indent
)
259 (if (setq head
(org-babel-where-is-src-block-head))
262 (setq info
(org-babel-parse-src-block-match))
263 (setq indent
(car (last info
)))
264 (setq info
(butlast info
))
265 (while (and (forward-line -
1)
266 (looking-at org-babel-multi-line-header-regexp
))
268 (org-babel-merge-params
270 (org-babel-parse-header-arguments (match-string 1)))))
271 (when (looking-at org-babel-src-name-w-name-regexp
)
272 (setq name
(org-no-properties (match-string 3)))))
273 ;; inline source block
274 (when (org-babel-get-inline-src-block-matches)
275 (setq info
(org-babel-parse-inline-src-block-match))))
276 ;; resolve variable references and add summary parameters
277 (when (and info
(not light
))
278 (setf (nth 2 info
) (org-babel-process-params (nth 2 info
))))
279 (when info
(append info
(list name indent head
)))))
281 (defvar org-current-export-file
) ; dynamically bound
282 (defmacro org-babel-check-confirm-evaluate
(info &rest body
)
283 "Evaluate BODY with special execution confirmation variables set.
285 Specifically; NOEVAL will indicate if evaluation is allowed,
286 QUERY will indicate if a user query is required, CODE-BLOCK will
287 hold the language of the code block, and BLOCK-NAME will hold the
288 name of the code block."
289 (declare (indent defun
))
291 (lang block-body headers name eval eval-no export eval-no-export
)
292 `(let* ((,lang
(nth 0 ,info
))
293 (,block-body
(nth 1 ,info
))
294 (,headers
(nth 2 ,info
))
295 (,name
(nth 4 ,info
))
296 (,eval
(or (cdr (assoc :eval
,headers
))
297 (when (assoc :noeval
,headers
) "no")))
298 (,eval-no
(or (equal ,eval
"no")
299 (equal ,eval
"never")))
300 (,export
(org-bound-and-true-p org-current-export-file
))
301 (,eval-no-export
(and ,export
(or (equal ,eval
"no-export")
302 (equal ,eval
"never-export"))))
303 (noeval (or ,eval-no
,eval-no-export
))
304 (query (or (equal ,eval
"query")
305 (and ,export
(equal ,eval
"query-export"))
306 (if (functionp org-confirm-babel-evaluate
)
307 (funcall org-confirm-babel-evaluate
309 org-confirm-babel-evaluate
)))
310 (code-block (if ,info
(format " %s " ,lang
) " "))
311 (block-name (if ,name
(format " (%s) " ,name
) " ")))
314 (defsubst org-babel-check-evaluate
(info)
315 "Check if code block INFO should be evaluated.
316 Do not query the user."
317 (org-babel-check-confirm-evaluate info
319 (message (format "Evaluation of this%scode-block%sis disabled."
320 code-block block-name
))))))
322 ;; dynamically scoped for asynchronous export
323 (defvar org-babel-confirm-evaluate-answer-no
)
325 (defsubst org-babel-confirm-evaluate
(info)
326 "Confirm evaluation of the code block INFO.
328 If the variable `org-babel-confirm-evaluate-answer-no' is bound
329 to a non-nil value, auto-answer with \"no\".
331 This query can also be suppressed by setting the value of
332 `org-confirm-babel-evaluate' to nil, in which case all future
333 interactive code block evaluations will proceed without any
334 confirmation from the user.
336 Note disabling confirmation may result in accidental evaluation
337 of potentially harmful code."
338 (org-babel-check-confirm-evaluate info
341 (and (not (org-bound-and-true-p
342 org-babel-confirm-evaluate-answer-no
))
344 (format "Evaluate this%scode block%son your system? "
345 code-block block-name
)))
346 (message (format "Evaluation of this%scode-block%sis aborted."
347 code-block block-name
)))))))
350 (defun org-babel-execute-safely-maybe ()
351 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
352 (org-babel-execute-maybe)))
354 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-execute-safely-maybe
)
357 (defun org-babel-execute-maybe ()
359 (or (org-babel-execute-src-block-maybe)
360 (org-babel-lob-execute-maybe)))
362 (defmacro org-babel-when-in-src-block
(&rest body
)
363 "Execute BODY if point is in a source block and return t.
365 Otherwise do nothing and return nil."
366 `(if (or (org-babel-where-is-src-block-head)
367 (org-babel-get-inline-src-block-matches))
373 (defun org-babel-execute-src-block-maybe ()
374 "Conditionally execute a source block.
375 Detect if this is context for a Babel src-block and if so
376 then run `org-babel-execute-src-block'."
378 (org-babel-when-in-src-block
379 (org-babel-eval-wipe-error-buffer)
380 (org-babel-execute-src-block current-prefix-arg
)))
383 (defun org-babel-view-src-block-info ()
384 "Display information on the current source block.
385 This includes header arguments, language and name, and is largely
386 a window into the `org-babel-get-src-block-info' function."
388 (let ((info (org-babel-get-src-block-info 'light
))
389 (full (lambda (it) (> (length it
) 0)))
390 (printf (lambda (fmt &rest args
) (princ (apply #'format fmt args
)))))
392 (with-help-window (help-buffer)
393 (let ((name (nth 4 info
))
395 (switches (nth 3 info
))
396 (header-args (nth 2 info
)))
397 (when name
(funcall printf
"Name: %s\n" name
))
398 (when lang
(funcall printf
"Lang: %s\n" lang
))
399 (when (funcall full switches
) (funcall printf
"Switches: %s\n" switches
))
400 (funcall printf
"Header Arguments:\n")
401 (dolist (pair (sort header-args
402 (lambda (a b
) (string< (symbol-name (car a
))
403 (symbol-name (car b
))))))
404 (when (funcall full
(cdr pair
))
405 (funcall printf
"\t%S%s\t%s\n"
407 (if (> (length (format "%S" (car pair
))) 7) "" "\t")
411 (defun org-babel-expand-src-block-maybe ()
412 "Conditionally expand a source block.
413 Detect if this is context for a org-babel src-block and if so
414 then run `org-babel-expand-src-block'."
416 (org-babel-when-in-src-block
417 (org-babel-expand-src-block current-prefix-arg
)))
420 (defun org-babel-load-in-session-maybe ()
421 "Conditionally load a source block in a session.
422 Detect if this is context for a org-babel src-block and if so
423 then run `org-babel-load-in-session'."
425 (org-babel-when-in-src-block
426 (org-babel-load-in-session current-prefix-arg
)))
428 (add-hook 'org-metaup-hook
'org-babel-load-in-session-maybe
)
431 (defun org-babel-pop-to-session-maybe ()
432 "Conditionally pop to a session.
433 Detect if this is context for a org-babel src-block and if so
434 then run `org-babel-switch-to-session'."
436 (org-babel-when-in-src-block
437 (org-babel-switch-to-session current-prefix-arg
)))
439 (add-hook 'org-metadown-hook
'org-babel-pop-to-session-maybe
)
441 (defconst org-babel-common-header-args-w-values
442 '((cache .
((no yes
)))
444 (colnames .
((nil no yes
)))
445 (comments .
((no link yes org both noweb
)))
447 (eval .
((never query
)))
448 (exports .
((code results both none
)))
452 (hlines .
((no yes
)))
453 (mkdirp .
((yes no
)))
456 (noweb .
((yes no tangle no-export strip-export
)))
459 (padline .
((yes no
)))
462 (results .
((file list vector table scalar verbatim
)
463 (raw html latex org code pp drawer
)
464 (replace silent none append prepend
)
466 (rownames .
((no yes
)))
470 (tangle .
((tangle yes no
:any
)))
471 (tangle-mode .
((#o755
#o555
#o444
:any
)))
475 (defconst org-babel-header-arg-names
476 (mapcar #'car org-babel-common-header-args-w-values
)
477 "Common header arguments used by org-babel.
478 Note that individual languages may define their own language
479 specific header arguments as well.")
481 (defvar org-babel-default-header-args
482 '((:session .
"none") (:results .
"replace") (:exports .
"code")
483 (:cache .
"no") (:noweb .
"no") (:hlines .
"no") (:tangle .
"no"))
484 "Default arguments to use when evaluating a source block.")
486 (defvar org-babel-default-inline-header-args
487 '((:session .
"none") (:results .
"replace") (:exports .
"results"))
488 "Default arguments to use when evaluating an inline source block.")
490 (defvar org-babel-data-names
'("tblname" "results" "name"))
492 (defvar org-babel-result-regexp
493 (concat "^[ \t]*#\\+"
494 (regexp-opt org-babel-data-names t
)
496 ;; FIXME The string below is `org-ts-regexp'
497 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
498 " \\)?\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*")
499 "Regular expression used to match result lines.
500 If the results are associated with a hash key then the hash will
501 be saved in the second match data.")
503 (defvar org-babel-result-w-name-regexp
504 (concat org-babel-result-regexp
505 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
507 (defvar org-babel-min-lines-for-block-output
10
508 "The minimum number of lines for block output.
509 If number of lines of output is equal to or exceeds this
510 value, the output is placed in a #+begin_example...#+end_example
511 block. Otherwise the output is marked as literal by inserting
512 colons at the starts of the lines. This variable only takes
513 effect if the :results output option is in effect.")
515 (defvar org-babel-noweb-error-langs nil
516 "Languages for which Babel will raise literate programming errors.
517 List of languages for which errors should be raised when the
518 source code block satisfying a noweb reference in this language
519 can not be resolved.")
521 (defvar org-babel-hash-show
4
522 "Number of initial characters to show of a hidden results hash.")
524 (defvar org-babel-hash-show-time nil
525 "Non-nil means show the time the code block was evaluated in the result hash.")
527 (defvar org-babel-after-execute-hook nil
528 "Hook for functions to be called after `org-babel-execute-src-block'")
530 (defun org-babel-named-src-block-regexp-for-name (name)
531 "This generates a regexp used to match a src block named NAME."
532 (concat org-babel-src-name-regexp
(regexp-quote name
)
533 "[ \t(]*[\r\n]\\(?:^#.*[\r\n]\\)*"
534 (substring org-babel-src-block-regexp
1)))
536 (defun org-babel-named-data-regexp-for-name (name)
537 "This generates a regexp used to match data named NAME."
538 (concat org-babel-result-regexp
(regexp-quote name
) "\\([ \t]\\|$\\)"))
541 (defvar call-process-region
)
542 (defvar org-babel-current-src-block-location nil
543 "Marker pointing to the src block currently being executed.
544 This may also point to a call line or an inline code block. If
545 multiple blocks are being executed (e.g., in chained execution
546 through use of the :var header argument) this marker points to
547 the outer-most code block.")
550 (defun org-babel-execute-src-block (&optional arg info params
)
551 "Execute the current source code block.
552 Insert the results of execution into the buffer. Source code
553 execution and the collection and formatting of results can be
554 controlled through a variety of header arguments.
556 With prefix argument ARG, force re-execution even if an existing
557 result cached in the buffer would otherwise have been returned.
559 Optionally supply a value for INFO in the form returned by
560 `org-babel-get-src-block-info'.
562 Optionally supply a value for PARAMS which will be merged with
563 the header arguments specified at the front of the source code
566 (let* ((org-babel-current-src-block-location
567 (or org-babel-current-src-block-location
569 (org-babel-where-is-src-block-head)))
572 (org-babel-get-src-block-info)))
573 (merged-params (org-babel-merge-params (nth 2 info
) params
)))
574 (when (org-babel-check-evaluate
575 (let ((i info
)) (setf (nth 2 i
) merged-params
) i
))
576 (let* ((params (if params
577 (org-babel-process-params merged-params
)
579 (cachep (and (not arg
) (cdr (assoc :cache params
))
580 (string= "yes" (cdr (assoc :cache params
)))))
581 (new-hash (when cachep
(org-babel-sha1-hash info
)))
582 (old-hash (when cachep
(org-babel-current-result-hash)))
583 (cache-current-p (and (not arg
) new-hash
584 (equal new-hash old-hash
))))
587 (save-excursion ;; return cached result
588 (goto-char (org-babel-where-is-src-block-result nil info
))
589 (end-of-line 1) (forward-char 1)
590 (let ((result (org-babel-read-result)))
591 (message (replace-regexp-in-string
592 "%" "%%" (format "%S" result
))) result
)))
593 ((org-babel-confirm-evaluate
594 (let ((i info
)) (setf (nth 2 i
) merged-params
) i
))
595 (let* ((lang (nth 0 info
))
596 (result-params (cdr (assoc :result-params params
)))
597 (body (setf (nth 1 info
)
598 (if (org-babel-noweb-p params
:eval
)
599 (org-babel-expand-noweb-references info
)
601 (dir (cdr (assoc :dir params
)))
603 (or (and dir
(file-name-as-directory (expand-file-name dir
)))
605 (org-babel-call-process-region-original ;; for tramp handler
606 (or (org-bound-and-true-p
607 org-babel-call-process-region-original
)
608 (symbol-function 'call-process-region
)))
609 (indent (nth 5 info
))
612 (let ((call-process-region
614 (apply 'org-babel-tramp-handle-call-process-region
618 (let ((f (intern (concat "org-babel-execute:" f
))))
619 (when (fboundp f
) f
)))))
621 (or (funcall lang-check lang
)
624 (cdr (assoc lang org-src-lang-modes
))))
625 (error "No org-babel-execute function for %s!"
627 (message "executing %s code block%s..."
629 (if (nth 4 info
) (format " (%s)" (nth 4 info
)) ""))
630 (if (member "none" result-params
)
632 (funcall cmd body params
)
633 (message "result silenced")
636 (let ((result (funcall cmd body params
)))
637 (if (and (eq (cdr (assoc :result-type params
))
639 (or (member "vector" result-params
)
640 (member "table" result-params
))
641 (not (listp result
)))
642 (list (list result
)) result
)))
643 ;; If non-empty result and :file then write to :file.
644 (when (cdr (assoc :file params
))
646 (with-temp-file (cdr (assoc :file params
))
648 (org-babel-format-result
649 result
(cdr (assoc :sep
(nth 2 info
)))))))
650 (setq result
(cdr (assoc :file params
))))
651 ;; Possibly perform post process provided its appropriate.
652 (when (cdr (assoc :post params
))
653 (let ((*this
* (if (cdr (assoc :file params
))
654 (org-babel-result-to-file
655 (cdr (assoc :file params
))
656 (when (assoc :file-desc params
)
657 (or (cdr (assoc :file-desc params
))
660 (setq result
(org-babel-ref-resolve
661 (cdr (assoc :post params
))))
662 (when (cdr (assoc :file params
))
664 (remove "file" result-params
)))))
665 (org-babel-insert-result
666 result result-params info new-hash indent lang
))
667 (run-hooks 'org-babel-after-execute-hook
)
669 (setq call-process-region
670 'org-babel-call-process-region-original
)))))))))
672 (defun org-babel-expand-body:generic
(body params
&optional var-lines
)
673 "Expand BODY with PARAMS.
674 Expand a block of code with org-babel according to its header
675 arguments. This generic implementation of body expansion is
676 called for languages which have not defined their own specific
677 org-babel-expand-body:lang function."
678 (let ((pro (cdr (assoc :prologue params
)))
679 (epi (cdr (assoc :epilogue params
))))
680 (mapconcat #'identity
681 (append (when pro
(list pro
))
684 (when epi
(list epi
)))
688 (defun org-babel-expand-src-block (&optional arg info params
)
689 "Expand the current source code block.
690 Expand according to the source code block's header
691 arguments and pop open the results in a preview buffer."
693 (let* ((info (or info
(org-babel-get-src-block-info)))
695 (params (setf (nth 2 info
)
696 (sort (org-babel-merge-params (nth 2 info
) params
)
697 (lambda (el1 el2
) (string< (symbol-name (car el1
))
698 (symbol-name (car el2
)))))))
699 (body (setf (nth 1 info
)
700 (if (org-babel-noweb-p params
:eval
)
701 (org-babel-expand-noweb-references info
) (nth 1 info
))))
702 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
703 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
706 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
707 (org-babel-expand-body:generic
708 body params
(and (fboundp assignments-cmd
)
709 (funcall assignments-cmd params
))))))
710 (if (org-called-interactively-p 'any
)
713 (concat "*Org-Babel Preview " (buffer-name) "[ " lang
" ]*"))
716 (defun org-babel-edit-distance (s1 s2
)
717 "Return the edit (levenshtein) distance between strings S1 S2."
718 (let* ((l1 (length s1
))
720 (dist (vconcat (mapcar (lambda (_) (make-vector (1+ l2
) nil
))
721 (number-sequence 1 (1+ l1
)))))
722 (in (lambda (i j
) (aref (aref dist i
) j
))))
723 (setf (aref (aref dist
0) 0) 0)
724 (dolist (j (number-sequence 1 l2
))
725 (setf (aref (aref dist
0) j
) j
))
726 (dolist (i (number-sequence 1 l1
))
727 (setf (aref (aref dist i
) 0) i
)
728 (dolist (j (number-sequence 1 l2
))
729 (setf (aref (aref dist i
) j
)
731 (1+ (funcall in
(1- i
) j
))
732 (1+ (funcall in i
(1- j
)))
733 (+ (if (equal (aref s1
(1- i
)) (aref s2
(1- j
))) 0 1)
734 (funcall in
(1- i
) (1- j
)))))))
737 (defun org-babel-combine-header-arg-lists (original &rest others
)
738 "Combine a number of lists of header argument names and arguments."
739 (let ((results (copy-sequence original
)))
740 (dolist (new-list others
)
741 (dolist (arg-pair new-list
)
742 (let ((header (car arg-pair
))
743 (args (cdr arg-pair
)))
745 (cons arg-pair
(org-remove-if
746 (lambda (pair) (equal header
(car pair
)))
751 (defun org-babel-check-src-block ()
752 "Check for misspelled header arguments in the current code block."
754 ;; TODO: report malformed code block
755 ;; TODO: report incompatible combinations of header arguments
756 ;; TODO: report uninitialized variables
757 (let ((too-close 2) ;; <- control closeness to report potential match
758 (names (mapcar #'symbol-name org-babel-header-arg-names
)))
759 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg
)) 1))
760 (and (org-babel-where-is-src-block-head)
761 (org-babel-parse-header-arguments
763 (match-string 4))))))
765 (when (and (not (string= header name
))
766 (<= (org-babel-edit-distance header name
) too-close
)
767 (not (member header names
)))
768 (error "Supplied header \"%S\" is suspiciously close to \"%S\""
770 (message "No suspicious header arguments found.")))
773 (defun org-babel-insert-header-arg ()
774 "Insert a header argument selecting from lists of common args and values."
776 (let* ((lang (car (org-babel-get-src-block-info 'light
)))
777 (lang-headers (intern (concat "org-babel-header-args:" lang
)))
778 (headers (org-babel-combine-header-arg-lists
779 org-babel-common-header-args-w-values
780 (when (boundp lang-headers
) (eval lang-headers
))))
781 (arg (org-icompleting-read
784 (lambda (header-spec) (symbol-name (car header-spec
)))
787 (let ((vals (cdr (assoc (intern arg
) headers
))))
793 (read-from-minibuffer "value: "))
797 (let ((arg (org-icompleting-read
799 (cons "default" (mapcar #'symbol-name group
)))))
800 (if (and arg
(not (string= "default" arg
)))
805 ;; Add support for completing-read insertion of header arguments after ":"
806 (defun org-babel-header-arg-expand ()
807 "Call `org-babel-enter-header-arg-w-completion' in appropriate contexts."
808 (when (and (equal (char-before) ?\
:) (org-babel-where-is-src-block-head))
809 (org-babel-enter-header-arg-w-completion (match-string 2))))
811 (defun org-babel-enter-header-arg-w-completion (&optional lang
)
812 "Insert header argument appropriate for LANG with completion."
813 (let* ((lang-headers-var (intern (concat "org-babel-header-args:" lang
)))
814 (lang-headers (when (boundp lang-headers-var
) (eval lang-headers-var
)))
815 (headers-w-values (org-babel-combine-header-arg-lists
816 org-babel-common-header-args-w-values lang-headers
))
817 (headers (mapcar #'symbol-name
(mapcar #'car headers-w-values
)))
818 (header (org-completing-read "Header Arg: " headers
))
819 (args (cdr (assoc (intern header
) headers-w-values
)))
820 (arg (when (and args
(listp args
))
822 (format "%s: " header
)
823 (mapcar #'symbol-name
(apply #'append args
))))))
824 (insert (concat header
" " (or arg
"")))
827 (add-hook 'org-tab-first-hook
'org-babel-header-arg-expand
)
830 (defun org-babel-load-in-session (&optional arg info
)
831 "Load the body of the current source-code block.
832 Evaluate the header arguments for the source block before
833 entering the session. After loading the body this pops open the
836 (let* ((info (or info
(org-babel-get-src-block-info)))
838 (params (nth 2 info
))
840 (user-error "No src code block at point")
842 (if (org-babel-noweb-p params
:eval
)
843 (org-babel-expand-noweb-references info
)
845 (session (cdr (assoc :session params
)))
846 (dir (cdr (assoc :dir params
)))
848 (or (and dir
(file-name-as-directory dir
)) default-directory
))
849 (cmd (intern (concat "org-babel-load-session:" lang
))))
850 (unless (fboundp cmd
)
851 (error "No org-babel-load-session function for %s!" lang
))
852 (pop-to-buffer (funcall cmd session body params
))
856 (defun org-babel-initiate-session (&optional arg info
)
857 "Initiate session for current code block.
858 If called with a prefix argument then resolve any variable
859 references in the header arguments and assign these variables in
860 the session. Copy the body of the code block to the kill ring."
862 (let* ((info (or info
(org-babel-get-src-block-info (not arg
))))
865 (params (nth 2 info
))
866 (session (cdr (assoc :session params
)))
867 (dir (cdr (assoc :dir params
)))
869 (or (and dir
(file-name-as-directory dir
)) default-directory
))
870 (init-cmd (intern (format "org-babel-%s-initiate-session" lang
)))
871 (prep-cmd (intern (concat "org-babel-prep-session:" lang
))))
872 (if (and (stringp session
) (string= session
"none"))
873 (error "This block is not using a session!"))
874 (unless (fboundp init-cmd
)
875 (error "No org-babel-initiate-session function for %s!" lang
))
876 (with-temp-buffer (insert (org-babel-trim body
))
877 (copy-region-as-kill (point-min) (point-max)))
879 (unless (fboundp prep-cmd
)
880 (error "No org-babel-prep-session function for %s!" lang
))
881 (funcall prep-cmd session params
))
882 (funcall init-cmd session params
)))
885 (defun org-babel-switch-to-session (&optional arg info
)
886 "Switch to the session of the current code block.
887 Uses `org-babel-initiate-session' to start the session. If called
888 with a prefix argument then this is passed on to
889 `org-babel-initiate-session'."
891 (pop-to-buffer (org-babel-initiate-session arg info
))
894 (defalias 'org-babel-pop-to-session
'org-babel-switch-to-session
)
896 (defvar org-src-window-setup
)
899 (defun org-babel-switch-to-session-with-code (&optional arg info
)
900 "Switch to code buffer and display session."
904 (let ((other-window-buffer (window-buffer (next-window))))
905 (set-window-buffer (next-window) (current-buffer))
906 (set-window-buffer (selected-window) other-window-buffer
))
908 (info (org-babel-get-src-block-info))
909 (org-src-window-setup 'reorganize-frame
))
911 (org-babel-switch-to-session arg info
))
913 (funcall swap-windows
)))
915 (defmacro org-babel-do-in-edit-buffer
(&rest body
)
916 "Evaluate BODY in edit buffer if there is a code block at point.
917 Return t if a code block was found at point, nil otherwise."
918 `(let ((org-src-window-setup 'switch-invisibly
))
919 (when (and (org-babel-where-is-src-block-head)
920 (org-edit-src-code nil nil nil
))
921 (unwind-protect (progn ,@body
)
922 (if (org-bound-and-true-p org-edit-src-from-org-mode
)
923 (org-edit-src-exit)))
925 (def-edebug-spec org-babel-do-in-edit-buffer
(body))
927 (defun org-babel-do-key-sequence-in-edit-buffer (key)
928 "Read key sequence and execute the command in edit buffer.
929 Enter a key sequence to be executed in the language major-mode
930 edit buffer. For example, TAB will alter the contents of the
931 Org-mode code block according to the effect of TAB in the
932 language major-mode buffer. For languages that support
933 interactive sessions, this can be used to send code from the Org
934 buffer to the session for evaluation using the native major-mode
935 evaluation mechanisms."
936 (interactive "kEnter key-sequence to execute in edit buffer: ")
937 (org-babel-do-in-edit-buffer
939 (key-binding (or key
(read-key-sequence nil
))))))
941 (defvar org-bracket-link-regexp
)
943 (defun org-babel-active-location-p ()
944 (memq (car (save-match-data (org-element-context)))
945 '(babel-call inline-babel-call inline-src-block src-block
)))
948 (defun org-babel-open-src-block-result (&optional re-run
)
949 "If `point' is on a src block then open the results of the
950 source code block, otherwise return nil. With optional prefix
951 argument RE-RUN the source-code block is evaluated even if
952 results already exist."
954 (let ((info (org-babel-get-src-block-info 'light
)))
957 ;; go to the results, if there aren't any then run the block
958 (goto-char (or (and (not re-run
) (org-babel-where-is-src-block-result))
959 (progn (org-babel-execute-src-block)
960 (org-babel-where-is-src-block-result))))
962 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
964 (if (looking-at org-bracket-link-regexp
)
967 (let ((r (org-babel-format-result
968 (org-babel-read-result) (cdr (assoc :sep
(nth 2 info
))))))
969 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
970 (delete-region (point-min) (point-max))
975 (defmacro org-babel-map-src-blocks
(file &rest body
)
976 "Evaluate BODY forms on each source-block in FILE.
977 If FILE is nil evaluate BODY forms on source blocks in current
978 buffer. During evaluation of BODY the following local variables
979 are set relative to the currently matched code block.
981 full-block ------- string holding the entirety of the code block
982 beg-block -------- point at the beginning of the code block
983 end-block -------- point at the end of the matched code block
984 lang ------------- string holding the language of the code block
985 beg-lang --------- point at the beginning of the lang
986 end-lang --------- point at the end of the lang
987 switches --------- string holding the switches
988 beg-switches ----- point at the beginning of the switches
989 end-switches ----- point at the end of the switches
990 header-args ------ string holding the header-args
991 beg-header-args -- point at the beginning of the header-args
992 end-header-args -- point at the end of the header-args
993 body ------------- string holding the body of the code block
994 beg-body --------- point at the beginning of the body
995 end-body --------- point at the end of the body"
997 (let ((tempvar (make-symbol "file")))
998 `(let* ((,tempvar
,file
)
999 (visited-p (or (null ,tempvar
)
1000 (get-file-buffer (expand-file-name ,tempvar
))))
1001 (point (point)) to-be-removed
)
1002 (save-window-excursion
1003 (when ,tempvar
(find-file ,tempvar
))
1004 (setq to-be-removed
(current-buffer))
1005 (goto-char (point-min))
1006 (while (re-search-forward org-babel-src-block-regexp nil t
)
1007 (when (org-babel-active-location-p)
1008 (goto-char (match-beginning 0))
1009 (let ((full-block (match-string 0))
1010 (beg-block (match-beginning 0))
1011 (end-block (match-end 0))
1012 (lang (match-string 2))
1013 (beg-lang (match-beginning 2))
1014 (end-lang (match-end 2))
1015 (switches (match-string 3))
1016 (beg-switches (match-beginning 3))
1017 (end-switches (match-end 3))
1018 (header-args (match-string 4))
1019 (beg-header-args (match-beginning 4))
1020 (end-header-args (match-end 4))
1021 (body (match-string 5))
1022 (beg-body (match-beginning 5))
1023 (end-body (match-end 5)))
1025 (goto-char end-block
)))))
1026 (unless visited-p
(kill-buffer to-be-removed
))
1027 (goto-char point
))))
1028 (def-edebug-spec org-babel-map-src-blocks
(form body
))
1031 (defmacro org-babel-map-inline-src-blocks
(file &rest body
)
1032 "Evaluate BODY forms on each inline source-block in FILE.
1033 If FILE is nil evaluate BODY forms on source blocks in current
1035 (declare (indent 1))
1036 (let ((tempvar (make-symbol "file")))
1037 `(let* ((,tempvar
,file
)
1038 (visited-p (or (null ,tempvar
)
1039 (get-file-buffer (expand-file-name ,tempvar
))))
1040 (point (point)) to-be-removed
)
1041 (save-window-excursion
1042 (when ,tempvar
(find-file ,tempvar
))
1043 (setq to-be-removed
(current-buffer))
1044 (goto-char (point-min))
1045 (while (re-search-forward org-babel-inline-src-block-regexp nil t
)
1046 (when (org-babel-active-location-p)
1047 (goto-char (match-beginning 1))
1048 (save-match-data ,@body
))
1049 (goto-char (match-end 0))))
1050 (unless visited-p
(kill-buffer to-be-removed
))
1051 (goto-char point
))))
1052 (def-edebug-spec org-babel-map-inline-src-blocks
(form body
))
1054 (defvar org-babel-lob-one-liner-regexp
)
1057 (defmacro org-babel-map-call-lines
(file &rest body
)
1058 "Evaluate BODY forms on each call line in FILE.
1059 If FILE is nil evaluate BODY forms on source blocks in current
1061 (declare (indent 1))
1062 (let ((tempvar (make-symbol "file")))
1063 `(let* ((,tempvar
,file
)
1064 (visited-p (or (null ,tempvar
)
1065 (get-file-buffer (expand-file-name ,tempvar
))))
1066 (point (point)) to-be-removed
)
1067 (save-window-excursion
1068 (when ,tempvar
(find-file ,tempvar
))
1069 (setq to-be-removed
(current-buffer))
1070 (goto-char (point-min))
1071 (while (re-search-forward org-babel-lob-one-liner-regexp nil t
)
1072 (when (org-babel-active-location-p)
1073 (goto-char (match-beginning 1))
1074 (save-match-data ,@body
))
1075 (goto-char (match-end 0))))
1076 (unless visited-p
(kill-buffer to-be-removed
))
1077 (goto-char point
))))
1078 (def-edebug-spec org-babel-map-call-lines
(form body
))
1081 (defmacro org-babel-map-executables
(file &rest body
)
1082 (declare (indent 1))
1083 (let ((tempvar (make-symbol "file"))
1084 (rx (make-symbol "rx")))
1085 `(let* ((,tempvar
,file
)
1086 (,rx
(concat "\\(" org-babel-src-block-regexp
1087 "\\|" org-babel-inline-src-block-regexp
1088 "\\|" org-babel-lob-one-liner-regexp
"\\)"))
1089 (visited-p (or (null ,tempvar
)
1090 (get-file-buffer (expand-file-name ,tempvar
))))
1091 (point (point)) to-be-removed
)
1092 (save-window-excursion
1093 (when ,tempvar
(find-file ,tempvar
))
1094 (setq to-be-removed
(current-buffer))
1095 (goto-char (point-min))
1096 (while (re-search-forward ,rx nil t
)
1097 (when (org-babel-active-location-p)
1098 (goto-char (match-beginning 1))
1099 (when (looking-at org-babel-inline-src-block-regexp
)
1101 (save-match-data ,@body
))
1102 (goto-char (match-end 0))))
1103 (unless visited-p
(kill-buffer to-be-removed
))
1104 (goto-char point
))))
1105 (def-edebug-spec org-babel-map-executables
(form body
))
1108 (defun org-babel-execute-buffer (&optional arg
)
1109 "Execute source code blocks in a buffer.
1110 Call `org-babel-execute-src-block' on every source block in
1111 the current buffer."
1113 (org-babel-eval-wipe-error-buffer)
1114 (org-save-outline-visibility t
1115 (org-babel-map-executables nil
1116 (if (looking-at org-babel-lob-one-liner-regexp
)
1117 (org-babel-lob-execute-maybe)
1118 (org-babel-execute-src-block arg
)))))
1121 (defun org-babel-execute-subtree (&optional arg
)
1122 "Execute source code blocks in a subtree.
1123 Call `org-babel-execute-src-block' on every source block in
1124 the current subtree."
1128 (org-narrow-to-subtree)
1129 (org-babel-execute-buffer arg
)
1133 (defun org-babel-sha1-hash (&optional info
)
1134 "Generate an sha1 hash based on the value of info."
1136 (let ((print-level nil
)
1137 (info (or info
(org-babel-get-src-block-info))))
1139 (sort (copy-sequence (nth 2 info
))
1140 (lambda (a b
) (string< (car a
) (car b
)))))
1141 (let* ((rm (lambda (lst)
1142 (dolist (p '("replace" "silent" "none"
1143 "append" "prepend"))
1144 (setq lst
(remove p lst
)))
1147 (let ((v (if (and (listp (cdr arg
)) (null (cddr arg
)))
1148 (copy-sequence (cdr arg
))
1150 (when (and v
(not (and (sequencep v
)
1154 ((and (listp v
) ; lists are sorted
1155 (member (car arg
) '(:result-params
)))
1156 (sort (funcall rm v
) #'string
<))
1157 ((and (stringp v
) ; strings are sorted
1158 (member (car arg
) '(:results
:exports
)))
1159 (mapconcat #'identity
(sort (funcall rm
(split-string v
))
1162 (let* ((it (format "%s-%s"
1165 (delq nil
(mapcar (lambda (arg)
1166 (let ((normalized (funcall norm arg
)))
1168 (format "%S" normalized
))))
1172 (when (org-called-interactively-p 'interactive
) (message hash
))
1175 (defun org-babel-current-result-hash ()
1176 "Return the current in-buffer hash."
1177 (org-babel-where-is-src-block-result)
1178 (org-no-properties (match-string 5)))
1180 (defun org-babel-set-current-result-hash (hash)
1181 "Set the current in-buffer hash to HASH."
1182 (org-babel-where-is-src-block-result)
1183 (save-excursion (goto-char (match-beginning 5))
1184 (mapc #'delete-overlay
(overlays-at (point)))
1185 (forward-char org-babel-hash-show
)
1186 (mapc #'delete-overlay
(overlays-at (point)))
1187 (replace-match hash nil nil nil
5)
1188 (goto-char (point-at-bol))
1189 (org-babel-hide-hash)))
1191 (defun org-babel-hide-hash ()
1192 "Hide the hash in the current results line.
1193 Only the initial `org-babel-hash-show' characters of the hash
1194 will remain visible."
1195 (add-to-invisibility-spec '(org-babel-hide-hash . t
))
1197 (when (and (re-search-forward org-babel-result-regexp nil t
)
1199 (let* ((start (match-beginning 5))
1200 (hide-start (+ org-babel-hash-show start
))
1202 (hash (match-string 5))
1204 (setq ov1
(make-overlay start hide-start
))
1205 (setq ov2
(make-overlay hide-start end
))
1206 (overlay-put ov2
'invisible
'org-babel-hide-hash
)
1207 (overlay-put ov1
'babel-hash hash
)))))
1209 (defun org-babel-hide-all-hashes ()
1210 "Hide the hash in the current buffer.
1211 Only the initial `org-babel-hash-show' characters of each hash
1212 will remain visible. This function should be called as part of
1213 the `org-mode-hook'."
1215 (while (and (not org-babel-hash-show-time
)
1216 (re-search-forward org-babel-result-regexp nil t
))
1217 (goto-char (match-beginning 0))
1218 (org-babel-hide-hash)
1219 (goto-char (match-end 0)))))
1220 (add-hook 'org-mode-hook
'org-babel-hide-all-hashes
)
1222 (defun org-babel-hash-at-point (&optional point
)
1223 "Return the value of the hash at POINT.
1224 The hash is also added as the last element of the kill ring.
1225 This can be called with C-c C-c."
1227 (let ((hash (car (delq nil
(mapcar
1228 (lambda (ol) (overlay-get ol
'babel-hash
))
1229 (overlays-at (or point
(point))))))))
1230 (when hash
(kill-new hash
) (message hash
))))
1231 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-hash-at-point
)
1233 (defun org-babel-result-hide-spec ()
1234 "Hide portions of results lines.
1235 Add `org-babel-hide-result' as an invisibility spec for hiding
1236 portions of results lines."
1237 (add-to-invisibility-spec '(org-babel-hide-result . t
)))
1238 (add-hook 'org-mode-hook
'org-babel-result-hide-spec
)
1240 (defvar org-babel-hide-result-overlays nil
1241 "Overlays hiding results.")
1243 (defun org-babel-result-hide-all ()
1244 "Fold all results in the current buffer."
1246 (org-babel-show-result-all)
1248 (while (re-search-forward org-babel-result-regexp nil t
)
1249 (save-excursion (goto-char (match-beginning 0))
1250 (org-babel-hide-result-toggle-maybe)))))
1252 (defun org-babel-show-result-all ()
1253 "Unfold all results in the current buffer."
1254 (mapc 'delete-overlay org-babel-hide-result-overlays
)
1255 (setq org-babel-hide-result-overlays nil
))
1258 (defun org-babel-hide-result-toggle-maybe ()
1259 "Toggle visibility of result at point."
1261 (let ((case-fold-search t
))
1263 (beginning-of-line 1)
1264 (looking-at org-babel-result-regexp
))
1265 (progn (org-babel-hide-result-toggle)
1266 t
) ;; to signal that we took action
1267 nil
))) ;; to signal that we did not
1269 (defun org-babel-hide-result-toggle (&optional force
)
1270 "Toggle the visibility of the current result."
1274 (if (re-search-forward org-babel-result-regexp nil t
)
1275 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
1277 (while (looking-at org-babel-multi-line-header-regexp
)
1279 (goto-char (- (org-babel-result-end) 1)) (point)))
1281 (if (memq t
(mapcar (lambda (overlay)
1282 (eq (overlay-get overlay
'invisible
)
1283 'org-babel-hide-result
))
1284 (overlays-at start
)))
1285 (if (or (not force
) (eq force
'off
))
1287 (when (member ov org-babel-hide-result-overlays
)
1288 (setq org-babel-hide-result-overlays
1289 (delq ov org-babel-hide-result-overlays
)))
1290 (when (eq (overlay-get ov
'invisible
)
1291 'org-babel-hide-result
)
1292 (delete-overlay ov
)))
1293 (overlays-at start
)))
1294 (setq ov
(make-overlay start end
))
1295 (overlay-put ov
'invisible
'org-babel-hide-result
)
1296 ;; make the block accessible to isearch
1298 ov
'isearch-open-invisible
1300 (when (member ov org-babel-hide-result-overlays
)
1301 (setq org-babel-hide-result-overlays
1302 (delq ov org-babel-hide-result-overlays
)))
1303 (when (eq (overlay-get ov
'invisible
)
1304 'org-babel-hide-result
)
1305 (delete-overlay ov
))))
1306 (push ov org-babel-hide-result-overlays
)))
1307 (error "Not looking at a result line"))))
1309 ;; org-tab-after-check-for-cycling-hook
1310 (add-hook 'org-tab-first-hook
'org-babel-hide-result-toggle-maybe
)
1311 ;; Remove overlays when changing major mode
1312 (add-hook 'org-mode-hook
1313 (lambda () (org-add-hook 'change-major-mode-hook
1314 'org-babel-show-result-all
'append
'local
)))
1316 (defvar org-file-properties
)
1317 (defun org-babel-params-from-properties (&optional lang
)
1318 "Retrieve parameters specified as properties.
1319 Return a list of association lists of source block params
1320 specified in the properties of the current outline entry."
1323 ;; DEPRECATED header arguments specified as separate property at
1324 ;; point of definition
1326 (org-babel-parse-multiple-vars
1329 (lambda (header-arg)
1330 (and (setq val
(org-entry-get (point) header-arg t
))
1331 (cons (intern (concat ":" header-arg
))
1332 (org-babel-read val
))))
1337 (org-babel-combine-header-arg-lists
1338 org-babel-common-header-args-w-values
1340 (setq sym
(intern (concat "org-babel-header-args:" lang
)))
1341 (and (boundp sym
) (eval sym
))))))))))
1342 ;; header arguments specified with the header-args property at
1344 (org-babel-parse-header-arguments
1345 (org-entry-get org-babel-current-src-block-location
1346 "header-args" 'inherit
))
1347 (when lang
;; language-specific header arguments at point of call
1348 (org-babel-parse-header-arguments
1349 (org-entry-get org-babel-current-src-block-location
1350 (concat "header-args:" lang
) 'inherit
))))))
1352 (defvar org-src-preserve-indentation
) ;; declare defcustom from org-src
1353 (defun org-babel-parse-src-block-match ()
1354 "Parse the results from a match of the `org-babel-src-block-regexp'."
1355 (let* ((block-indentation (length (match-string 1)))
1356 (lang (org-no-properties (match-string 2)))
1357 (lang-headers (intern (concat "org-babel-default-header-args:" lang
)))
1358 (switches (match-string 3))
1359 (body (org-no-properties
1360 (let* ((body (match-string 5))
1361 (sub-length (- (length body
) 1)))
1362 (if (and (> sub-length
0)
1363 (string= "\n" (substring body sub-length
)))
1364 (substring body
0 sub-length
)
1366 (preserve-indentation (or org-src-preserve-indentation
1368 (string-match "-i\\>" switches
)))))
1370 ;; get block body less properties, protective commas, and indentation
1373 (insert (org-unescape-code-in-string body
))
1374 (unless preserve-indentation
(org-do-remove-indentation))
1376 (apply #'org-babel-merge-params
1377 org-babel-default-header-args
1378 (when (boundp lang-headers
) (eval lang-headers
))
1380 (org-babel-params-from-properties lang
)
1381 (list (org-babel-parse-header-arguments
1382 (org-no-properties (or (match-string 4) ""))))))
1384 block-indentation
)))
1386 (defun org-babel-parse-inline-src-block-match ()
1387 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
1388 (let* ((lang (org-no-properties (match-string 2)))
1389 (lang-headers (intern (concat "org-babel-default-header-args:" lang
))))
1391 (org-unescape-code-in-string (org-no-properties (match-string 5)))
1392 (apply #'org-babel-merge-params
1393 org-babel-default-inline-header-args
1394 (if (boundp lang-headers
) (eval lang-headers
) nil
)
1396 (org-babel-params-from-properties lang
)
1397 (list (org-babel-parse-header-arguments
1398 (org-no-properties (or (match-string 4) "")))))))))
1400 (defun org-babel-balanced-split (string alts
)
1401 "Split STRING on instances of ALTS.
1402 ALTS is a cons of two character options where each option may be
1403 either the numeric code of a single character or a list of
1404 character alternatives. For example to split on balanced
1405 instances of \"[ \t]:\" set ALTS to '((32 9) . 58)."
1406 (let* ((matches (lambda (ch spec
) (if (listp spec
) (member ch spec
) (equal spec ch
))))
1407 (matched (lambda (ch last
)
1409 (and (funcall matches ch
(cdr alts
))
1410 (funcall matches last
(car alts
)))
1411 (funcall matches ch alts
))))
1412 (balance 0) (last 0)
1414 (mapc (lambda (ch) ; split on [], (), "" balanced instances of [ \t]:
1415 (setq balance
(+ balance
1416 (cond ((or (equal 91 ch
) (equal 40 ch
)) 1)
1417 ((or (equal 93 ch
) (equal 41 ch
)) -
1)
1419 (when (and (equal 34 ch
) (not (equal 92 last
)))
1420 (setq quote
(not quote
)))
1421 (setq partial
(cons ch partial
))
1422 (when (and (= balance
0) (not quote
) (funcall matched ch last
))
1423 (setq lst
(cons (apply #'string
(nreverse
1430 (string-to-list string
))
1431 (nreverse (cons (apply #'string
(nreverse partial
)) lst
))))
1433 (defun org-babel-join-splits-near-ch (ch list
)
1434 "Join splits where \"=\" is on either end of the split."
1435 (let ((last= (lambda (str) (= ch
(aref str
(1- (length str
))))))
1436 (first= (lambda (str) (= ch
(aref str
0)))))
1438 (org-reduce (lambda (acc el
)
1439 (let ((head (car acc
)))
1440 (if (and head
(or (funcall last
= head
) (funcall first
= el
)))
1441 (cons (concat head el
) (cdr acc
))
1443 list
:initial-value nil
))))
1445 (defun org-babel-parse-header-arguments (arg-string)
1446 "Parse a string of header arguments returning an alist."
1447 (when (> (length arg-string
) 0)
1448 (org-babel-parse-multiple-vars
1453 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1455 (cons (intern (match-string 1 arg
))
1456 (org-babel-read (org-babel-chomp (match-string 2 arg
))))
1457 (cons (intern (org-babel-chomp arg
)) nil
)))
1458 (let ((raw (org-babel-balanced-split arg-string
'((32 9) .
58))))
1459 (cons (car raw
) (mapcar (lambda (r) (concat ":" r
)) (cdr raw
)))))))))
1461 (defun org-babel-parse-multiple-vars (header-arguments)
1462 "Expand multiple variable assignments behind a single :var keyword.
1464 This allows expression of multiple variables with one :var as
1467 #+PROPERTY: var foo=1, bar=2"
1469 (mapc (lambda (pair)
1470 (if (eq (car pair
) :var
)
1471 (mapcar (lambda (v) (push (cons :var
(org-babel-trim v
)) results
))
1472 (org-babel-join-splits-near-ch
1473 61 (org-babel-balanced-split (cdr pair
) 32)))
1474 (push pair results
)))
1476 (nreverse results
)))
1478 (defun org-babel-process-params (params)
1479 "Expand variables in PARAMS and add summary parameters."
1480 (let* ((processed-vars (mapcar (lambda (el)
1481 (if (consp (cdr el
))
1483 (org-babel-ref-parse (cdr el
))))
1484 (org-babel-get-header params
:var
)))
1485 (vars-and-names (if (and (assoc :colname-names params
)
1486 (assoc :rowname-names params
))
1487 (list processed-vars
)
1488 (org-babel-disassemble-tables
1490 (cdr (assoc :hlines params
))
1491 (cdr (assoc :colnames params
))
1492 (cdr (assoc :rownames params
)))))
1493 (raw-result (or (cdr (assoc :results params
)) ""))
1494 (result-params (append
1495 (split-string (if (stringp raw-result
)
1498 (cdr (assoc :result-params params
)))))
1500 (mapcar (lambda (var) (cons :var var
)) (car vars-and-names
))
1502 (cons :colname-names
(or (cdr (assoc :colname-names params
))
1503 (cadr vars-and-names
)))
1504 (cons :rowname-names
(or (cdr (assoc :rowname-names params
))
1505 (caddr vars-and-names
)))
1506 (cons :result-params result-params
)
1507 (cons :result-type
(cond ((member "output" result-params
) 'output
)
1508 ((member "value" result-params
) 'value
)
1510 (org-babel-get-header params
:var
'other
))))
1512 ;; row and column names
1513 (defun org-babel-del-hlines (table)
1514 "Remove all 'hlines from TABLE."
1515 (remove 'hline table
))
1517 (defun org-babel-get-colnames (table)
1518 "Return the column names of TABLE.
1519 Return a cons cell, the `car' of which contains the TABLE less
1520 colnames, and the `cdr' of which contains a list of the column
1522 (if (equal 'hline
(nth 1 table
))
1523 (cons (cddr table
) (car table
))
1524 (cons (cdr table
) (car table
))))
1526 (defun org-babel-get-rownames (table)
1527 "Return the row names of TABLE.
1528 Return a cons cell, the `car' of which contains the TABLE less
1529 rownames, and the `cdr' of which contains a list of the rownames.
1530 Note: this function removes any hlines in TABLE."
1531 (let* ((table (org-babel-del-hlines table
))
1532 (rownames (funcall (lambda ()
1538 (setq tp
(cdr tp
))))
1540 (cons table rownames
)))
1542 (defun org-babel-put-colnames (table colnames
)
1543 "Add COLNAMES to TABLE if they exist."
1544 (if colnames
(apply 'list colnames
'hline table
) table
))
1546 (defun org-babel-put-rownames (table rownames
)
1547 "Add ROWNAMES to TABLE if they exist."
1549 (mapcar (lambda (row)
1551 (cons (or (pop rownames
) "") row
)
1555 (defun org-babel-pick-name (names selector
)
1556 "Select one out of an alist of row or column names.
1557 SELECTOR can be either a list of names in which case those names
1558 will be returned directly, or an index into the list NAMES in
1559 which case the indexed names will be return."
1560 (if (listp selector
)
1563 (if (and selector
(symbolp selector
) (not (equal t selector
)))
1564 (cdr (assoc selector names
))
1565 (if (integerp selector
)
1566 (nth (- selector
1) names
)
1567 (cdr (car (last names
))))))))
1569 (defun org-babel-disassemble-tables (vars hlines colnames rownames
)
1570 "Parse tables for further processing.
1571 Process the variables in VARS according to the HLINES,
1572 ROWNAMES and COLNAMES header arguments. Return a list consisting
1573 of the vars, cnames and rnames."
1574 (let (cnames rnames
)
1578 (when (listp (cdr var
))
1579 (when (and (not (equal colnames
"no"))
1580 (or colnames
(and (equal (nth 1 (cdr var
)) 'hline
)
1581 (not (member 'hline
(cddr (cdr var
)))))))
1582 (let ((both (org-babel-get-colnames (cdr var
))))
1583 (setq cnames
(cons (cons (car var
) (cdr both
))
1585 (setq var
(cons (car var
) (car both
)))))
1586 (when (and rownames
(not (equal rownames
"no")))
1587 (let ((both (org-babel-get-rownames (cdr var
))))
1588 (setq rnames
(cons (cons (car var
) (cdr both
))
1590 (setq var
(cons (car var
) (car both
)))))
1591 (when (and hlines
(not (equal hlines
"yes")))
1592 (setq var
(cons (car var
) (org-babel-del-hlines (cdr var
))))))
1595 (reverse cnames
) (reverse rnames
))))
1597 (defun org-babel-reassemble-table (table colnames rownames
)
1598 "Add column and row names to a table.
1599 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1600 to the table for reinsertion to org-mode."
1602 (let ((table (if (and rownames
(= (length table
) (length rownames
)))
1603 (org-babel-put-rownames table rownames
) table
)))
1604 (if (and colnames
(listp (car table
)) (= (length (car table
))
1606 (org-babel-put-colnames table colnames
) table
))
1609 (defun org-babel-where-is-src-block-head ()
1610 "Find where the current source block begins.
1611 Return the point at the beginning of the current source
1612 block. Specifically at the beginning of the #+BEGIN_SRC line.
1613 If the point is not on a source block then return nil."
1614 (let ((initial (point)) (case-fold-search t
) top bottom
)
1616 (save-excursion ;; on a source name line or a #+header line
1617 (beginning-of-line 1)
1618 (and (or (looking-at org-babel-src-name-regexp
)
1619 (looking-at org-babel-multi-line-header-regexp
))
1621 (while (and (forward-line 1)
1622 (or (looking-at org-babel-src-name-regexp
)
1623 (looking-at org-babel-multi-line-header-regexp
))))
1624 (looking-at org-babel-src-block-regexp
))
1626 (save-excursion ;; on a #+begin_src line
1627 (beginning-of-line 1)
1628 (and (looking-at org-babel-src-block-regexp
)
1630 (save-excursion ;; inside a src block
1632 (re-search-backward "^[ \t]*#\\+begin_src" nil t
) (setq top
(point))
1633 (re-search-forward "^[ \t]*#\\+end_src" nil t
) (setq bottom
(point))
1634 (< top initial
) (< initial bottom
)
1635 (progn (goto-char top
) (beginning-of-line 1)
1636 (looking-at org-babel-src-block-regexp
))
1640 (defun org-babel-goto-src-block-head ()
1641 "Go to the beginning of the current code block."
1643 (let ((head (org-babel-where-is-src-block-head)))
1644 (if head
(goto-char head
) (error "Not currently in a code block"))))
1647 (defun org-babel-goto-named-src-block (name)
1648 "Go to a named source-code block."
1650 (let ((completion-ignore-case t
)
1651 (case-fold-search t
)
1652 (under-point (thing-at-point 'line
)))
1653 (list (org-icompleting-read
1654 "source-block name: " (org-babel-src-block-names) nil t
1657 ((string-match (org-babel-noweb-wrap) under-point
)
1658 (let ((block-name (match-string 1 under-point
)))
1659 (string-match "[^(]*" block-name
)
1660 (match-string 0 block-name
)))
1662 ((string-match org-babel-lob-one-liner-regexp under-point
)
1663 (let ((source-info (car (org-babel-lob-get-info))))
1664 (if (string-match "^\\([^\\[]+?\\)\\(\\[.*\\]\\)?(" source-info
)
1665 (let ((source-name (match-string 1 source-info
)))
1668 ((string-match (concat "#\\+" org-babel-results-keyword
1669 "\\:\s+\\([^\\(]*\\)") under-point
)
1670 (match-string 1 under-point
))
1672 ((and (thing-at-point 'symbol
))
1673 (org-babel-find-named-block (thing-at-point 'symbol
))
1674 (thing-at-point 'symbol
))
1676 (let ((point (org-babel-find-named-block name
)))
1678 ;; taken from `org-open-at-point'
1679 (progn (org-mark-ring-push) (goto-char point
) (org-show-context))
1680 (message "source-code block '%s' not found in this buffer" name
))))
1682 (defun org-babel-find-named-block (name)
1683 "Find a named source-code block.
1684 Return the location of the source block identified by source
1685 NAME, or nil if no such block exists. Set match data according to
1686 org-babel-named-src-block-regexp."
1688 (let ((case-fold-search t
)
1689 (regexp (org-babel-named-src-block-regexp-for-name name
)) msg
)
1690 (goto-char (point-min))
1691 (when (or (re-search-forward regexp nil t
)
1692 (re-search-backward regexp nil t
))
1693 (match-beginning 0)))))
1695 (defun org-babel-src-block-names (&optional file
)
1696 "Returns the names of source blocks in FILE or the current buffer."
1698 (when file
(find-file file
)) (goto-char (point-min))
1699 (let ((case-fold-search t
) names
)
1700 (while (re-search-forward org-babel-src-name-w-name-regexp nil t
)
1701 (setq names
(cons (match-string 3) names
)))
1705 (defun org-babel-goto-named-result (name)
1706 "Go to a named result."
1708 (let ((completion-ignore-case t
))
1709 (list (org-icompleting-read "source-block name: "
1710 (org-babel-result-names) nil t
))))
1711 (let ((point (org-babel-find-named-result name
)))
1713 ;; taken from `org-open-at-point'
1714 (progn (goto-char point
) (org-show-context))
1715 (message "result '%s' not found in this buffer" name
))))
1717 (defun org-babel-find-named-result (name &optional point
)
1718 "Find a named result.
1719 Return the location of the result named NAME in the current
1720 buffer or nil if no such result exists."
1722 (let ((case-fold-search t
))
1723 (goto-char (or point
(point-min)))
1724 (catch 'is-a-code-block
1725 (when (re-search-forward
1726 (concat org-babel-result-regexp
1727 "[ \t]" (regexp-quote name
) "[ \t]*[\n\f\v\r]") nil t
)
1728 (when (and (string= "name" (downcase (match-string 1)))
1729 (or (beginning-of-line 1)
1730 (looking-at org-babel-src-block-regexp
)
1731 (looking-at org-babel-multi-line-header-regexp
)
1732 (looking-at org-babel-lob-one-liner-regexp
)))
1733 (throw 'is-a-code-block
(org-babel-find-named-result name
(point))))
1734 (beginning-of-line 0) (point))))))
1736 (defun org-babel-result-names (&optional file
)
1737 "Returns the names of results in FILE or the current buffer."
1739 (when file
(find-file file
)) (goto-char (point-min))
1740 (let ((case-fold-search t
) names
)
1741 (while (re-search-forward org-babel-result-w-name-regexp nil t
)
1742 (setq names
(cons (match-string 4) names
)))
1746 (defun org-babel-next-src-block (&optional arg
)
1747 "Jump to the next source block.
1748 With optional prefix argument ARG, jump forward ARG many source blocks."
1750 (org-next-block arg nil org-babel-src-block-regexp
))
1753 (defun org-babel-previous-src-block (&optional arg
)
1754 "Jump to the previous source block.
1755 With optional prefix argument ARG, jump backward ARG many source blocks."
1757 (org-previous-block arg org-babel-src-block-regexp
))
1759 (defvar org-babel-load-languages
)
1762 (defun org-babel-mark-block ()
1763 "Mark current src block."
1765 (let ((head (org-babel-where-is-src-block-head)))
1769 (looking-at org-babel-src-block-regexp
))
1770 (push-mark (match-end 5) nil t
)
1771 (goto-char (match-beginning 5)))))
1773 (defun org-babel-demarcate-block (&optional arg
)
1774 "Wrap or split the code in the region or on the point.
1775 When called from inside of a code block the current block is
1776 split. When called from outside of a code block a new code block
1777 is created. In both cases if the region is demarcated and if the
1778 region is not active then the point is demarcated."
1780 (let ((info (org-babel-get-src-block-info 'light
))
1781 (headers (progn (org-babel-where-is-src-block-head)
1783 (stars (concat (make-string (or (org-current-level) 1) ?
*) " ")))
1789 (let ((lang (nth 0 info
))
1790 (indent (make-string (nth 5 info
) ?
)))
1791 (when (string-match "^[[:space:]]*$"
1792 (buffer-substring (point-at-bol)
1794 (delete-region (point-at-bol) (point-at-eol)))
1796 (if (looking-at "^") "" "\n")
1797 indent
"#+end_src\n"
1798 (if arg stars indent
) "\n"
1799 indent
"#+begin_src " lang
1800 (if (> (length headers
) 1)
1801 (concat " " headers
) headers
)
1802 (if (looking-at "[\n\r]")
1804 (concat "\n" (make-string (current-column) ?
)))))))
1805 (move-end-of-line 2))
1806 (sort (if (org-region-active-p) (list (mark) (point)) (list (point))) #'>))
1807 (let ((start (point))
1808 (lang (org-icompleting-read
1810 (mapcar #'symbol-name
1812 (append (mapcar #'car org-babel-load-languages
)
1813 (mapcar (lambda (el) (intern (car el
)))
1814 org-src-lang-modes
))))))
1815 (body (delete-and-extract-region
1816 (if (org-region-active-p) (mark) (point)) (point))))
1817 (insert (concat (if (looking-at "^") "" "\n")
1818 (if arg
(concat stars
"\n") "")
1819 "#+begin_src " lang
"\n"
1821 (if (or (= (length body
) 0)
1822 (string-match "[\r\n]$" body
)) "" "\n")
1824 (goto-char start
) (move-end-of-line 1)))))
1826 (defvar org-babel-lob-one-liner-regexp
)
1827 (defun org-babel-where-is-src-block-result (&optional insert info hash indent
)
1828 "Find where the current source block results begin.
1829 Return the point at the beginning of the result of the current
1830 source block. Specifically at the beginning of the results line.
1831 If no result exists for this block then create a results line
1832 following the source block."
1834 (let* ((case-fold-search t
)
1835 (on-lob-line (save-excursion
1836 (beginning-of-line 1)
1837 (looking-at org-babel-lob-one-liner-regexp
)))
1838 (inlinep (when (org-babel-get-inline-src-block-matches)
1840 (name (nth 4 (or info
(org-babel-get-src-block-info 'light
))))
1841 (head (unless on-lob-line
(org-babel-where-is-src-block-head)))
1843 (when head
(goto-char head
))
1844 (org-with-wide-buffer
1846 found
;; was there a result (before we potentially insert one)
1851 ;; - return t if it is found, else return nil
1852 ;; - if it does not need to be rebuilt, then don't set end
1853 ;; - if it does need to be rebuilt then do set end
1854 name
(setq beg
(org-babel-find-named-result name
))
1856 (when (and hash
(not (string= hash
(match-string 5))))
1857 (goto-char beg
) (setq end beg
) ;; beginning of result
1859 (delete-region end
(org-babel-result-end)) nil
)))
1862 ;; - return t if it is found, else return nil
1863 ;; - if it is found, and the hash doesn't match, delete and set end
1864 (or on-lob-line
(re-search-forward "^[ \t]*#\\+end_src" nil t
))
1865 (progn (end-of-line 1)
1866 (if (eobp) (insert "\n") (forward-char 1))
1870 (progn ;; unnamed results line already exists
1872 (while (re-search-forward "[^ \f\t\n\r\v]" nil t
)
1873 (beginning-of-line 1)
1875 ((looking-at (concat org-babel-result-regexp
"\n"))
1876 (throw 'non-comment t
))
1877 ((looking-at "^[ \t]*#") (end-of-line 1))
1878 (t (throw 'non-comment nil
))))))
1879 (let ((this-hash (match-string 5)))
1881 ;; must remove and rebuild if hash!=old-hash
1882 (if (and hash
(not (string= hash this-hash
)))
1886 end
(org-babel-result-end)))
1887 (setq end nil
)))))))))))
1888 (if (not (and insert end
)) found
1891 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1893 (when (wholenump indent
) (make-string indent ?
))
1894 "#+" org-babel-results-keyword
1896 (if org-babel-hash-show-time
1898 "["(format-time-string "<%Y-%m-%d %H:%M:%S>")" "hash
"]")
1899 (concat "["hash
"]")))
1901 (when name
(concat " " name
)) "\n"))
1902 (unless beg
(insert "\n") (backward-char))
1903 (beginning-of-line 0)
1904 (if hash
(org-babel-hide-hash))
1907 (defvar org-block-regexp
)
1908 (defun org-babel-read-result ()
1909 "Read the result at `point' into emacs-lisp."
1910 (let ((case-fold-search t
) result-string
)
1912 ((org-at-table-p) (org-babel-read-table))
1913 ((org-at-item-p) (org-babel-read-list))
1914 ((looking-at org-bracket-link-regexp
) (org-babel-read-link))
1915 ((looking-at org-block-regexp
) (org-babel-trim (match-string 4)))
1916 ((or (looking-at "^[ \t]*: ") (looking-at "^[ \t]*:$"))
1919 (mapconcat (lambda (line)
1920 (or (and (> (length line
) 1)
1921 (string-match "^[ \t]*: ?\\(.+\\)" line
)
1922 (match-string 1 line
))
1926 (point) (org-babel-result-end)) "[\r\n]+")
1928 (or (org-babel-number-p result-string
) result-string
))
1929 ((looking-at org-babel-result-regexp
)
1930 (save-excursion (forward-line 1) (org-babel-read-result))))))
1932 (defun org-babel-read-table ()
1933 "Read the table at `point' into emacs-lisp."
1934 (mapcar (lambda (row)
1935 (if (and (symbolp row
) (equal row
'hline
)) row
1936 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
)) row
)))
1937 (org-table-to-lisp)))
1939 (defun org-babel-read-list ()
1940 "Read the list at `point' into emacs-lisp."
1941 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
))
1942 (mapcar #'cadr
(cdr (org-list-parse-list)))))
1944 (defvar org-link-types-re
)
1945 (defun org-babel-read-link ()
1946 "Read the link at `point' into emacs-lisp.
1947 If the path of the link is a file path it is expanded using
1948 `expand-file-name'."
1949 (let* ((case-fold-search t
)
1950 (raw (and (looking-at org-bracket-link-regexp
)
1951 (org-no-properties (match-string 1))))
1952 (type (and (string-match org-link-types-re raw
)
1953 (match-string 1 raw
))))
1955 ((not type
) (expand-file-name raw
))
1956 ((string= type
"file")
1957 (and (string-match "file\\(.*\\):\\(.+\\)" raw
)
1958 (expand-file-name (match-string 2 raw
))))
1961 (defun org-babel-format-result (result &optional sep
)
1962 "Format RESULT for writing to file."
1963 (let ((echo-res (lambda (r) (if (stringp r
) r
(format "%S" r
)))))
1967 result
(list :sep
(or sep
"\t") :fmt echo-res
))
1969 (funcall echo-res result
))))
1971 (defun org-babel-insert-result
1972 (result &optional result-params info hash indent lang
)
1973 "Insert RESULT into the current buffer.
1974 By default RESULT is inserted after the end of the
1975 current source block. With optional argument RESULT-PARAMS
1976 controls insertion of results in the org-mode file.
1977 RESULT-PARAMS can take the following values:
1979 replace - (default option) insert results after the source block
1980 replacing any previously inserted results
1982 silent -- no results are inserted into the Org-mode buffer but
1983 the results are echoed to the minibuffer and are
1984 ingested by Emacs (a potentially time consuming
1987 file ---- the results are interpreted as a file path, and are
1988 inserted into the buffer using the Org-mode file syntax
1990 list ---- the results are interpreted as an Org-mode list.
1992 raw ----- results are added directly to the Org-mode file. This
1993 is a good option if you code block will output org-mode
1996 drawer -- results are added directly to the Org-mode file as with
1997 \"raw\", but are wrapped in a RESULTS drawer, allowing
1998 them to later be replaced or removed automatically.
2000 org ----- results are added inside of a \"#+BEGIN_SRC org\" block.
2001 They are not comma-escaped when inserted, but Org syntax
2002 here will be discarded when exporting the file.
2004 html ---- results are added inside of a #+BEGIN_HTML block. This
2005 is a good option if you code block will output html
2008 latex --- results are added inside of a #+BEGIN_LATEX block.
2009 This is a good option if you code block will output
2010 latex formatted text.
2012 code ---- the results are extracted in the syntax of the source
2013 code of the language being evaluated and are added
2014 inside of a #+BEGIN_SRC block with the source-code
2015 language set appropriately. Note this relies on the
2016 optional LANG argument."
2017 (if (stringp result
)
2019 (setq result
(org-no-properties result
))
2020 (when (member "file" result-params
)
2021 (setq result
(org-babel-result-to-file
2022 result
(when (assoc :file-desc
(nth 2 info
))
2023 (or (cdr (assoc :file-desc
(nth 2 info
)))
2025 (unless (listp result
) (setq result
(format "%S" result
))))
2026 (if (and result-params
(member "silent" result-params
))
2028 (message (replace-regexp-in-string "%" "%%" (format "%S" result
)))
2033 (when (or (org-babel-get-inline-src-block-matches)
2034 (org-babel-get-lob-one-liner-matches))
2035 (goto-char (match-end 0))
2036 (insert (if (listp result
) "\n" " "))
2038 (existing-result (unless inlinep
2039 (org-babel-where-is-src-block-result
2040 t info hash indent
)))
2042 (cdr (assoc :results_switches
(nth 2 info
))))
2043 (visible-beg (copy-marker (point-min)))
2044 (visible-end (copy-marker (point-max)))
2045 ;; When results exist outside of the current visible
2046 ;; region of the buffer, be sure to widen buffer to
2048 (outside-scope-p (and existing-result
2049 (or (> visible-beg existing-result
)
2050 (<= visible-end existing-result
))))
2052 (when (and (stringp result
) ; ensure results end in a newline
2054 (> (length result
) 0)
2055 (not (or (string-equal (substring result -
1) "\n")
2056 (string-equal (substring result -
1) "\r"))))
2057 (setq result
(concat result
"\n")))
2060 (when outside-scope-p
(widen))
2061 (if (not existing-result
)
2062 (setq beg
(or inlinep
(point)))
2063 (goto-char existing-result
)
2065 (re-search-forward "#" nil t
)
2066 (setq indent
(- (current-column) 1)))
2070 ((member "replace" result-params
)
2071 (delete-region (point) (org-babel-result-end)))
2072 ((member "append" result-params
)
2073 (goto-char (org-babel-result-end)) (setq beg
(point-marker)))
2074 ((member "prepend" result-params
)))) ; already there
2075 (setq results-switches
2076 (if results-switches
(concat " " results-switches
) ""))
2077 (let ((wrap (lambda (start finish
&optional no-escape
)
2078 (goto-char end
) (insert (concat finish
"\n"))
2079 (goto-char beg
) (insert (concat start
"\n"))
2081 (org-escape-code-in-region (min (point) end
) end
))
2082 (goto-char end
) (goto-char (point-at-eol))
2083 (setq end
(point-marker))))
2084 (proper-list-p (lambda (it) (and (listp it
) (null (cdr (last it
)))))))
2085 ;; insert results based on type
2087 ;; do nothing for an empty result
2089 ;; insert a list if preferred
2090 ((member "list" result-params
)
2093 (org-list-to-generic
2096 (lambda (el) (list nil
(if (stringp el
) el
(format "%S" el
))))
2097 (if (listp result
) result
(split-string result
"\n" t
))))
2098 '(:splicep nil
:istart
"- " :iend
"\n")))
2100 ;; assume the result is a table if it's not a string
2101 ((funcall proper-list-p result
)
2103 (insert (concat (orgtbl-to-orgtbl
2105 (lambda (el) (or (listp el
) (eq el
'hline
)))
2107 result
(list result
))
2108 '(:fmt
(lambda (cell) (format "%s" cell
)))) "\n"))
2109 (goto-char beg
) (when (org-at-table-p) (org-table-align)))
2110 ((and (listp result
) (not (funcall proper-list-p result
)))
2111 (insert (format "%s\n" result
)))
2112 ((member "file" result-params
)
2113 (when inlinep
(goto-char inlinep
))
2115 (t (goto-char beg
) (insert result
)))
2116 (when (funcall proper-list-p result
) (goto-char (org-table-end)))
2117 (setq end
(point-marker))
2118 ;; possibly wrap result
2120 ((assoc :wrap
(nth 2 info
))
2121 (let ((name (or (cdr (assoc :wrap
(nth 2 info
))) "RESULTS")))
2122 (funcall wrap
(concat "#+BEGIN_" name
)
2123 (concat "#+END_" (car (org-split-string name
))))))
2124 ((member "html" result-params
)
2125 (funcall wrap
"#+BEGIN_HTML" "#+END_HTML"))
2126 ((member "latex" result-params
)
2127 (funcall wrap
"#+BEGIN_LaTeX" "#+END_LaTeX"))
2128 ((member "org" result-params
)
2129 (goto-char beg
) (if (org-at-table-p) (org-cycle))
2130 (funcall wrap
"#+BEGIN_SRC org" "#+END_SRC"))
2131 ((member "code" result-params
)
2132 (funcall wrap
(format "#+BEGIN_SRC %s%s" (or lang
"none") results-switches
)
2134 ((member "raw" result-params
)
2135 (goto-char beg
) (if (org-at-table-p) (org-cycle)))
2136 ((or (member "drawer" result-params
)
2137 ;; Stay backward compatible with <7.9.2
2138 (member "wrap" result-params
))
2139 (goto-char beg
) (if (org-at-table-p) (org-cycle))
2140 (funcall wrap
":RESULTS:" ":END:" 'no-escape
))
2141 ((and (not (funcall proper-list-p result
))
2142 (not (member "file" result-params
)))
2143 (org-babel-examplize-region beg end results-switches
)
2144 (setq end
(point)))))
2145 ;; possibly indent the results to match the #+results line
2146 (when (and (not inlinep
) (numberp indent
) indent
(> indent
0)
2147 ;; in this case `table-align' does the work for us
2148 (not (and (listp result
)
2149 (member "append" result-params
))))
2150 (indent-rigidly beg end indent
))
2152 (if (member "value" result-params
)
2153 (message "Code block returned no value.")
2154 (message "Code block produced no output."))
2155 (message "Code block evaluation complete.")))
2156 (when outside-scope-p
(narrow-to-region visible-beg visible-end
))
2157 (set-marker visible-beg nil
)
2158 (set-marker visible-end nil
))))))
2160 (defun org-babel-remove-result (&optional info
)
2161 "Remove the result of the current source block."
2163 (let ((location (org-babel-where-is-src-block-result nil info
)) start
)
2165 (setq start
(- location
1))
2167 (goto-char location
) (forward-line 1)
2168 (delete-region start
(org-babel-result-end))))))
2170 (defun org-babel-result-end ()
2171 "Return the point at the end of the current set of results."
2174 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
2175 ((org-at-item-p) (let* ((struct (org-list-struct))
2176 (prvs (org-list-prevs-alist struct
)))
2177 (org-list-get-list-end (point-at-bol) struct prvs
)))
2178 ((let ((case-fold-search t
)) (looking-at "^\\([ \t]*\\):results:"))
2179 (progn (re-search-forward (concat "^" (match-string 1) ":END:"))
2180 (forward-char 1) (point)))
2182 (let ((case-fold-search t
))
2183 (if (looking-at (concat "[ \t]*#\\+begin_\\([^ \t\n\r]+\\)"))
2184 (progn (re-search-forward (concat "[ \t]*#\\+end_" (match-string 1))
2187 (while (looking-at "[ \t]*\\(: \\|:$\\|\\[\\[\\)")
2191 (defun org-babel-result-to-file (result &optional description
)
2192 "Convert RESULT into an `org-mode' link with optional DESCRIPTION.
2193 If the `default-directory' is different from the containing
2194 file's directory then expand relative links."
2195 (when (stringp result
)
2196 (format "[[file:%s]%s]"
2197 (if (and default-directory
2199 (not (string= (expand-file-name default-directory
)
2201 (file-name-directory buffer-file-name
)))))
2202 (expand-file-name result default-directory
)
2204 (if description
(concat "[" description
"]") ""))))
2206 (defvar org-babel-capitalize-examplize-region-markers nil
2207 "Make true to capitalize begin/end example markers inserted by code blocks.")
2209 (defun org-babel-examplize-region (beg end
&optional results-switches
)
2210 "Comment out region using the inline '==' or ': ' org example quote."
2212 (let ((chars-between (lambda (b e
)
2213 (not (string-match "^[\\s]*$" (buffer-substring b e
)))))
2214 (maybe-cap (lambda (str) (if org-babel-capitalize-examplize-region-markers
2215 (upcase str
) str
))))
2216 (if (or (funcall chars-between
(save-excursion (goto-char beg
) (point-at-bol)) beg
)
2217 (funcall chars-between end
(save-excursion (goto-char end
) (point-at-eol))))
2220 (insert (format org-babel-inline-result-wrap
2221 (prog1 (buffer-substring beg end
)
2222 (delete-region beg end
)))))
2223 (let ((size (count-lines beg end
)))
2225 (cond ((= size
0)) ; do nothing for an empty result
2226 ((< size org-babel-min-lines-for-block-output
)
2229 (beginning-of-line 1) (insert ": ") (forward-line 1)))
2232 (insert (if results-switches
2234 (funcall maybe-cap
"#+begin_example")
2236 (funcall maybe-cap
"#+begin_example\n")))
2237 (if (markerp end
) (goto-char end
) (forward-char (- end beg
)))
2238 (insert (funcall maybe-cap
"#+end_example\n")))))))))
2240 (defun org-babel-update-block-body (new-body)
2241 "Update the body of the current code block to NEW-BODY."
2242 (if (not (org-babel-where-is-src-block-head))
2243 (error "Not in a source block")
2245 (replace-match (concat (org-babel-trim new-body
) "\n") nil t nil
5))
2246 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
2248 (defun org-babel-merge-params (&rest plists
)
2249 "Combine all parameter association lists in PLISTS.
2250 Later elements of PLISTS override the values of previous elements.
2251 This takes into account some special considerations for certain
2252 parameters when merging lists."
2253 (let* ((results-exclusive-groups
2254 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2255 (cdr (assoc 'results org-babel-common-header-args-w-values
))))
2256 (exports-exclusive-groups
2257 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2258 (cdr (assoc 'exports org-babel-common-header-args-w-values
))))
2260 (e-merge (lambda (exclusive-groups &rest result-params
)
2261 ;; maintain exclusivity of mutually exclusive parameters
2263 (mapc (lambda (new-params)
2264 (mapc (lambda (new-param)
2265 (mapc (lambda (exclusive-group)
2266 (when (member new-param exclusive-group
)
2267 (mapcar (lambda (excluded-param)
2274 (setq output
(org-uniquify
2275 (cons new-param output
))))
2279 params results exports tangle noweb cache vars shebang comments padline
2288 (let ((name (if (listp (cdr pair
))
2290 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
2292 (intern (match-string 1 (cdr pair
)))))))
2296 (if (member name
(mapcar #'car vars
))
2298 (push name clearnames
)
2302 (unless (equal (car p
) name
) p
))
2305 (list (cons name pair
))))
2306 ;; if no name is given and we already have named variables
2307 ;; then assign to named variables in order
2308 (if (and vars
(nth variable-index vars
))
2309 (let ((name (car (nth variable-index vars
))))
2310 (push name clearnames
) ; clear out colnames
2313 (prog1 (setf (cddr (nth variable-index vars
))
2314 (concat (symbol-name name
) "=" (cdr pair
)))
2315 (incf variable-index
)))
2316 (error "Variable \"%s\" must be assigned a default value"
2319 (setq results
(funcall e-merge results-exclusive-groups
2322 (let ((r (cdr pair
)))
2323 (if (stringp r
) r
(eval r
)))))))
2326 (setq results
(funcall e-merge results-exclusive-groups
2328 (unless (or (member "both" exports
)
2329 (member "none" exports
)
2330 (member "code" exports
))
2331 (setq exports
(funcall e-merge exports-exclusive-groups
2332 exports
'("results"))))
2333 (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))
2335 (setq exports
(funcall e-merge exports-exclusive-groups
2336 exports
(split-string (cdr pair
)))))
2337 (:tangle
;; take the latest -- always overwrite
2338 (setq tangle
(or (list (cdr pair
)) tangle
)))
2340 (setq noweb
(funcall e-merge
2341 '(("yes" "no" "tangle" "no-export"
2342 "strip-export" "eval"))
2344 (split-string (or (cdr pair
) "")))))
2346 (setq cache
(funcall e-merge
'(("yes" "no")) cache
2347 (split-string (or (cdr pair
) "")))))
2349 (setq padline
(funcall e-merge
'(("yes" "no")) padline
2350 (split-string (or (cdr pair
) "")))))
2351 (:shebang
;; take the latest -- always overwrite
2352 (setq shebang
(or (list (cdr pair
)) shebang
)))
2354 (setq comments
(funcall e-merge
'(("yes" "no")) comments
2355 (split-string (or (cdr pair
) "")))))
2356 (t ;; replace: this covers e.g. :session
2357 (setq params
(cons pair
(assq-delete-all (car pair
) params
))))))
2360 (setq vars
(reverse vars
))
2361 (while vars
(setq params
(cons (cons :var
(cddr (pop vars
))) params
)))
2362 ;; clear out col-names and row-names for replaced variables
2367 (when (assoc param params
)
2368 (setf (cdr (assoc param params
))
2369 (org-remove-if (lambda (pair) (equal (car pair
) name
))
2370 (cdr (assoc param params
))))
2371 (setf params
(org-remove-if (lambda (pair) (and (equal (car pair
) param
)
2374 (list :colname-names
:rowname-names
)))
2378 (let ((key (intern (concat ":" (symbol-name hd
))))
2380 (setf params
(cons (cons key
(mapconcat 'identity val
" ")) params
))))
2381 '(results exports tangle noweb padline cache shebang comments
))
2384 (defvar org-babel-use-quick-and-dirty-noweb-expansion nil
2385 "Set to true to use regular expressions to expand noweb references.
2386 This results in much faster noweb reference expansion but does
2387 not properly allow code blocks to inherit the \":noweb-ref\"
2388 header argument from buffer or subtree wide properties.")
2390 (defun org-babel-noweb-p (params context
)
2391 "Check if PARAMS require expansion in CONTEXT.
2392 CONTEXT may be one of :tangle, :export or :eval."
2394 (intersect (lambda (as bs
)
2396 (if (member (car as
) bs
)
2398 (funcall intersect
(cdr as
) bs
))))))
2399 (funcall intersect
(case context
2400 (:tangle
'("yes" "tangle" "no-export" "strip-export"))
2401 (:eval
'("yes" "no-export" "strip-export" "eval"))
2403 (split-string (or (cdr (assoc :noweb params
)) "")))))
2405 (defun org-babel-expand-noweb-references (&optional info parent-buffer
)
2406 "Expand Noweb references in the body of the current source code block.
2408 For example the following reference would be replaced with the
2409 body of the source-code block named 'example-block'.
2413 Note that any text preceding the <<foo>> construct on a line will
2414 be interposed between the lines of the replacement text. So for
2415 example if <<foo>> is placed behind a comment, then the entire
2416 replacement text will also be commented.
2418 This function must be called from inside of the buffer containing
2419 the source-code block which holds BODY.
2421 In addition the following syntax can be used to insert the
2422 results of evaluating the source-code block named 'example-block'.
2426 Any optional arguments can be passed to example-block by placing
2427 the arguments inside the parenthesis following the convention
2428 defined by `org-babel-lob'. For example
2430 <<example-block(a=9)>>
2432 would set the value of argument \"a\" equal to \"9\". Note that
2433 these arguments are not evaluated in the current source-code
2434 block but are passed literally to the \"example-block\"."
2435 (let* ((parent-buffer (or parent-buffer
(current-buffer)))
2436 (info (or info
(org-babel-get-src-block-info 'light
)))
2439 (ob-nww-start org-babel-noweb-wrap-start
)
2440 (ob-nww-end org-babel-noweb-wrap-end
)
2441 (comment (string= "noweb" (cdr (assoc :comments
(nth 2 info
)))))
2442 (rx-prefix (concat "\\(" org-babel-src-name-regexp
"\\|"
2443 ":noweb-ref[ \t]+" "\\)"))
2445 (nb-add (lambda (text) (setq new-body
(concat new-body text
))))
2446 (c-wrap (lambda (text)
2448 (funcall (intern (concat lang
"-mode")))
2449 (comment-region (point) (progn (insert text
) (point)))
2450 (org-babel-trim (buffer-string)))))
2451 index source-name evaluate prefix
)
2453 (org-set-local 'org-babel-noweb-wrap-start ob-nww-start
)
2454 (org-set-local 'org-babel-noweb-wrap-end ob-nww-end
)
2455 (insert body
) (goto-char (point-min))
2456 (setq index
(point))
2457 (while (and (re-search-forward (org-babel-noweb-wrap) nil t
))
2458 (save-match-data (setf source-name
(match-string 1)))
2459 (save-match-data (setq evaluate
(string-match "\(.*\)" source-name
)))
2462 (buffer-substring (match-beginning 0)
2464 (beginning-of-line 1) (point)))))
2465 ;; add interval to new-body (removing noweb reference)
2466 (goto-char (match-beginning 0))
2467 (funcall nb-add
(buffer-substring index
(point)))
2468 (goto-char (match-end 0))
2469 (setq index
(point))
2472 (with-current-buffer parent-buffer
2475 (mapconcat ;; Interpose PREFIX between every line.
2479 (let ((raw (org-babel-ref-resolve source-name
)))
2480 (if (stringp raw
) raw
(format "%S" raw
)))
2482 ;; Retrieve from the library of babel.
2483 (nth 2 (assoc (intern source-name
)
2484 org-babel-library-of-babel
))
2485 ;; Return the contents of headlines literally.
2487 (when (org-babel-ref-goto-headline-id source-name
)
2488 (org-babel-ref-headline-body)))
2489 ;; Find the expansion of reference in this buffer.
2490 (let ((rx (concat rx-prefix source-name
"[ \t\n]"))
2493 (goto-char (point-min))
2494 (if org-babel-use-quick-and-dirty-noweb-expansion
2495 (while (re-search-forward rx nil t
)
2496 (let* ((i (org-babel-get-src-block-info 'light
))
2497 (body (org-babel-expand-noweb-references i
))
2498 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2501 (let ((cs (org-babel-tangle-comment-links i
)))
2502 (concat (funcall c-wrap
(car cs
)) "\n"
2504 (funcall c-wrap
(cadr cs
))))
2506 (setq expansion
(cons sep
(cons full expansion
)))))
2507 (org-babel-map-src-blocks nil
2508 (let ((i (org-babel-get-src-block-info 'light
)))
2509 (when (equal (or (cdr (assoc :noweb-ref
(nth 2 i
)))
2512 (let* ((body (org-babel-expand-noweb-references i
))
2513 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2516 (let ((cs (org-babel-tangle-comment-links i
)))
2517 (concat (funcall c-wrap
(car cs
)) "\n"
2519 (funcall c-wrap
(cadr cs
))))
2522 (cons sep
(cons full expansion
)))))))))
2524 (mapconcat #'identity
(nreverse (cdr expansion
)) "")))
2525 ;; Possibly raise an error if named block doesn't exist.
2526 (if (member lang org-babel-noweb-error-langs
)
2528 (org-babel-noweb-wrap source-name
)
2529 "could not be resolved (see "
2530 "`org-babel-noweb-error-langs')"))
2532 "[\n\r]") (concat "\n" prefix
))))))
2533 (funcall nb-add
(buffer-substring index
(point-max))))
2536 (defun org-babel-script-escape (str &optional force
)
2537 "Safely convert tables into elisp lists."
2542 (or (and (string-equal "[" (substring str
0 1))
2543 (string-equal "]" (substring str -
1)))
2544 (and (string-equal "{" (substring str
0 1))
2545 (string-equal "}" (substring str -
1)))
2546 (and (string-equal "(" (substring str
0 1))
2547 (string-equal ")" (substring str -
1))))))
2551 (let (in-single in-double out
)
2557 (91 (if (or in-double in-single
) ; [
2560 (93 (if (or in-double in-single
) ; ]
2563 (123 (if (or in-double in-single
) ; {
2566 (125 (if (or in-double in-single
) ; }
2569 (44 (if (or in-double in-single
) ; ,
2570 (cons 44 out
) (cons 32 out
)))
2571 (39 (if in-double
; '
2573 (setq in-single
(not in-single
)) (cons 34 out
)))
2574 (34 (if in-single
; "
2575 (append (list 34 32) out
)
2576 (setq in-double
(not in-double
)) (cons 34 out
)))
2577 (t (cons ch out
)))))
2578 (string-to-list str
))
2579 (apply #'string
(reverse out
)))))
2581 (condition-case nil
(org-babel-read escaped
) (error escaped
))))
2583 (defun org-babel-read (cell &optional inhibit-lisp-eval
)
2584 "Convert the string value of CELL to a number if appropriate.
2585 Otherwise if cell looks like lisp (meaning it starts with a
2586 \"(\", \"'\", \"`\" or a \"[\") then read it as lisp,
2587 otherwise return it unmodified as a string. Optional argument
2588 NO-LISP-EVAL inhibits lisp evaluation for situations in which is
2589 it not appropriate."
2590 (if (and (stringp cell
) (not (equal cell
"")))
2591 (or (org-babel-number-p cell
)
2592 (if (and (not inhibit-lisp-eval
)
2593 (or (member (substring cell
0 1) '("(" "'" "`" "["))
2594 (string= cell
"*this*")))
2596 (if (string= (substring cell
0 1) "\"")
2598 (progn (set-text-properties 0 (length cell
) nil cell
) cell
))))
2601 (defun org-babel-number-p (string)
2602 "If STRING represents a number return its value."
2603 (if (and (string-match "[0-9]+" string
)
2604 (string-match "^-?[0-9]*\\.?[0-9]*$" string
)
2605 (= (length (substring string
(match-beginning 0)
2608 (string-to-number string
)))
2610 (defun org-babel-import-elisp-from-file (file-name &optional separator
)
2611 "Read the results located at FILE-NAME into an elisp table.
2612 If the table is trivial, then return it as a scalar."
2614 (save-window-excursion
2618 (org-table-import file-name separator
)
2619 (delete-file file-name
)
2620 (setq result
(mapcar (lambda (row)
2621 (mapcar #'org-babel-string-read row
))
2622 (org-table-to-lisp))))
2623 (error (message "Error reading results: %s" err
) nil
)))
2624 (if (null (cdr result
)) ;; if result is trivial vector, then scalarize it
2625 (if (consp (car result
))
2626 (if (null (cdr (car result
)))
2632 (defun org-babel-string-read (cell)
2633 "Strip nested \"s from around strings."
2634 (org-babel-read (or (and (stringp cell
)
2635 (string-match "\\\"\\(.+\\)\\\"" cell
)
2636 (match-string 1 cell
))
2639 (defun org-babel-chomp (string &optional regexp
)
2640 "Strip trailing spaces and carriage returns from STRING.
2641 Default regexp used is \"[ \f\t\n\r\v]\" but can be
2642 overwritten by specifying a regexp as a second argument."
2643 (let ((regexp (or regexp
"[ \f\t\n\r\v]")))
2644 (while (and (> (length string
) 0)
2645 (string-match regexp
(substring string -
1)))
2646 (setq string
(substring string
0 -
1)))
2649 (defun org-babel-trim (string &optional regexp
)
2650 "Strip leading and trailing spaces and carriage returns from STRING.
2651 Like `org-babel-chomp' only it runs on both the front and back
2653 (org-babel-chomp (org-reverse-string
2654 (org-babel-chomp (org-reverse-string string
) regexp
))
2657 (defun org-babel-tramp-handle-call-process-region
2658 (start end program
&optional delete buffer display
&rest args
)
2659 "Use Tramp to handle `call-process-region'.
2660 Fixes a bug in `tramp-handle-call-process-region'."
2661 (if (and (featurep 'tramp
) (file-remote-p default-directory
))
2662 (let ((tmpfile (tramp-compat-make-temp-file "")))
2663 (write-region start end tmpfile
)
2664 (when delete
(delete-region start end
))
2666 ;; (apply 'call-process program tmpfile buffer display args)
2668 (apply 'process-file program tmpfile buffer display args
)
2669 (delete-file tmpfile
)))
2670 ;; org-babel-call-process-region-original is the original emacs
2671 ;; definition. It is in scope from the let binding in
2672 ;; org-babel-execute-src-block
2673 (apply org-babel-call-process-region-original
2674 start end program delete buffer display args
)))
2676 (defun org-babel-local-file-name (file)
2677 "Return the local name component of FILE."
2678 (if (file-remote-p file
)
2680 (with-parsed-tramp-file-name file nil
2684 (defun org-babel-process-file-name (name &optional no-quote-p
)
2685 "Prepare NAME to be used in an external process.
2686 If NAME specifies a remote location, the remote portion of the
2687 name is removed, since in that case the process will be executing
2688 remotely. The file name is then processed by `expand-file-name'.
2689 Unless second argument NO-QUOTE-P is non-nil, the file name is
2690 additionally processed by `shell-quote-argument'"
2691 (let ((f (expand-file-name (org-babel-local-file-name name
))))
2692 (if no-quote-p f
(shell-quote-argument f
))))
2694 (defvar org-babel-temporary-directory
)
2695 (unless (or noninteractive
(boundp 'org-babel-temporary-directory
))
2696 (defvar org-babel-temporary-directory
2697 (or (and (boundp 'org-babel-temporary-directory
)
2698 (file-exists-p org-babel-temporary-directory
)
2699 org-babel-temporary-directory
)
2700 (make-temp-file "babel-" t
))
2701 "Directory to hold temporary files created to execute code blocks.
2702 Used by `org-babel-temp-file'. This directory will be removed on
2705 (defmacro org-babel-result-cond
(result-params scalar-form
&rest table-forms
)
2706 "Call the code to parse raw string results according to RESULT-PARAMS."
2708 (debug (form form
&rest form
)))
2709 (org-with-gensyms (params)
2710 `(let ((,params
,result-params
))
2711 (unless (member "none" ,params
)
2712 (if (or (member "scalar" ,params
)
2713 (member "verbatim" ,params
)
2714 (member "html" ,params
)
2715 (member "code" ,params
)
2716 (member "pp" ,params
)
2717 (and (or (member "output" ,params
)
2718 (member "raw" ,params
)
2719 (member "org" ,params
)
2720 (member "drawer" ,params
))
2721 (not (member "table" ,params
))))
2724 (def-edebug-spec org-babel-result-cond
(form form body
))
2726 (defun org-babel-temp-file (prefix &optional suffix
)
2727 "Create a temporary file in the `org-babel-temporary-directory'.
2728 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2729 value of `temporary-file-directory' temporarily set to the value
2730 of `org-babel-temporary-directory'."
2731 (if (file-remote-p default-directory
)
2733 (concat (file-remote-p default-directory
)
2734 (expand-file-name prefix temporary-file-directory
))))
2735 (make-temp-file prefix nil suffix
))
2736 (let ((temporary-file-directory
2737 (or (and (boundp 'org-babel-temporary-directory
)
2738 (file-exists-p org-babel-temporary-directory
)
2739 org-babel-temporary-directory
)
2740 temporary-file-directory
)))
2741 (make-temp-file prefix nil suffix
))))
2743 (defun org-babel-remove-temporary-directory ()
2744 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2745 (when (and (boundp 'org-babel-temporary-directory
)
2746 (file-exists-p org-babel-temporary-directory
))
2747 ;; taken from `delete-directory' in files.el
2750 (mapc (lambda (file)
2751 ;; This test is equivalent to
2752 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2753 ;; but more efficient
2754 (if (eq t
(car (file-attributes file
)))
2755 (delete-directory file
)
2756 (delete-file file
)))
2757 ;; We do not want to delete "." and "..".
2758 (directory-files org-babel-temporary-directory
'full
2759 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2760 (delete-directory org-babel-temporary-directory
))
2762 (message "Failed to remove temporary Org-babel directory %s"
2763 (if (boundp 'org-babel-temporary-directory
)
2764 org-babel-temporary-directory
2765 "[directory not defined]"))))))
2767 (add-hook 'kill-emacs-hook
'org-babel-remove-temporary-directory
)
2772 ;; generated-autoload-file: "org-loaddefs.el"
2775 ;;; ob-core.el ends here