Merge branch 'maint'
[org-mode/org-tableheadings.git] / lisp / ob-core.el
blob1f2a67c28c9d6491139f5e4de9b0d9de98dd6c2b
1 ;;; ob-core.el --- working with code blocks in org-mode
3 ;; Copyright (C) 2009-2016 Free Software Foundation, Inc.
5 ;; Authors: Eric Schulte
6 ;; Dan Davison
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/>.
25 ;;; Code:
26 (eval-when-compile
27 (require 'cl))
28 (require 'cl-lib)
29 (require 'ob-eval)
30 (require 'org-macs)
31 (require 'org-compat)
33 (defconst org-babel-exeext
34 (if (memq system-type '(windows-nt cygwin))
35 ".exe"
36 nil))
38 ;; dynamically scoped for tramp
39 (defvar org-babel-call-process-region-original nil)
40 (defvar org-babel-library-of-babel)
41 (defvar org-edit-src-content-indentation)
42 (defvar org-src-lang-modes)
44 (declare-function outline-show-all "outline" ())
45 (declare-function org-get-indentation "org" (&optional line))
46 (declare-function org-remove-indentation "org" (code &optional n))
47 (declare-function org-mark-ring-push "org" (&optional pos buffer))
48 (declare-function tramp-compat-make-temp-file "tramp-compat"
49 (filename &optional dir-flag))
50 (declare-function tramp-dissect-file-name "tramp" (name &optional nodefault))
51 (declare-function tramp-file-name-user "tramp" (vec))
52 (declare-function tramp-file-name-host "tramp" (vec))
53 (declare-function with-parsed-tramp-file-name "tramp" (filename var &rest body))
54 (declare-function org-edit-src-code "org-src" (&optional code edit-buffer-name))
55 (declare-function org-edit-src-exit "org-src" ())
56 (declare-function org-open-at-point "org" (&optional in-emacs reference-buffer))
57 (declare-function org-save-outline-visibility "org-macs" (use-markers &rest body))
58 (declare-function org-outline-overlay-data "org" (&optional use-markers))
59 (declare-function org-set-outline-overlay-data "org" (data))
60 (declare-function org-narrow-to-subtree "org" ())
61 (declare-function org-split-string "org" (string &optional separators))
62 (declare-function org-entry-get "org"
63 (pom property &optional inherit literal-nil))
64 (declare-function org-make-options-regexp "org" (kwds &optional extra))
65 (declare-function org-do-remove-indentation "org" (&optional n))
66 (declare-function org-next-block "org" (arg &optional backward block-regexp))
67 (declare-function org-previous-block "org" (arg &optional block-regexp))
68 (declare-function org-show-context "org" (&optional key))
69 (declare-function org-at-table-p "org" (&optional table-type))
70 (declare-function org-cycle "org" (&optional arg))
71 (declare-function org-uniquify "org" (list))
72 (declare-function org-current-level "org" ())
73 (declare-function org-table-import "org-table" (file arg))
74 (declare-function org-add-hook "org-compat"
75 (hook function &optional append local))
76 (declare-function org-table-align "org-table" ())
77 (declare-function org-table-end "org-table" (&optional table-type))
78 (declare-function orgtbl-to-generic "org-table" (table params))
79 (declare-function orgtbl-to-orgtbl "org-table" (table params))
80 (declare-function org-babel-tangle-comment-links "ob-tangle" (&optional info))
81 (declare-function org-babel-lob-get-info "ob-lob" nil)
82 (declare-function org-babel-ref-split-args "ob-ref" (arg-string))
83 (declare-function org-babel-ref-parse "ob-ref" (assignment))
84 (declare-function org-babel-ref-resolve "ob-ref" (ref))
85 (declare-function org-babel-ref-goto-headline-id "ob-ref" (id))
86 (declare-function org-babel-ref-headline-body "ob-ref" ())
87 (declare-function org-babel-lob-execute-maybe "ob-lob" ())
88 (declare-function org-number-sequence "org-compat" (from &optional to inc))
89 (declare-function org-at-item-p "org-list" ())
90 (declare-function org-list-to-generic "org-list" (LIST PARAMS))
91 (declare-function org-list-to-lisp "org-list" (&optional delete))
92 (declare-function org-list-struct "org-list" ())
93 (declare-function org-list-prevs-alist "org-list" (struct))
94 (declare-function org-list-get-list-end "org-list" (item struct prevs))
95 (declare-function org-completing-read "org" (&rest args))
96 (declare-function org-escape-code-in-region "org-src" (beg end))
97 (declare-function org-unescape-code-in-string "org-src" (s))
98 (declare-function org-table-to-lisp "org-table" (&optional txt))
99 (declare-function org-reverse-string "org" (string))
100 (declare-function org-element-context "org-element" (&optional element))
101 (declare-function org-element-type "org-element" (element))
102 (declare-function org-element-at-point "org-element" ())
103 (declare-function org-element-normalize-string "org-element" (s))
104 (declare-function org-element-property "org-element" (property element))
105 (declare-function org-macro-escape-arguments "org-macro" (&rest args))
107 (defgroup org-babel nil
108 "Code block evaluation and management in `org-mode' documents."
109 :tag "Babel"
110 :group 'org)
112 (defcustom org-confirm-babel-evaluate t
113 "Confirm before evaluation.
114 \\<org-mode-map>\
115 Require confirmation before interactively evaluating code
116 blocks in Org-mode buffers. The default value of this variable
117 is t, meaning confirmation is required for any code block
118 evaluation. This variable can be set to nil to inhibit any
119 future confirmation requests. This variable can also be set to a
120 function which takes two arguments the language of the code block
121 and the body of the code block. Such a function should then
122 return a non-nil value if the user should be prompted for
123 execution or nil if no prompt is required.
125 Warning: Disabling confirmation may result in accidental
126 evaluation of potentially harmful code. It may be advisable
127 remove code block execution from \\[org-ctrl-c-ctrl-c] \
128 as further protection
129 against accidental code block evaluation. The
130 `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
131 remove code block execution from the \\[org-ctrl-c-ctrl-c] keybinding."
132 :group 'org-babel
133 :version "24.1"
134 :type '(choice boolean function))
135 ;; don't allow this variable to be changed through file settings
136 (put 'org-confirm-babel-evaluate 'safe-local-variable (lambda (x) (eq x t)))
138 (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
139 "\\<org-mode-map>\
140 Remove code block evaluation from the \\[org-ctrl-c-ctrl-c] key binding."
141 :group 'org-babel
142 :version "24.1"
143 :type 'boolean)
145 (defcustom org-babel-results-keyword "RESULTS"
146 "Keyword used to name results generated by code blocks.
147 It should be \"RESULTS\". However any capitalization may be
148 used."
149 :group 'org-babel
150 :version "24.4"
151 :package-version '(Org . "8.0")
152 :type 'string
153 :safe (lambda (v)
154 (and (stringp v)
155 (eq (compare-strings "RESULTS" nil nil v nil nil t)
156 t))))
158 (defcustom org-babel-noweb-wrap-start "<<"
159 "String used to begin a noweb reference in a code block.
160 See also `org-babel-noweb-wrap-end'."
161 :group 'org-babel
162 :type 'string)
164 (defcustom org-babel-noweb-wrap-end ">>"
165 "String used to end a noweb reference in a code block.
166 See also `org-babel-noweb-wrap-start'."
167 :group 'org-babel
168 :type 'string)
170 (defcustom org-babel-inline-result-wrap "=%s="
171 "Format string used to wrap inline results.
172 This string must include a \"%s\" which will be replaced by the results."
173 :group 'org-babel
174 :type 'string)
175 (put 'org-babel-inline-result-wrap
176 'safe-local-variable
177 (lambda (value)
178 (and (stringp value)
179 (string-match-p "%s" value))))
181 (defun org-babel-noweb-wrap (&optional regexp)
182 (concat org-babel-noweb-wrap-start
183 (or regexp "\\([^ \t\n].+?[^ \t]\\|[^ \t\n]\\)")
184 org-babel-noweb-wrap-end))
186 (defvar org-babel-src-name-regexp
187 "^[ \t]*#\\+name:[ \t]*"
188 "Regular expression used to match a source name line.")
190 (defvar org-babel-multi-line-header-regexp
191 "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
192 "Regular expression used to match multi-line header arguments.")
194 (defvar org-babel-src-block-regexp
195 (concat
196 ;; (1) indentation (2) lang
197 "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
198 ;; (3) switches
199 "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
200 ;; (4) header arguments
201 "\\([^\n]*\\)\n"
202 ;; (5) body
203 "\\([^\000]*?\n\\)??[ \t]*#\\+end_src")
204 "Regexp used to identify code blocks.")
206 (defvar org-babel-inline-src-block-regexp
207 (concat
208 ;; (1) replacement target (2) lang
209 "\\(?:^\\|[^-[:alnum:]]?\\)\\(src_\\([^ \f\t\n\r\v[]+\\)"
210 ;; (3,4) (unused, headers)
211 "\\(\\|\\[[ \t]*\\(.*?\\)\\]\\)"
212 ;; (5) body
213 "{\\([^\f\n\r\v]+?\\)}\\)")
214 "Regexp used to identify inline src-blocks.")
216 (defun org-babel--get-vars (params)
217 "Return the babel variable assignments in PARAMS.
219 PARAMS is a quasi-alist of header args, whcih may contain
220 multiple entries for the key `:var'. This function returns a
221 list of the cdr of all the `:var' entries."
222 (mapcar #'cdr
223 (cl-remove-if-not (lambda (x) (eq (car x) :var)) params)))
225 (defun org-babel-get-inline-src-block-matches ()
226 "Set match data if within body of an inline source block.
227 Returns non-nil if match-data set"
228 (save-excursion
229 (let ((datum (org-element-context)))
230 (when (eq (org-element-type datum) 'inline-src-block)
231 (goto-char (org-element-property :begin datum))
232 (when (looking-at org-babel-inline-src-block-regexp)
233 t )))))
235 (defvar org-babel-inline-lob-one-liner-regexp)
236 (defun org-babel-get-lob-one-liner-matches ()
237 "Set match data if on line of an lob one liner.
238 Returns non-nil if match-data set"
239 (save-excursion
240 (let ((datum (org-element-context)))
241 (when (eq (org-element-type datum) 'inline-babel-call)
242 (goto-char (org-element-property :begin datum))))
243 (if (looking-at org-babel-inline-lob-one-liner-regexp)
245 nil)))
247 (defun org-babel-get-src-block-info (&optional light)
248 "Get information on the current source block.
250 Optional argument LIGHT does not resolve remote variable
251 references; a process which could likely result in the execution
252 of other code blocks.
254 Returns a list
255 (language body header-arguments-alist switches name indent block-head)."
256 (let ((case-fold-search t) head info name indent)
257 ;; full code block
258 (if (setq head (org-babel-where-is-src-block-head))
259 (save-excursion
260 (goto-char head)
261 (setq info (org-babel-parse-src-block-match))
262 (setq indent (car (last info)))
263 (setq info (butlast info))
264 (while (and (forward-line -1)
265 (looking-at org-babel-multi-line-header-regexp))
266 (setf (nth 2 info)
267 (org-babel-merge-params
268 (nth 2 info)
269 (org-babel-parse-header-arguments (match-string 1)))))
270 (when (looking-at (org-babel-named-src-block-regexp-for-name))
271 (setq name (org-match-string-no-properties 9))))
272 ;; inline source block
273 (when (org-babel-get-inline-src-block-matches)
274 (setq head (match-beginning 0))
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
280 (setf (nth 2 info) (org-babel-generate-file-param name (nth 2 info))))
281 (when info (append info (list name indent head)))))
283 (defvar org-babel-exp-reference-buffer nil
284 "Buffer containing original contents of the exported buffer.
285 This is used by Babel to resolve references in source blocks.
286 Its value is dynamically bound during export.")
288 (defun org-babel-check-confirm-evaluate (info)
289 "Check whether INFO allows code block evaluation.
291 Returns nil if evaluation is disallowed, t if it is
292 unconditionally allowed, and the symbol `query' if the user
293 should be asked whether to allow evaluation."
294 (let* ((headers (nth 2 info))
295 (eval (or (cdr (assq :eval headers))
296 (when (assq :noeval headers) "no")))
297 (eval-no (member eval '("no" "never")))
298 (export org-babel-exp-reference-buffer)
299 (eval-no-export (and export (member eval '("no-export" "never-export"))))
300 (noeval (or eval-no eval-no-export))
301 (query (or (equal eval "query")
302 (and export (equal eval "query-export"))
303 (if (functionp org-confirm-babel-evaluate)
304 (save-excursion
305 (goto-char (nth 6 info))
306 (funcall org-confirm-babel-evaluate
307 ;; language, code block body
308 (nth 0 info) (nth 1 info)))
309 org-confirm-babel-evaluate))))
310 (cond
311 (noeval nil)
312 (query 'query)
313 (t t))))
315 (defun org-babel-check-evaluate (info)
316 "Check if code block INFO should be evaluated.
318 Do not query the user, but do display an informative message if
319 evaluation is blocked. Returns non-nil if evaluation is not blocked."
320 (let ((evalp (org-babel-check-confirm-evaluate info)))
321 (when (null evalp)
322 (message "Evaluation of this %s code-block%sis disabled."
323 (nth 0 info)
324 (let ((name (nth 4 info))) (if name (format " (%s) " name) ""))))
325 evalp))
327 ;; Dynamically scoped for asynchronous export.
328 (defvar org-babel-confirm-evaluate-answer-no)
330 (defun org-babel-confirm-evaluate (info)
331 "Confirm evaluation of the code block INFO.
333 This query can also be suppressed by setting the value of
334 `org-confirm-babel-evaluate' to nil, in which case all future
335 interactive code block evaluations will proceed without any
336 confirmation from the user.
338 Note disabling confirmation may result in accidental evaluation
339 of potentially harmful code.
341 The variable `org-babel-confirm-evaluate-answer-no' is used by
342 the async export process, which requires a non-interactive
343 environment, to override this check."
344 (let* ((evalp (org-babel-check-confirm-evaluate info))
345 (lang (nth 0 info))
346 (name (nth 4 info))
347 (name-string (if name (format " (%s) " name) " ")))
348 (pcase evalp
349 (`nil nil)
350 (`t t)
351 (`query (or
352 (and (not (org-bound-and-true-p
353 org-babel-confirm-evaluate-answer-no))
354 (yes-or-no-p
355 (format "Evaluate this %s code block%son your system? "
356 lang name-string)))
357 (progn
358 (message "Evaluation of this %s code-block%sis aborted."
359 lang name-string)
360 nil)))
361 (x (error "Unexpected value `%s' from `org-babel-check-confirm-evaluate'" x)))))
363 ;;;###autoload
364 (defun org-babel-execute-safely-maybe ()
365 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
366 (org-babel-execute-maybe)))
368 (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-execute-safely-maybe)
370 ;;;###autoload
371 (defun org-babel-execute-maybe ()
372 (interactive)
373 (or (org-babel-execute-src-block-maybe)
374 (org-babel-lob-execute-maybe)))
376 (defmacro org-babel-when-in-src-block (&rest body)
377 "Execute BODY if point is in a source block and return t.
379 Otherwise do nothing and return nil."
380 `(if (or (org-babel-where-is-src-block-head)
381 (org-babel-get-inline-src-block-matches))
382 (progn
383 ,@body
385 nil))
387 (defun org-babel-execute-src-block-maybe ()
388 "Conditionally execute a source block.
389 Detect if this is context for a Babel src-block and if so
390 then run `org-babel-execute-src-block'."
391 (interactive)
392 (org-babel-when-in-src-block
393 (org-babel-eval-wipe-error-buffer)
394 (org-babel-execute-src-block current-prefix-arg)))
396 ;;;###autoload
397 (defun org-babel-view-src-block-info ()
398 "Display information on the current source block.
399 This includes header arguments, language and name, and is largely
400 a window into the `org-babel-get-src-block-info' function."
401 (interactive)
402 (let ((info (org-babel-get-src-block-info 'light))
403 (full (lambda (it) (> (length it) 0)))
404 (printf (lambda (fmt &rest args) (princ (apply #'format fmt args)))))
405 (when info
406 (with-help-window (help-buffer)
407 (let ((name (nth 4 info))
408 (lang (nth 0 info))
409 (switches (nth 3 info))
410 (header-args (nth 2 info)))
411 (when name (funcall printf "Name: %s\n" name))
412 (when lang (funcall printf "Lang: %s\n" lang))
413 (funcall printf "Properties:\n")
414 (funcall printf "\t:header-args \t%s\n" (org-entry-get (point) "header-args" t))
415 (funcall printf "\t:header-args:%s \t%s\n" lang (org-entry-get (point) (concat "header-args:" lang) t))
417 (when (funcall full switches) (funcall printf "Switches: %s\n" switches))
418 (funcall printf "Header Arguments:\n")
419 (dolist (pair (sort header-args
420 (lambda (a b) (string< (symbol-name (car a))
421 (symbol-name (car b))))))
422 (when (funcall full (format "%s" (cdr pair)))
423 (funcall printf "\t%S%s\t%s\n"
424 (car pair)
425 (if (> (length (format "%S" (car pair))) 7) "" "\t")
426 (cdr pair)))))))))
428 ;;;###autoload
429 (defun org-babel-expand-src-block-maybe ()
430 "Conditionally expand a source block.
431 Detect if this is context for a org-babel src-block and if so
432 then run `org-babel-expand-src-block'."
433 (interactive)
434 (org-babel-when-in-src-block
435 (org-babel-expand-src-block current-prefix-arg)))
437 ;;;###autoload
438 (defun org-babel-load-in-session-maybe ()
439 "Conditionally load a source block in a session.
440 Detect if this is context for a org-babel src-block and if so
441 then run `org-babel-load-in-session'."
442 (interactive)
443 (org-babel-when-in-src-block
444 (org-babel-load-in-session current-prefix-arg)))
446 (add-hook 'org-metaup-hook 'org-babel-load-in-session-maybe)
448 ;;;###autoload
449 (defun org-babel-pop-to-session-maybe ()
450 "Conditionally pop to a session.
451 Detect if this is context for a org-babel src-block and if so
452 then run `org-babel-switch-to-session'."
453 (interactive)
454 (org-babel-when-in-src-block
455 (org-babel-switch-to-session current-prefix-arg)))
457 (add-hook 'org-metadown-hook 'org-babel-pop-to-session-maybe)
459 (defconst org-babel-common-header-args-w-values
460 '((cache . ((no yes)))
461 (cmdline . :any)
462 (colnames . ((nil no yes)))
463 (comments . ((no link yes org both noweb)))
464 (dir . :any)
465 (eval . ((yes no no-export strip-export never-export eval never
466 query)))
467 (exports . ((code results both none)))
468 (epilogue . :any)
469 (file . :any)
470 (file-desc . :any)
471 (file-ext . :any)
472 (hlines . ((no yes)))
473 (mkdirp . ((yes no)))
474 (no-expand)
475 (noeval)
476 (noweb . ((yes no tangle no-export strip-export)))
477 (noweb-ref . :any)
478 (noweb-sep . :any)
479 (output-dir . :any)
480 (padline . ((yes no)))
481 (post . :any)
482 (prologue . :any)
483 (results . ((file list vector table scalar verbatim)
484 (raw html latex org code pp drawer)
485 (replace silent none append prepend)
486 (output value)))
487 (rownames . ((no yes)))
488 (sep . :any)
489 (session . :any)
490 (shebang . :any)
491 (tangle . ((tangle yes no :any)))
492 (tangle-mode . ((#o755 #o555 #o444 :any)))
493 (var . :any)
494 (wrap . :any)))
496 (defconst org-babel-header-arg-names
497 (mapcar #'car org-babel-common-header-args-w-values)
498 "Common header arguments used by org-babel.
499 Note that individual languages may define their own language
500 specific header arguments as well.")
502 (defconst org-babel-safe-header-args
503 '(:cache :colnames :comments :exports :epilogue :hlines :noeval
504 :noweb :noweb-ref :noweb-sep :padline :prologue :rownames
505 :sep :session :tangle :wrap
506 (:eval . ("never" "query"))
507 (:results . (lambda (str) (not (string-match "file" str)))))
508 "A list of safe header arguments for babel source blocks.
510 The list can have entries of the following forms:
511 - :ARG -> :ARG is always a safe header arg
512 - (:ARG . (VAL1 VAL2 ...)) -> :ARG is safe as a header arg if it is
513 `equal' to one of the VALs.
514 - (:ARG . FN) -> :ARG is safe as a header arg if the function FN
515 returns non-nil. FN is passed one
516 argument, the value of the header arg
517 (as a string).")
519 (defmacro org-babel-header-args-safe-fn (safe-list)
520 "Return a function that determines whether a list of header args are safe.
522 Intended usage is:
523 \(put \\='org-babel-default-header-args \\='safe-local-variable
524 (org-babel-header-args-safe-p org-babel-safe-header-args)
526 This allows org-babel languages to extend the list of safe values for
527 their `org-babel-default-header-args:foo' variable.
529 For the format of SAFE-LIST, see `org-babel-safe-header-args'."
530 `(lambda (value)
531 (and (listp value)
532 (cl-every
533 (lambda (pair)
534 (and (consp pair)
535 (org-babel-one-header-arg-safe-p pair ,safe-list)))
536 value))))
538 (defvar org-babel-default-header-args
539 '((:session . "none") (:results . "replace") (:exports . "code")
540 (:cache . "no") (:noweb . "no") (:hlines . "no") (:tangle . "no"))
541 "Default arguments to use when evaluating a source block.")
542 (put 'org-babel-default-header-args 'safe-local-variable
543 (org-babel-header-args-safe-fn org-babel-safe-header-args))
545 (defvar org-babel-default-inline-header-args
546 '((:session . "none") (:results . "replace")
547 (:exports . "results") (:hlines . "yes"))
548 "Default arguments to use when evaluating an inline source block.")
549 (put 'org-babel-default-inline-header-args 'safe-local-variable
550 (org-babel-header-args-safe-fn org-babel-safe-header-args))
552 (defvar org-babel-data-names '("tblname" "results" "name"))
554 (defvar org-babel-result-regexp
555 (concat "^[ \t]*#\\+"
556 (regexp-opt org-babel-data-names t)
557 "\\(\\[\\("
558 ;; FIXME The string below is `org-ts-regexp'
559 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
560 " \\)?\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*")
561 "Regular expression used to match result lines.
562 If the results are associated with a hash key then the hash will
563 be saved in the second match data.")
565 (defvar org-babel-result-w-name-regexp
566 (concat org-babel-result-regexp
567 "\\([^ ()\f\t\n\r\v]+\\)\\((\\(.*\\))\\|\\)"))
569 (defvar org-babel-min-lines-for-block-output 10
570 "The minimum number of lines for block output.
571 If number of lines of output is equal to or exceeds this
572 value, the output is placed in a #+begin_example...#+end_example
573 block. Otherwise the output is marked as literal by inserting
574 colons at the starts of the lines. This variable only takes
575 effect if the :results output option is in effect.")
577 (defvar org-babel-noweb-error-all-langs nil
578 "Raise errors when noweb references don't resolve.
579 Also see `org-babel-noweb-error-langs' to control noweb errors on
580 a language by language bases.")
582 (defvar org-babel-noweb-error-langs nil
583 "Languages for which Babel will raise literate programming errors.
584 List of languages for which errors should be raised when the
585 source code block satisfying a noweb reference in this language
586 can not be resolved. Also see `org-babel-noweb-error-all-langs'
587 to raise errors for all languages.")
589 (defvar org-babel-hash-show 4
590 "Number of initial characters to show of a hidden results hash.")
592 (defvar org-babel-hash-show-time nil
593 "Non-nil means show the time the code block was evaluated in the result hash.")
595 (defvar org-babel-after-execute-hook nil
596 "Hook for functions to be called after `org-babel-execute-src-block'")
598 (defun org-babel-named-src-block-regexp-for-name (&optional name)
599 "This generates a regexp used to match a src block named NAME.
600 If NAME is nil, match any name. Matched name is then put in
601 match group 9. Other match groups are defined in
602 `org-babel-src-block-regexp'."
603 (concat org-babel-src-name-regexp
604 (concat (if name (regexp-quote name) "\\(?9:.*?\\)") "[ \t]*" )
605 "\\(?:\n[ \t]*#\\+\\S-+:.*\\)*?"
606 "\n"
607 (substring org-babel-src-block-regexp 1)))
609 (defun org-babel-named-data-regexp-for-name (name)
610 "This generates a regexp used to match data named NAME."
611 (concat org-babel-result-regexp (regexp-quote name) "\\([ \t]\\|$\\)"))
613 ;;; functions
614 (defvar call-process-region)
615 (defvar org-babel-current-src-block-location nil
616 "Marker pointing to the src block currently being executed.
617 This may also point to a call line or an inline code block. If
618 multiple blocks are being executed (e.g., in chained execution
619 through use of the :var header argument) this marker points to
620 the outer-most code block.")
622 (defvar *this*)
624 ;;;###autoload
625 (defun org-babel-execute-src-block (&optional arg info params)
626 "Execute the current source code block.
627 Insert the results of execution into the buffer. Source code
628 execution and the collection and formatting of results can be
629 controlled through a variety of header arguments.
631 With prefix argument ARG, force re-execution even if an existing
632 result cached in the buffer would otherwise have been returned.
634 Optionally supply a value for INFO in the form returned by
635 `org-babel-get-src-block-info'.
637 Optionally supply a value for PARAMS which will be merged with
638 the header arguments specified at the front of the source code
639 block."
640 (interactive)
641 (let* ((org-babel-current-src-block-location
642 (or org-babel-current-src-block-location
643 (nth 6 info)
644 (org-babel-where-is-src-block-head)
645 ;; inline src block
646 (and (org-babel-get-inline-src-block-matches)
647 (match-beginning 0))))
648 (info (if info
649 (copy-tree info)
650 (org-babel-get-src-block-info))))
651 (cl-callf org-babel-merge-params (nth 2 info) params)
652 (when (org-babel-check-evaluate info)
653 (cl-callf org-babel-process-params (nth 2 info))
654 (let* ((params (nth 2 info))
655 (cachep (and (not arg) (cdr (assoc :cache params))
656 (string= "yes" (cdr (assoc :cache params)))))
657 (new-hash (when cachep (org-babel-sha1-hash info)))
658 (old-hash (when cachep (org-babel-current-result-hash)))
659 (cache-current-p (and (not arg) new-hash
660 (equal new-hash old-hash))))
661 (cond
662 (cache-current-p
663 (save-excursion ;; return cached result
664 (goto-char (org-babel-where-is-src-block-result nil info))
665 (forward-line)
666 (skip-chars-forward " \t")
667 (let ((result (org-babel-read-result)))
668 (message (replace-regexp-in-string
669 "%" "%%" (format "%S" result)))
670 result)))
671 ((org-babel-confirm-evaluate info)
672 (let* ((lang (nth 0 info))
673 (result-params (cdr (assoc :result-params params)))
674 (body (setf (nth 1 info)
675 (if (org-babel-noweb-p params :eval)
676 (org-babel-expand-noweb-references info)
677 (nth 1 info))))
678 (dir (cdr (assoc :dir params)))
679 (default-directory
680 (or (and dir (file-name-as-directory (expand-file-name dir)))
681 default-directory))
682 (org-babel-call-process-region-original ;; for tramp handler
683 (or (org-bound-and-true-p
684 org-babel-call-process-region-original)
685 (symbol-function 'call-process-region)))
686 (indent (nth 5 info))
687 result cmd)
688 (unwind-protect
689 (let ((call-process-region
690 (lambda (&rest args)
691 (apply 'org-babel-tramp-handle-call-process-region
692 args))))
693 (let ((lang-check
694 (lambda (f)
695 (let ((f (intern (concat "org-babel-execute:" f))))
696 (when (fboundp f) f)))))
697 (setq cmd
698 (or (funcall lang-check lang)
699 (funcall lang-check
700 (symbol-name
701 (cdr (assoc lang org-src-lang-modes))))
702 (error "No org-babel-execute function for %s!"
703 lang))))
704 (message "executing %s code block%s..."
705 (capitalize lang)
706 (if (nth 4 info) (format " (%s)" (nth 4 info)) ""))
707 (if (member "none" result-params)
708 (progn
709 (funcall cmd body params)
710 (message "result silenced")
711 (setq result nil))
712 (setq result
713 (let ((result (funcall cmd body params)))
714 (if (and (eq (cdr (assoc :result-type params))
715 'value)
716 (or (member "vector" result-params)
717 (member "table" result-params))
718 (not (listp result)))
719 (list (list result)) result)))
720 ;; If non-empty result and :file then write to :file.
721 (when (cdr (assoc :file params))
722 (when result
723 (with-temp-file (cdr (assoc :file params))
724 (insert
725 (org-babel-format-result
726 result (cdr (assoc :sep (nth 2 info)))))))
727 (setq result (cdr (assoc :file params))))
728 ;; Possibly perform post process provided its appropriate.
729 (when (cdr (assoc :post params))
730 (let ((*this* (if (cdr (assoc :file params))
731 (org-babel-result-to-file
732 (cdr (assoc :file params))
733 (when (assoc :file-desc params)
734 (or (cdr (assoc :file-desc params))
735 result)))
736 result)))
737 (setq result (org-babel-ref-resolve
738 (cdr (assoc :post params))))
739 (when (cdr (assoc :file params))
740 (setq result-params
741 (remove "file" result-params)))))
742 (org-babel-insert-result
743 result result-params info new-hash indent lang))
744 (run-hooks 'org-babel-after-execute-hook)
745 result)
746 (setq call-process-region
747 'org-babel-call-process-region-original)))))))))
749 (defun org-babel-expand-body:generic (body params &optional var-lines)
750 "Expand BODY with PARAMS.
751 Expand a block of code with org-babel according to its header
752 arguments. This generic implementation of body expansion is
753 called for languages which have not defined their own specific
754 org-babel-expand-body:lang function."
755 (let ((pro (cdr (assoc :prologue params)))
756 (epi (cdr (assoc :epilogue params))))
757 (mapconcat #'identity
758 (append (when pro (list pro))
759 var-lines
760 (list body)
761 (when epi (list epi)))
762 "\n")))
764 ;;;###autoload
765 (defun org-babel-expand-src-block (&optional _arg info params)
766 "Expand the current source code block.
767 Expand according to the source code block's header
768 arguments and pop open the results in a preview buffer."
769 (interactive)
770 (let* ((info (or info (org-babel-get-src-block-info)))
771 (lang (nth 0 info))
772 (params (setf (nth 2 info)
773 (sort (org-babel-merge-params (nth 2 info) params)
774 (lambda (el1 el2) (string< (symbol-name (car el1))
775 (symbol-name (car el2)))))))
776 (body (setf (nth 1 info)
777 (if (org-babel-noweb-p params :eval)
778 (org-babel-expand-noweb-references info) (nth 1 info))))
779 (expand-cmd (intern (concat "org-babel-expand-body:" lang)))
780 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
781 lang)))
782 (expanded
783 (if (fboundp expand-cmd) (funcall expand-cmd body params)
784 (org-babel-expand-body:generic
785 body params (and (fboundp assignments-cmd)
786 (funcall assignments-cmd params))))))
787 (if (org-called-interactively-p 'any)
788 (org-edit-src-code
789 expanded (concat "*Org-Babel Preview " (buffer-name) "[ " lang " ]*"))
790 expanded)))
792 (defun org-babel-edit-distance (s1 s2)
793 "Return the edit (levenshtein) distance between strings S1 S2."
794 (let* ((l1 (length s1))
795 (l2 (length s2))
796 (dist (vconcat (mapcar (lambda (_) (make-vector (1+ l2) nil))
797 (number-sequence 1 (1+ l1)))))
798 (in (lambda (i j) (aref (aref dist i) j))))
799 (setf (aref (aref dist 0) 0) 0)
800 (dolist (j (number-sequence 1 l2))
801 (setf (aref (aref dist 0) j) j))
802 (dolist (i (number-sequence 1 l1))
803 (setf (aref (aref dist i) 0) i)
804 (dolist (j (number-sequence 1 l2))
805 (setf (aref (aref dist i) j)
806 (min
807 (1+ (funcall in (1- i) j))
808 (1+ (funcall in i (1- j)))
809 (+ (if (equal (aref s1 (1- i)) (aref s2 (1- j))) 0 1)
810 (funcall in (1- i) (1- j)))))))
811 (funcall in l1 l2)))
813 (defun org-babel-combine-header-arg-lists (original &rest others)
814 "Combine a number of lists of header argument names and arguments."
815 (let ((results (copy-sequence original)))
816 (dolist (new-list others)
817 (dolist (arg-pair new-list)
818 (let ((header (car arg-pair)))
819 (setq results
820 (cons arg-pair (cl-remove-if
821 (lambda (pair) (equal header (car pair)))
822 results))))))
823 results))
825 ;;;###autoload
826 (defun org-babel-check-src-block ()
827 "Check for misspelled header arguments in the current code block."
828 (interactive)
829 ;; TODO: report malformed code block
830 ;; TODO: report incompatible combinations of header arguments
831 ;; TODO: report uninitialized variables
832 (let ((too-close 2) ;; <- control closeness to report potential match
833 (names (mapcar #'symbol-name org-babel-header-arg-names)))
834 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg)) 1))
835 (and (org-babel-where-is-src-block-head)
836 (org-babel-parse-header-arguments
837 (org-no-properties
838 (match-string 4))))))
839 (dolist (name names)
840 (when (and (not (string= header name))
841 (<= (org-babel-edit-distance header name) too-close)
842 (not (member header names)))
843 (error "Supplied header \"%S\" is suspiciously close to \"%S\""
844 header name))))
845 (message "No suspicious header arguments found.")))
847 ;;;###autoload
848 (defun org-babel-insert-header-arg (&optional header-arg value)
849 "Insert a header argument selecting from lists of common args and values."
850 (interactive)
851 (let* ((info (org-babel-get-src-block-info 'light))
852 (lang (car info))
853 (begin (nth 6 info))
854 (lang-headers (intern (concat "org-babel-header-args:" lang)))
855 (headers (org-babel-combine-header-arg-lists
856 org-babel-common-header-args-w-values
857 (when (boundp lang-headers) (eval lang-headers))))
858 (header-arg (or header-arg
859 (completing-read
860 "Header Arg: "
861 (mapcar
862 (lambda (header-spec) (symbol-name (car header-spec)))
863 headers))))
864 (vals (cdr (assoc (intern header-arg) headers)))
865 (value (or value
866 (cond
867 ((eq vals :any)
868 (read-from-minibuffer "value: "))
869 ((listp vals)
870 (mapconcat
871 (lambda (group)
872 (let ((arg (completing-read
873 "Value: "
874 (cons "default"
875 (mapcar #'symbol-name group)))))
876 (if (and arg (not (string= "default" arg)))
877 (concat arg " ")
878 "")))
879 vals ""))))))
880 (save-excursion
881 (goto-char begin)
882 (goto-char (point-at-eol))
883 (unless (= (char-before (point)) ?\ ) (insert " "))
884 (insert ":" header-arg) (when value (insert " " value)))))
886 ;; Add support for completing-read insertion of header arguments after ":"
887 (defun org-babel-header-arg-expand ()
888 "Call `org-babel-enter-header-arg-w-completion' in appropriate contexts."
889 (when (and (equal (char-before) ?\:) (org-babel-where-is-src-block-head))
890 (org-babel-enter-header-arg-w-completion (match-string 2))))
892 (defun org-babel-enter-header-arg-w-completion (&optional lang)
893 "Insert header argument appropriate for LANG with completion."
894 (let* ((lang-headers-var (intern (concat "org-babel-header-args:" lang)))
895 (lang-headers (when (boundp lang-headers-var) (eval lang-headers-var)))
896 (headers-w-values (org-babel-combine-header-arg-lists
897 org-babel-common-header-args-w-values lang-headers))
898 (headers (mapcar #'symbol-name (mapcar #'car headers-w-values)))
899 (header (org-completing-read "Header Arg: " headers))
900 (args (cdr (assoc (intern header) headers-w-values)))
901 (arg (when (and args (listp args))
902 (org-completing-read
903 (format "%s: " header)
904 (mapcar #'symbol-name (apply #'append args))))))
905 (insert (concat header " " (or arg "")))
906 (cons header arg)))
908 (add-hook 'org-tab-first-hook 'org-babel-header-arg-expand)
910 ;;;###autoload
911 (defun org-babel-load-in-session (&optional _arg info)
912 "Load the body of the current source-code block.
913 Evaluate the header arguments for the source block before
914 entering the session. After loading the body this pops open the
915 session."
916 (interactive)
917 (let* ((info (or info (org-babel-get-src-block-info)))
918 (lang (nth 0 info))
919 (params (nth 2 info))
920 (body (if (not info)
921 (user-error "No src code block at point")
922 (setf (nth 1 info)
923 (if (org-babel-noweb-p params :eval)
924 (org-babel-expand-noweb-references info)
925 (nth 1 info)))))
926 (session (cdr (assoc :session params)))
927 (dir (cdr (assoc :dir params)))
928 (default-directory
929 (or (and dir (file-name-as-directory dir)) default-directory))
930 (cmd (intern (concat "org-babel-load-session:" lang))))
931 (unless (fboundp cmd)
932 (error "No org-babel-load-session function for %s!" lang))
933 (pop-to-buffer (funcall cmd session body params))
934 (end-of-line 1)))
936 ;;;###autoload
937 (defun org-babel-initiate-session (&optional arg info)
938 "Initiate session for current code block.
939 If called with a prefix argument then resolve any variable
940 references in the header arguments and assign these variables in
941 the session. Copy the body of the code block to the kill ring."
942 (interactive "P")
943 (let* ((info (or info (org-babel-get-src-block-info (not arg))))
944 (lang (nth 0 info))
945 (body (nth 1 info))
946 (params (nth 2 info))
947 (session (cdr (assoc :session params)))
948 (dir (cdr (assoc :dir params)))
949 (default-directory
950 (or (and dir (file-name-as-directory dir)) default-directory))
951 (init-cmd (intern (format "org-babel-%s-initiate-session" lang)))
952 (prep-cmd (intern (concat "org-babel-prep-session:" lang))))
953 (if (and (stringp session) (string= session "none"))
954 (error "This block is not using a session!"))
955 (unless (fboundp init-cmd)
956 (error "No org-babel-initiate-session function for %s!" lang))
957 (with-temp-buffer (insert (org-babel-trim body))
958 (copy-region-as-kill (point-min) (point-max)))
959 (when arg
960 (unless (fboundp prep-cmd)
961 (error "No org-babel-prep-session function for %s!" lang))
962 (funcall prep-cmd session params))
963 (funcall init-cmd session params)))
965 ;;;###autoload
966 (defun org-babel-switch-to-session (&optional arg info)
967 "Switch to the session of the current code block.
968 Uses `org-babel-initiate-session' to start the session. If called
969 with a prefix argument then this is passed on to
970 `org-babel-initiate-session'."
971 (interactive "P")
972 (pop-to-buffer (org-babel-initiate-session arg info))
973 (end-of-line 1))
975 (defalias 'org-babel-pop-to-session 'org-babel-switch-to-session)
977 (defvar org-src-window-setup)
979 ;;;###autoload
980 (defun org-babel-switch-to-session-with-code (&optional arg _info)
981 "Switch to code buffer and display session."
982 (interactive "P")
983 (let ((swap-windows
984 (lambda ()
985 (let ((other-window-buffer (window-buffer (next-window))))
986 (set-window-buffer (next-window) (current-buffer))
987 (set-window-buffer (selected-window) other-window-buffer))
988 (other-window 1)))
989 (info (org-babel-get-src-block-info))
990 (org-src-window-setup 'reorganize-frame))
991 (save-excursion
992 (org-babel-switch-to-session arg info))
993 (org-edit-src-code)
994 (funcall swap-windows)))
996 ;;;###autoload
997 (defmacro org-babel-do-in-edit-buffer (&rest body)
998 "Evaluate BODY in edit buffer if there is a code block at point.
999 Return t if a code block was found at point, nil otherwise."
1000 `(let ((org-src-window-setup 'switch-invisibly))
1001 (when (and (org-babel-where-is-src-block-head)
1002 (org-edit-src-code))
1003 (unwind-protect (progn ,@body)
1004 (org-edit-src-exit))
1005 t)))
1006 (def-edebug-spec org-babel-do-in-edit-buffer (body))
1008 (defun org-babel-do-key-sequence-in-edit-buffer (key)
1009 "Read key sequence and execute the command in edit buffer.
1010 Enter a key sequence to be executed in the language major-mode
1011 edit buffer. For example, TAB will alter the contents of the
1012 Org-mode code block according to the effect of TAB in the
1013 language major-mode buffer. For languages that support
1014 interactive sessions, this can be used to send code from the Org
1015 buffer to the session for evaluation using the native major-mode
1016 evaluation mechanisms."
1017 (interactive "kEnter key-sequence to execute in edit buffer: ")
1018 (org-babel-do-in-edit-buffer
1019 (call-interactively
1020 (key-binding (or key (read-key-sequence nil))))))
1022 (defvar org-bracket-link-regexp)
1024 (defun org-babel-active-location-p ()
1025 (memq (org-element-type (save-match-data (org-element-context)))
1026 '(babel-call inline-babel-call inline-src-block src-block)))
1028 ;;;###autoload
1029 (defun org-babel-open-src-block-result (&optional re-run)
1030 "If `point' is on a src block then open the results of the
1031 source code block, otherwise return nil. With optional prefix
1032 argument RE-RUN the source-code block is evaluated even if
1033 results already exist."
1034 (interactive "P")
1035 (let ((info (org-babel-get-src-block-info 'light)))
1036 (when info
1037 (save-excursion
1038 ;; go to the results, if there aren't any then run the block
1039 (goto-char (or (and (not re-run) (org-babel-where-is-src-block-result))
1040 (progn (org-babel-execute-src-block)
1041 (org-babel-where-is-src-block-result))))
1042 (end-of-line 1)
1043 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
1044 ;; open the results
1045 (if (looking-at org-bracket-link-regexp)
1046 ;; file results
1047 (org-open-at-point)
1048 (let ((r (org-babel-format-result
1049 (org-babel-read-result) (cdr (assoc :sep (nth 2 info))))))
1050 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
1051 (delete-region (point-min) (point-max))
1052 (insert r)))
1053 t))))
1055 ;;;###autoload
1056 (defmacro org-babel-map-src-blocks (file &rest body)
1057 "Evaluate BODY forms on each source-block in FILE.
1058 If FILE is nil evaluate BODY forms on source blocks in current
1059 buffer. During evaluation of BODY the following local variables
1060 are set relative to the currently matched code block.
1062 full-block ------- string holding the entirety of the code block
1063 beg-block -------- point at the beginning of the code block
1064 end-block -------- point at the end of the matched code block
1065 lang ------------- string holding the language of the code block
1066 beg-lang --------- point at the beginning of the lang
1067 end-lang --------- point at the end of the lang
1068 switches --------- string holding the switches
1069 beg-switches ----- point at the beginning of the switches
1070 end-switches ----- point at the end of the switches
1071 header-args ------ string holding the header-args
1072 beg-header-args -- point at the beginning of the header-args
1073 end-header-args -- point at the end of the header-args
1074 body ------------- string holding the body of the code block
1075 beg-body --------- point at the beginning of the body
1076 end-body --------- point at the end of the body"
1077 (declare (indent 1))
1078 (let ((tempvar (make-symbol "file")))
1079 `(let* ((case-fold-search t)
1080 (,tempvar ,file)
1081 (visited-p (or (null ,tempvar)
1082 (get-file-buffer (expand-file-name ,tempvar))))
1083 (point (point)) to-be-removed)
1084 (save-window-excursion
1085 (when ,tempvar (find-file ,tempvar))
1086 (setq to-be-removed (current-buffer))
1087 (goto-char (point-min))
1088 (while (re-search-forward org-babel-src-block-regexp nil t)
1089 (when (org-babel-active-location-p)
1090 (goto-char (match-beginning 0))
1091 (let ((full-block (match-string 0))
1092 (beg-block (match-beginning 0))
1093 (end-block (match-end 0))
1094 (lang (match-string 2))
1095 (beg-lang (match-beginning 2))
1096 (end-lang (match-end 2))
1097 (switches (match-string 3))
1098 (beg-switches (match-beginning 3))
1099 (end-switches (match-end 3))
1100 (header-args (match-string 4))
1101 (beg-header-args (match-beginning 4))
1102 (end-header-args (match-end 4))
1103 (body (match-string 5))
1104 (beg-body (match-beginning 5))
1105 (end-body (match-end 5)))
1106 ;; Silence byte-compiler in case `body' doesn't use all
1107 ;; those variables.
1108 (ignore full-block beg-block end-block lang
1109 beg-lang end-lang switches beg-switches
1110 end-switches header-args beg-header-args
1111 end-header-args body beg-body end-body)
1112 ,@body
1113 (goto-char end-block)))))
1114 (unless visited-p (kill-buffer to-be-removed))
1115 (goto-char point))))
1116 (def-edebug-spec org-babel-map-src-blocks (form body))
1118 ;;;###autoload
1119 (defmacro org-babel-map-inline-src-blocks (file &rest body)
1120 "Evaluate BODY forms on each inline source-block in FILE.
1121 If FILE is nil evaluate BODY forms on source blocks in current
1122 buffer."
1123 (declare (indent 1))
1124 (let ((tempvar (make-symbol "file")))
1125 `(let* ((case-fold-search t)
1126 (,tempvar ,file)
1127 (visited-p (or (null ,tempvar)
1128 (get-file-buffer (expand-file-name ,tempvar))))
1129 (point (point)) to-be-removed)
1130 (save-window-excursion
1131 (when ,tempvar (find-file ,tempvar))
1132 (setq to-be-removed (current-buffer))
1133 (goto-char (point-min))
1134 (while (re-search-forward org-babel-inline-src-block-regexp nil t)
1135 (when (org-babel-active-location-p)
1136 (goto-char (match-beginning 1))
1137 (save-match-data ,@body))
1138 (goto-char (match-end 0))))
1139 (unless visited-p (kill-buffer to-be-removed))
1140 (goto-char point))))
1141 (def-edebug-spec org-babel-map-inline-src-blocks (form body))
1143 (defvar org-babel-lob-one-liner-regexp)
1145 ;;;###autoload
1146 (defmacro org-babel-map-call-lines (file &rest body)
1147 "Evaluate BODY forms on each call line in FILE.
1148 If FILE is nil evaluate BODY forms on source blocks in current
1149 buffer."
1150 (declare (indent 1))
1151 (let ((tempvar (make-symbol "file")))
1152 `(let* ((,tempvar ,file)
1153 (visited-p (or (null ,tempvar)
1154 (get-file-buffer (expand-file-name ,tempvar))))
1155 (point (point)) to-be-removed)
1156 (save-window-excursion
1157 (when ,tempvar (find-file ,tempvar))
1158 (setq to-be-removed (current-buffer))
1159 (goto-char (point-min))
1160 (while (re-search-forward org-babel-lob-one-liner-regexp nil t)
1161 (when (org-babel-active-location-p)
1162 (goto-char (match-beginning 1))
1163 (save-match-data ,@body))
1164 (goto-char (match-end 0))))
1165 (unless visited-p (kill-buffer to-be-removed))
1166 (goto-char point))))
1167 (def-edebug-spec org-babel-map-call-lines (form body))
1169 ;;;###autoload
1170 (defmacro org-babel-map-executables (file &rest body)
1171 (declare (indent 1))
1172 (let ((tempvar (make-symbol "file"))
1173 (rx (make-symbol "rx")))
1174 `(let* ((,tempvar ,file)
1175 (,rx (concat "\\(" org-babel-src-block-regexp
1176 "\\|" org-babel-inline-src-block-regexp
1177 "\\|" org-babel-lob-one-liner-regexp "\\)"))
1178 (visited-p (or (null ,tempvar)
1179 (get-file-buffer (expand-file-name ,tempvar))))
1180 (point (point)) to-be-removed)
1181 (save-window-excursion
1182 (when ,tempvar (find-file ,tempvar))
1183 (setq to-be-removed (current-buffer))
1184 (goto-char (point-min))
1185 (while (re-search-forward ,rx nil t)
1186 (when (org-babel-active-location-p)
1187 (goto-char (match-beginning 1))
1188 (when (looking-at org-babel-inline-src-block-regexp)
1189 (forward-char 1))
1190 (save-match-data ,@body))
1191 (goto-char (match-end 0))))
1192 (unless visited-p (kill-buffer to-be-removed))
1193 (goto-char point))))
1194 (def-edebug-spec org-babel-map-executables (form body))
1196 ;;;###autoload
1197 (defun org-babel-execute-buffer (&optional arg)
1198 "Execute source code blocks in a buffer.
1199 Call `org-babel-execute-src-block' on every source block in
1200 the current buffer."
1201 (interactive "P")
1202 (org-babel-eval-wipe-error-buffer)
1203 (org-save-outline-visibility t
1204 (org-babel-map-executables nil
1205 (if (looking-at org-babel-lob-one-liner-regexp)
1206 (org-babel-lob-execute-maybe)
1207 (org-babel-execute-src-block arg)))))
1209 ;;;###autoload
1210 (defun org-babel-execute-subtree (&optional arg)
1211 "Execute source code blocks in a subtree.
1212 Call `org-babel-execute-src-block' on every source block in
1213 the current subtree."
1214 (interactive "P")
1215 (save-restriction
1216 (save-excursion
1217 (org-narrow-to-subtree)
1218 (org-babel-execute-buffer arg)
1219 (widen))))
1221 ;;;###autoload
1222 (defun org-babel-sha1-hash (&optional info)
1223 "Generate an sha1 hash based on the value of info."
1224 (interactive)
1225 (let ((print-level nil)
1226 (info (or info (org-babel-get-src-block-info))))
1227 (setf (nth 2 info)
1228 (sort (copy-sequence (nth 2 info))
1229 (lambda (a b) (string< (car a) (car b)))))
1230 (let* ((rm (lambda (lst)
1231 (dolist (p '("replace" "silent" "none"
1232 "append" "prepend"))
1233 (setq lst (remove p lst)))
1234 lst))
1235 (norm (lambda (arg)
1236 (let ((v (if (and (listp (cdr arg)) (null (cddr arg)))
1237 (copy-sequence (cdr arg))
1238 (cdr arg))))
1239 (when (and v (not (and (sequencep v)
1240 (not (consp v))
1241 (= (length v) 0))))
1242 (cond
1243 ((and (listp v) ; lists are sorted
1244 (member (car arg) '(:result-params)))
1245 (sort (funcall rm v) #'string<))
1246 ((and (stringp v) ; strings are sorted
1247 (member (car arg) '(:results :exports)))
1248 (mapconcat #'identity (sort (funcall rm (split-string v))
1249 #'string<) " "))
1250 (t v))))))
1251 ;; expanded body
1252 (lang (nth 0 info))
1253 (params (nth 2 info))
1254 (body (if (org-babel-noweb-p params :eval)
1255 (org-babel-expand-noweb-references info) (nth 1 info)))
1256 (expand-cmd (intern (concat "org-babel-expand-body:" lang)))
1257 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
1258 lang)))
1259 (expanded
1260 (if (fboundp expand-cmd) (funcall expand-cmd body params)
1261 (org-babel-expand-body:generic
1262 body params (and (fboundp assignments-cmd)
1263 (funcall assignments-cmd params))))))
1264 (let* ((it (format "%s-%s"
1265 (mapconcat
1266 #'identity
1267 (delq nil (mapcar (lambda (arg)
1268 (let ((normalized (funcall norm arg)))
1269 (when normalized
1270 (format "%S" normalized))))
1271 (nth 2 info))) ":")
1272 expanded))
1273 (hash (sha1 it)))
1274 (when (org-called-interactively-p 'interactive) (message hash))
1275 hash))))
1277 (defun org-babel-current-result-hash (&optional info)
1278 "Return the current in-buffer hash."
1279 (org-babel-where-is-src-block-result nil info)
1280 (org-no-properties (match-string 5)))
1282 (defun org-babel-set-current-result-hash (hash info)
1283 "Set the current in-buffer hash to HASH."
1284 (org-babel-where-is-src-block-result nil info)
1285 (save-excursion (goto-char (match-beginning 5))
1286 (mapc #'delete-overlay (overlays-at (point)))
1287 (forward-char org-babel-hash-show)
1288 (mapc #'delete-overlay (overlays-at (point)))
1289 (replace-match hash nil nil nil 5)
1290 (goto-char (point-at-bol))
1291 (org-babel-hide-hash)))
1293 (defun org-babel-hide-hash ()
1294 "Hide the hash in the current results line.
1295 Only the initial `org-babel-hash-show' characters of the hash
1296 will remain visible."
1297 (add-to-invisibility-spec '(org-babel-hide-hash . t))
1298 (save-excursion
1299 (when (and (re-search-forward org-babel-result-regexp nil t)
1300 (match-string 5))
1301 (let* ((start (match-beginning 5))
1302 (hide-start (+ org-babel-hash-show start))
1303 (end (match-end 5))
1304 (hash (match-string 5))
1305 ov1 ov2)
1306 (setq ov1 (make-overlay start hide-start))
1307 (setq ov2 (make-overlay hide-start end))
1308 (overlay-put ov2 'invisible 'org-babel-hide-hash)
1309 (overlay-put ov1 'babel-hash hash)))))
1311 (defun org-babel-hide-all-hashes ()
1312 "Hide the hash in the current buffer.
1313 Only the initial `org-babel-hash-show' characters of each hash
1314 will remain visible. This function should be called as part of
1315 the `org-mode-hook'."
1316 (save-excursion
1317 (while (and (not org-babel-hash-show-time)
1318 (re-search-forward org-babel-result-regexp nil t))
1319 (goto-char (match-beginning 0))
1320 (org-babel-hide-hash)
1321 (goto-char (match-end 0)))))
1322 (add-hook 'org-mode-hook 'org-babel-hide-all-hashes)
1324 (defun org-babel-hash-at-point (&optional point)
1325 "Return the value of the hash at POINT.
1326 \\<org-mode-map>\
1327 The hash is also added as the last element of the kill ring.
1328 This can be called with \\[org-ctrl-c-ctrl-c]."
1329 (interactive)
1330 (let ((hash (car (delq nil (mapcar
1331 (lambda (ol) (overlay-get ol 'babel-hash))
1332 (overlays-at (or point (point))))))))
1333 (when hash (kill-new hash) (message hash))))
1334 (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-hash-at-point)
1336 (defun org-babel-result-hide-spec ()
1337 "Hide portions of results lines.
1338 Add `org-babel-hide-result' as an invisibility spec for hiding
1339 portions of results lines."
1340 (add-to-invisibility-spec '(org-babel-hide-result . t)))
1341 (add-hook 'org-mode-hook 'org-babel-result-hide-spec)
1343 (defvar org-babel-hide-result-overlays nil
1344 "Overlays hiding results.")
1346 (defun org-babel-result-hide-all ()
1347 "Fold all results in the current buffer."
1348 (interactive)
1349 (org-babel-show-result-all)
1350 (save-excursion
1351 (while (re-search-forward org-babel-result-regexp nil t)
1352 (save-excursion (goto-char (match-beginning 0))
1353 (org-babel-hide-result-toggle-maybe)))))
1355 (defun org-babel-show-result-all ()
1356 "Unfold all results in the current buffer."
1357 (mapc 'delete-overlay org-babel-hide-result-overlays)
1358 (setq org-babel-hide-result-overlays nil))
1360 ;;;###autoload
1361 (defun org-babel-hide-result-toggle-maybe ()
1362 "Toggle visibility of result at point."
1363 (interactive)
1364 (let ((case-fold-search t))
1365 (if (save-excursion
1366 (beginning-of-line 1)
1367 (looking-at org-babel-result-regexp))
1368 (progn (org-babel-hide-result-toggle)
1369 t) ;; to signal that we took action
1370 nil))) ;; to signal that we did not
1372 (defun org-babel-hide-result-toggle (&optional force)
1373 "Toggle the visibility of the current result."
1374 (interactive)
1375 (save-excursion
1376 (beginning-of-line)
1377 (if (re-search-forward org-babel-result-regexp nil t)
1378 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
1379 (end (progn
1380 (while (looking-at org-babel-multi-line-header-regexp)
1381 (forward-line 1))
1382 (goto-char (- (org-babel-result-end) 1)) (point)))
1384 (if (memq t (mapcar (lambda (overlay)
1385 (eq (overlay-get overlay 'invisible)
1386 'org-babel-hide-result))
1387 (overlays-at start)))
1388 (if (or (not force) (eq force 'off))
1389 (mapc (lambda (ov)
1390 (when (member ov org-babel-hide-result-overlays)
1391 (setq org-babel-hide-result-overlays
1392 (delq ov org-babel-hide-result-overlays)))
1393 (when (eq (overlay-get ov 'invisible)
1394 'org-babel-hide-result)
1395 (delete-overlay ov)))
1396 (overlays-at start)))
1397 (setq ov (make-overlay start end))
1398 (overlay-put ov 'invisible 'org-babel-hide-result)
1399 ;; make the block accessible to isearch
1400 (overlay-put
1401 ov 'isearch-open-invisible
1402 (lambda (ov)
1403 (when (member ov org-babel-hide-result-overlays)
1404 (setq org-babel-hide-result-overlays
1405 (delq ov org-babel-hide-result-overlays)))
1406 (when (eq (overlay-get ov 'invisible)
1407 'org-babel-hide-result)
1408 (delete-overlay ov))))
1409 (push ov org-babel-hide-result-overlays)))
1410 (error "Not looking at a result line"))))
1412 ;; org-tab-after-check-for-cycling-hook
1413 (add-hook 'org-tab-first-hook 'org-babel-hide-result-toggle-maybe)
1414 ;; Remove overlays when changing major mode
1415 (add-hook 'org-mode-hook
1416 (lambda () (org-add-hook 'change-major-mode-hook
1417 'org-babel-show-result-all 'append 'local)))
1419 (defvar org-file-properties)
1420 (defun org-babel-params-from-properties (&optional lang)
1421 "Retrieve parameters specified as properties.
1422 Return a list of association lists of source block params
1423 specified in the properties of the current outline entry."
1424 (save-match-data
1425 (list
1426 ;; DEPRECATED header arguments specified as separate property at
1427 ;; point of definition.
1428 (org-babel-parse-multiple-vars
1429 (delq nil
1430 (mapcar
1431 (lambda (header)
1432 (let* ((arg (symbol-name (car header)))
1433 (val (org-entry-get (point) arg t)))
1434 (and val
1435 (cons (intern (concat ":" arg))
1436 (org-babel-read val)))))
1437 (org-babel-combine-header-arg-lists
1438 org-babel-common-header-args-w-values
1439 (let ((sym (intern (concat "org-babel-header-args:" lang))))
1440 (and (boundp sym) (symbol-value sym)))))))
1441 ;; header arguments specified with the header-args property at
1442 ;; point of call.
1443 (org-babel-parse-header-arguments
1444 (org-entry-get org-babel-current-src-block-location
1445 "header-args"
1446 'inherit))
1447 (and lang ; language-specific header arguments at point of call
1448 (org-babel-parse-header-arguments
1449 (org-entry-get org-babel-current-src-block-location
1450 (concat "header-args:" lang)
1451 'inherit))))))
1453 (defvar org-src-preserve-indentation) ;; declare defcustom from org-src
1454 (defun org-babel-parse-src-block-match ()
1455 "Parse the results from a match of the `org-babel-src-block-regexp'."
1456 (let* ((block-indentation (string-width (match-string 1)))
1457 (lang (org-match-string-no-properties 2))
1458 (lang-headers (intern (concat "org-babel-default-header-args:" lang)))
1459 (switches (match-string 3))
1460 (body (let* ((body (org-match-string-no-properties 5))
1461 (sub-length (- (length body) 1)))
1462 (if (and (> sub-length 0)
1463 (string= "\n" (substring body sub-length)))
1464 (substring body 0 sub-length)
1465 (or body ""))))
1466 (preserve-indentation (or org-src-preserve-indentation
1467 (save-match-data
1468 (string-match "-i\\>" switches)))))
1469 (list lang
1470 ;; get block body less properties, protective commas, and indentation
1471 (with-temp-buffer
1472 (save-match-data
1473 (insert (org-unescape-code-in-string body))
1474 (unless preserve-indentation (org-do-remove-indentation))
1475 (buffer-string)))
1476 (apply #'org-babel-merge-params
1477 org-babel-default-header-args
1478 (when (boundp lang-headers) (eval lang-headers))
1479 (append
1480 (org-babel-params-from-properties lang)
1481 (list (org-babel-parse-header-arguments
1482 (org-no-properties (or (match-string 4) ""))))))
1483 switches
1484 block-indentation)))
1486 (defun org-babel-parse-inline-src-block-match ()
1487 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
1488 (let* ((lang (org-no-properties (match-string 2)))
1489 (lang-headers (intern (concat "org-babel-default-header-args:" lang))))
1490 (list lang
1491 (org-unescape-code-in-string (org-no-properties (match-string 5)))
1492 (apply #'org-babel-merge-params
1493 org-babel-default-inline-header-args
1494 (if (boundp lang-headers) (eval lang-headers) nil)
1495 (append
1496 (org-babel-params-from-properties lang)
1497 (list (org-babel-parse-header-arguments
1498 (org-no-properties (or (match-string 4) ""))))))
1499 nil)))
1501 (defun org-babel-balanced-split (string alts)
1502 "Split STRING on instances of ALTS.
1503 ALTS is a cons of two character options where each option may be
1504 either the numeric code of a single character or a list of
1505 character alternatives. For example to split on balanced
1506 instances of \"[ \t]:\" set ALTS to ((32 9) . 58)."
1507 (let* ((matches (lambda (ch spec) (if (listp spec) (member ch spec) (equal spec ch))))
1508 (matched (lambda (ch last)
1509 (if (consp alts)
1510 (and (funcall matches ch (cdr alts))
1511 (funcall matches last (car alts)))
1512 (funcall matches ch alts))))
1513 (balance 0) (last 0)
1514 quote partial lst)
1515 (mapc (lambda (ch) ; split on [], (), "" balanced instances of [ \t]:
1516 (setq balance (+ balance
1517 (cond ((or (equal 91 ch) (equal 40 ch)) 1)
1518 ((or (equal 93 ch) (equal 41 ch)) -1)
1519 (t 0))))
1520 (when (and (equal 34 ch) (not (equal 92 last)))
1521 (setq quote (not quote)))
1522 (setq partial (cons ch partial))
1523 (when (and (= balance 0) (not quote) (funcall matched ch last))
1524 (setq lst (cons (apply #'string (nreverse
1525 (if (consp alts)
1526 (cddr partial)
1527 (cdr partial))))
1528 lst))
1529 (setq partial nil))
1530 (setq last ch))
1531 (string-to-list string))
1532 (nreverse (cons (apply #'string (nreverse partial)) lst))))
1534 (defun org-babel-join-splits-near-ch (ch list)
1535 "Join splits where \"=\" is on either end of the split."
1536 (let ((last= (lambda (str) (= ch (aref str (1- (length str))))))
1537 (first= (lambda (str) (= ch (aref str 0)))))
1538 (reverse
1539 (cl-reduce (lambda (acc el)
1540 (let ((head (car acc)))
1541 (if (and head (or (funcall last= head) (funcall first= el)))
1542 (cons (concat head el) (cdr acc))
1543 (cons el acc))))
1544 list :initial-value nil))))
1546 (defun org-babel-parse-header-arguments (arg-string)
1547 "Parse a string of header arguments returning an alist."
1548 (when (> (length arg-string) 0)
1549 (org-babel-parse-multiple-vars
1550 (delq nil
1551 (mapcar
1552 (lambda (arg)
1553 (if (string-match
1554 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1555 arg)
1556 (cons (intern (match-string 1 arg))
1557 (org-babel-read (org-babel-chomp (match-string 2 arg))))
1558 (cons (intern (org-babel-chomp arg)) nil)))
1559 (let ((raw (org-babel-balanced-split arg-string '((32 9) . 58))))
1560 (cons (car raw) (mapcar (lambda (r) (concat ":" r)) (cdr raw)))))))))
1562 (defun org-babel-parse-multiple-vars (header-arguments)
1563 "Expand multiple variable assignments behind a single :var keyword.
1565 This allows expression of multiple variables with one :var as
1566 shown below.
1568 #+PROPERTY: var foo=1, bar=2"
1569 (let (results)
1570 (mapc (lambda (pair)
1571 (if (eq (car pair) :var)
1572 (mapcar (lambda (v) (push (cons :var (org-babel-trim v)) results))
1573 (org-babel-join-splits-near-ch
1574 61 (org-babel-balanced-split (cdr pair) 32)))
1575 (push pair results)))
1576 header-arguments)
1577 (nreverse results)))
1579 (defun org-babel-process-params (params)
1580 "Expand variables in PARAMS and add summary parameters."
1581 (let* ((processed-vars (mapcar (lambda (el)
1582 (if (consp el)
1584 (org-babel-ref-parse el)))
1585 (org-babel--get-vars params)))
1586 (vars-and-names (if (and (assoc :colname-names params)
1587 (assoc :rowname-names params))
1588 (list processed-vars)
1589 (org-babel-disassemble-tables
1590 processed-vars
1591 (cdr (assoc :hlines params))
1592 (cdr (assoc :colnames params))
1593 (cdr (assoc :rownames params)))))
1594 (raw-result (or (cdr (assoc :results params)) ""))
1595 (result-params (append
1596 (split-string (if (stringp raw-result)
1597 raw-result
1598 (eval raw-result)))
1599 (cdr (assoc :result-params params)))))
1600 (append
1601 (mapcar (lambda (var) (cons :var var)) (car vars-and-names))
1602 (list
1603 (cons :colname-names (or (cdr (assoc :colname-names params))
1604 (cadr vars-and-names)))
1605 (cons :rowname-names (or (cdr (assoc :rowname-names params))
1606 (caddr vars-and-names)))
1607 (cons :result-params result-params)
1608 (cons :result-type (cond ((member "output" result-params) 'output)
1609 ((member "value" result-params) 'value)
1610 (t 'value))))
1611 (cl-remove-if
1612 (lambda (x) (memq (car x) '(:colname-names :rowname-names :result-params
1613 :result-type :var)))
1614 params))))
1616 ;; row and column names
1617 (defun org-babel-del-hlines (table)
1618 "Remove all `hline's from TABLE."
1619 (remq 'hline table))
1621 (defun org-babel-get-colnames (table)
1622 "Return the column names of TABLE.
1623 Return a cons cell, the `car' of which contains the TABLE less
1624 colnames, and the `cdr' of which contains a list of the column
1625 names."
1626 (if (equal 'hline (nth 1 table))
1627 (cons (cddr table) (car table))
1628 (cons (cdr table) (car table))))
1630 (defun org-babel-get-rownames (table)
1631 "Return the row names of TABLE.
1632 Return a cons cell, the `car' of which contains the TABLE less
1633 rownames, and the `cdr' of which contains a list of the rownames.
1634 Note: this function removes any hlines in TABLE."
1635 (let* ((table (org-babel-del-hlines table))
1636 (rownames (funcall (lambda ()
1637 (let ((tp table))
1638 (mapcar
1639 (lambda (_row)
1640 (prog1
1641 (pop (car tp))
1642 (setq tp (cdr tp))))
1643 table))))))
1644 (cons table rownames)))
1646 (defun org-babel-put-colnames (table colnames)
1647 "Add COLNAMES to TABLE if they exist."
1648 (if colnames (apply 'list colnames 'hline table) table))
1650 (defun org-babel-put-rownames (table rownames)
1651 "Add ROWNAMES to TABLE if they exist."
1652 (if rownames
1653 (mapcar (lambda (row)
1654 (if (listp row)
1655 (cons (or (pop rownames) "") row)
1656 row)) table)
1657 table))
1659 (defun org-babel-pick-name (names selector)
1660 "Select one out of an alist of row or column names.
1661 SELECTOR can be either a list of names in which case those names
1662 will be returned directly, or an index into the list NAMES in
1663 which case the indexed names will be return."
1664 (if (listp selector)
1665 selector
1666 (when names
1667 (if (and selector (symbolp selector) (not (equal t selector)))
1668 (cdr (assoc selector names))
1669 (if (integerp selector)
1670 (nth (- selector 1) names)
1671 (cdr (car (last names))))))))
1673 (defun org-babel-disassemble-tables (vars hlines colnames rownames)
1674 "Parse tables for further processing.
1675 Process the variables in VARS according to the HLINES,
1676 ROWNAMES and COLNAMES header arguments. Return a list consisting
1677 of the vars, cnames and rnames."
1678 (let (cnames rnames)
1679 (list
1680 (mapcar
1681 (lambda (var)
1682 (when (listp (cdr var))
1683 (when (and (not (equal colnames "no"))
1684 (or colnames (and (equal (nth 1 (cdr var)) 'hline)
1685 (not (member 'hline (cddr (cdr var)))))))
1686 (let ((both (org-babel-get-colnames (cdr var))))
1687 (setq cnames (cons (cons (car var) (cdr both))
1688 cnames))
1689 (setq var (cons (car var) (car both)))))
1690 (when (and rownames (not (equal rownames "no")))
1691 (let ((both (org-babel-get-rownames (cdr var))))
1692 (setq rnames (cons (cons (car var) (cdr both))
1693 rnames))
1694 (setq var (cons (car var) (car both)))))
1695 (when (and hlines (not (equal hlines "yes")))
1696 (setq var (cons (car var) (org-babel-del-hlines (cdr var))))))
1697 var)
1698 vars)
1699 (reverse cnames) (reverse rnames))))
1701 (defun org-babel-reassemble-table (table colnames rownames)
1702 "Add column and row names to a table.
1703 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1704 to the table for reinsertion to org-mode."
1705 (if (listp table)
1706 (let ((table (if (and rownames (= (length table) (length rownames)))
1707 (org-babel-put-rownames table rownames) table)))
1708 (if (and colnames (listp (car table)) (= (length (car table))
1709 (length colnames)))
1710 (org-babel-put-colnames table colnames) table))
1711 table))
1713 (defun org-babel-where-is-src-block-head (&optional src-block)
1714 "Find where the current source block begins.
1716 If optional argument SRC-BLOCK is `src-block' type element, find
1717 its current beginning instead.
1719 Return the point at the beginning of the current source block.
1720 Specifically at the beginning of the #+BEGIN_SRC line. Also set
1721 match-data relatively to `org-babel-src-block-regexp', which see.
1722 If the point is not on a source block then return nil."
1723 (let ((element (or src-block (org-element-at-point))))
1724 (when (eq (org-element-type element) 'src-block)
1725 (let ((end (org-element-property :end element)))
1726 (org-with-wide-buffer
1727 ;; Ensure point is not on a blank line after the block.
1728 (beginning-of-line)
1729 (skip-chars-forward " \r\t\n" end)
1730 (when (< (point) end)
1731 (prog1 (goto-char (org-element-property :post-affiliated element))
1732 (looking-at org-babel-src-block-regexp))))))))
1734 ;;;###autoload
1735 (defun org-babel-goto-src-block-head ()
1736 "Go to the beginning of the current code block."
1737 (interactive)
1738 (let ((head (org-babel-where-is-src-block-head)))
1739 (if head (goto-char head) (error "Not currently in a code block"))))
1741 ;;;###autoload
1742 (defun org-babel-goto-named-src-block (name)
1743 "Go to a named source-code block."
1744 (interactive
1745 (let ((completion-ignore-case t)
1746 (case-fold-search t)
1747 (under-point (thing-at-point 'line)))
1748 (list (completing-read
1749 "source-block name: " (org-babel-src-block-names) nil t
1750 (cond
1751 ;; noweb
1752 ((string-match (org-babel-noweb-wrap) under-point)
1753 (let ((block-name (match-string 1 under-point)))
1754 (string-match "[^(]*" block-name)
1755 (match-string 0 block-name)))
1756 ;; #+call:
1757 ((string-match org-babel-lob-one-liner-regexp under-point)
1758 (let ((source-info (car (org-babel-lob-get-info))))
1759 (if (string-match "^\\([^\\[]+?\\)\\(\\[.*\\]\\)?(" source-info)
1760 (let ((source-name (match-string 1 source-info)))
1761 source-name))))
1762 ;; #+results:
1763 ((string-match (concat "#\\+" org-babel-results-keyword
1764 "\\:\s+\\([^\\(]*\\)") under-point)
1765 (match-string 1 under-point))
1766 ;; symbol-at-point
1767 ((and (thing-at-point 'symbol))
1768 (org-babel-find-named-block (thing-at-point 'symbol))
1769 (thing-at-point 'symbol))
1770 (""))))))
1771 (let ((point (org-babel-find-named-block name)))
1772 (if point
1773 ;; taken from `org-open-at-point'
1774 (progn (org-mark-ring-push) (goto-char point) (org-show-context))
1775 (message "source-code block `%s' not found in this buffer" name))))
1777 (defun org-babel-find-named-block (name)
1778 "Find a named source-code block.
1779 Return the location of the source block identified by source
1780 NAME, or nil if no such block exists. Set match data according
1781 to `org-babel-named-src-block-regexp'."
1782 (save-excursion
1783 (goto-char (point-min))
1784 (ignore-errors
1785 (org-next-block 1 nil (org-babel-named-src-block-regexp-for-name name)))))
1787 (defun org-babel-src-block-names (&optional file)
1788 "Returns the names of source blocks in FILE or the current buffer."
1789 (when file (find-file file))
1790 (save-excursion
1791 (goto-char (point-min))
1792 (let ((re (org-babel-named-src-block-regexp-for-name))
1793 names)
1794 (while (ignore-errors (org-next-block 1 nil re))
1795 (push (org-match-string-no-properties 9) names))
1796 names)))
1798 ;;;###autoload
1799 (defun org-babel-goto-named-result (name)
1800 "Go to a named result."
1801 (interactive
1802 (let ((completion-ignore-case t))
1803 (list (completing-read "Source-block name: "
1804 (org-babel-result-names) nil t))))
1805 (let ((point (org-babel-find-named-result name)))
1806 (if point
1807 ;; taken from `org-open-at-point'
1808 (progn (goto-char point) (org-show-context))
1809 (message "result `%s' not found in this buffer" name))))
1811 (defun org-babel-find-named-result (name &optional point)
1812 "Find a named result.
1813 Return the location of the result named NAME in the current
1814 buffer or nil if no such result exists."
1815 (save-excursion
1816 (let ((case-fold-search t))
1817 (goto-char (or point (point-min)))
1818 (catch 'is-a-code-block
1819 (when (re-search-forward
1820 (concat org-babel-result-regexp
1821 "[ \t]" (regexp-quote name) "[ \t]*[\n\f\v\r]")
1822 nil t)
1823 (when (and (string= "name" (downcase (match-string 1)))
1824 (or (beginning-of-line 1)
1825 (looking-at org-babel-src-block-regexp)
1826 (looking-at org-babel-multi-line-header-regexp)
1827 (looking-at org-babel-lob-one-liner-regexp)))
1828 (throw 'is-a-code-block (org-babel-find-named-result name (point))))
1829 (beginning-of-line 0) (point))))))
1831 (defun org-babel-result-names (&optional file)
1832 "Returns the names of results in FILE or the current buffer."
1833 (save-excursion
1834 (when file (find-file file)) (goto-char (point-min))
1835 (let ((case-fold-search t) names)
1836 (while (re-search-forward org-babel-result-w-name-regexp nil t)
1837 (setq names (cons (match-string 4) names)))
1838 names)))
1840 ;;;###autoload
1841 (defun org-babel-next-src-block (&optional arg)
1842 "Jump to the next source block.
1843 With optional prefix argument ARG, jump forward ARG many source blocks."
1844 (interactive "p")
1845 (org-next-block arg nil org-babel-src-block-regexp))
1847 ;;;###autoload
1848 (defun org-babel-previous-src-block (&optional arg)
1849 "Jump to the previous source block.
1850 With optional prefix argument ARG, jump backward ARG many source blocks."
1851 (interactive "p")
1852 (org-previous-block arg org-babel-src-block-regexp))
1854 (defvar org-babel-load-languages)
1856 ;;;###autoload
1857 (defun org-babel-mark-block ()
1858 "Mark current src block."
1859 (interactive)
1860 (let ((head (org-babel-where-is-src-block-head)))
1861 (when head
1862 (save-excursion
1863 (goto-char head)
1864 (looking-at org-babel-src-block-regexp))
1865 (push-mark (match-end 5) nil t)
1866 (goto-char (match-beginning 5)))))
1868 (defun org-babel-demarcate-block (&optional arg)
1869 "Wrap or split the code in the region or on the point.
1870 When called from inside of a code block the current block is
1871 split. When called from outside of a code block a new code block
1872 is created. In both cases if the region is demarcated and if the
1873 region is not active then the point is demarcated."
1874 (interactive "P")
1875 (let* ((info (org-babel-get-src-block-info 'light))
1876 (start (org-babel-where-is-src-block-head))
1877 (block (and start (match-string 0)))
1878 (headers (and start (match-string 4)))
1879 (stars (concat (make-string (or (org-current-level) 1) ?*) " "))
1880 (lower-case-p (and block
1881 (let (case-fold-search)
1882 (org-string-match-p "#\\+begin_src" block)))))
1883 (if info
1884 (mapc
1885 (lambda (place)
1886 (save-excursion
1887 (goto-char place)
1888 (let ((lang (nth 0 info))
1889 (indent (make-string (nth 5 info) ? )))
1890 (when (string-match "^[[:space:]]*$"
1891 (buffer-substring (point-at-bol)
1892 (point-at-eol)))
1893 (delete-region (point-at-bol) (point-at-eol)))
1894 (insert (concat
1895 (if (looking-at "^") "" "\n")
1896 indent (funcall (if lower-case-p 'downcase 'upcase) "#+end_src\n")
1897 (if arg stars indent) "\n"
1898 indent (funcall (if lower-case-p 'downcase 'upcase) "#+begin_src ")
1899 lang
1900 (if (> (length headers) 1)
1901 (concat " " headers) headers)
1902 (if (looking-at "[\n\r]")
1904 (concat "\n" (make-string (current-column) ? )))))))
1905 (move-end-of-line 2))
1906 (sort (if (org-region-active-p) (list (mark) (point)) (list (point))) #'>))
1907 (let ((start (point))
1908 (lang (completing-read
1909 "Lang: "
1910 (mapcar #'symbol-name
1911 (delete-dups
1912 (append (mapcar #'car org-babel-load-languages)
1913 (mapcar (lambda (el) (intern (car el)))
1914 org-src-lang-modes))))))
1915 (body (delete-and-extract-region
1916 (if (org-region-active-p) (mark) (point)) (point))))
1917 (insert (concat (if (looking-at "^") "" "\n")
1918 (if arg (concat stars "\n") "")
1919 (funcall (if lower-case-p 'downcase 'upcase) "#+begin_src ")
1920 lang "\n"
1921 body
1922 (if (or (= (length body) 0)
1923 (string-match "[\r\n]$" body)) "" "\n")
1924 (funcall (if lower-case-p 'downcase 'upcase) "#+end_src\n")))
1925 (goto-char start) (move-end-of-line 1)))))
1927 (defvar org-babel-lob-one-liner-regexp)
1928 (defun org-babel-where-is-src-block-result (&optional insert info hash indent)
1929 "Find where the current source block results begin.
1930 Return the point at the beginning of the result of the current
1931 source block. Specifically at the beginning of the results line.
1932 If no result exists for this block then create a results line
1933 following the source block."
1934 (save-excursion
1935 (let* ((case-fold-search t)
1936 (on-lob-line (save-excursion
1937 (beginning-of-line 1)
1938 (looking-at org-babel-lob-one-liner-regexp)))
1939 (inlinep (when (org-babel-get-inline-src-block-matches)
1940 (match-end 0)))
1941 (name (nth 4 (or info (org-babel-get-src-block-info 'light))))
1942 (head (unless on-lob-line (org-babel-where-is-src-block-head)))
1943 found beg end)
1944 (when head (goto-char head))
1945 (org-with-wide-buffer
1946 (setq
1947 found ;; was there a result (before we potentially insert one)
1949 inlinep
1950 (and
1951 ;; named results:
1952 ;; - return t if it is found, else return nil
1953 ;; - if it does not need to be rebuilt, then don't set end
1954 ;; - if it does need to be rebuilt then do set end
1955 name (setq beg (org-babel-find-named-result name))
1956 (prog1 beg
1957 (when (and hash (not (string= hash (match-string 5))))
1958 (goto-char beg) (setq end beg) ;; beginning of result
1959 (forward-line 1)
1960 (delete-region end (org-babel-result-end)) nil)))
1961 (and
1962 ;; unnamed results:
1963 ;; - return t if it is found, else return nil
1964 ;; - if it is found, and the hash doesn't match, delete and set end
1965 (or on-lob-line (re-search-forward "^[ \t]*#\\+end_src" nil t))
1966 (progn (end-of-line 1)
1967 (if (eobp) (insert "\n") (forward-char 1))
1968 (setq end (point))
1969 (and
1970 (not name)
1971 (progn ;; unnamed results line already exists
1972 (catch 'non-comment
1973 (while (re-search-forward "[^ \f\t\n\r\v]" nil t)
1974 (beginning-of-line 1)
1975 (cond
1976 ((looking-at (concat org-babel-result-regexp "\n"))
1977 (throw 'non-comment t))
1978 ((and (looking-at "^[ \t]*#")
1979 (not (looking-at
1980 org-babel-lob-one-liner-regexp)))
1981 (end-of-line 1))
1982 (t (throw 'non-comment nil))))))
1983 (let ((this-hash (match-string 5)))
1984 (prog1 (point)
1985 ;; must remove and rebuild if hash!=old-hash
1986 (if (and hash (not (string= hash this-hash)))
1987 (progn
1988 (setq end (point-at-bol))
1989 (forward-line 1)
1990 (delete-region end (org-babel-result-end))
1991 (setq beg end))
1992 (setq end nil))))))))))
1993 (if (not (and insert end)) found
1994 (goto-char end)
1995 (unless beg
1996 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1997 (when (wholenump indent) (indent-to indent))
1998 (insert (concat
1999 "#+" org-babel-results-keyword
2000 (when hash
2001 (if org-babel-hash-show-time
2002 (concat
2003 "["(format-time-string "<%Y-%m-%d %H:%M:%S>")" "hash"]")
2004 (concat "["hash"]")))
2006 (when name (concat " " name)) "\n"))
2007 (unless beg (insert "\n") (backward-char))
2008 (beginning-of-line 0)
2009 (when hash (org-babel-hide-hash))
2010 (point)))))
2012 (defun org-babel-read-element (element)
2013 "Read ELEMENT into emacs-lisp.
2014 Return nil if ELEMENT cannot be read."
2015 (org-with-wide-buffer
2016 (goto-char (org-element-property :post-affiliated element))
2017 (pcase (org-element-type element)
2018 (`fixed-width
2019 (let ((v (org-babel-trim (org-element-property :value element))))
2020 (or (org-babel-number-p v) v)))
2021 (`table (org-babel-read-table))
2022 (`plain-list (org-babel-read-list))
2023 ((or `example-block `export-block)
2024 (org-remove-indentation (org-element-property :value element)))
2025 (`paragraph
2026 ;; Treat paragraphs containing a single link specially.
2027 (skip-chars-forward " \t")
2028 (if (and (looking-at org-bracket-link-regexp)
2029 (save-excursion
2030 (goto-char (match-end 0))
2031 (skip-chars-forward " \r\t\n")
2032 (<= (org-element-property :end element)
2033 (point))))
2034 (org-babel-read-link)
2035 (buffer-substring-no-properties
2036 (org-element-property :contents-begin element)
2037 (org-element-property :contents-end element))))
2038 ((or `center-block `quote-block `verse-block `special-block)
2039 (org-remove-indentation
2040 (buffer-substring-no-properties
2041 (org-element-property :contents-begin element)
2042 (org-element-property :contents-end element))))
2043 (_ nil))))
2045 (defvar org-block-regexp)
2046 (defun org-babel-read-result ()
2047 "Read the result at `point' into emacs-lisp."
2048 (let ((case-fold-search t) result-string)
2049 (cond
2050 ((org-at-table-p) (org-babel-read-table))
2051 ((org-at-item-p) (org-babel-read-list))
2052 ((looking-at org-bracket-link-regexp) (org-babel-read-link))
2053 ((looking-at org-block-regexp) (org-remove-indentation (match-string 4)))
2054 ((or (looking-at "^[ \t]*: ") (looking-at "^[ \t]*:$"))
2055 (setq result-string
2056 (org-babel-trim
2057 (mapconcat (lambda (line)
2058 (or (and (> (length line) 1)
2059 (string-match "^[ \t]*: ?\\(.+\\)" line)
2060 (match-string 1 line))
2061 ""))
2062 (split-string
2063 (buffer-substring
2064 (point) (org-babel-result-end)) "[\r\n]+")
2065 "\n")))
2066 (or (org-babel-number-p result-string) result-string))
2067 ((looking-at org-babel-result-regexp)
2068 (save-excursion (forward-line 1) (org-babel-read-result))))))
2070 (defun org-babel-read-table ()
2071 "Read the table at `point' into emacs-lisp."
2072 (mapcar (lambda (row)
2073 (if (and (symbolp row) (equal row 'hline)) row
2074 (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval)) row)))
2075 (org-table-to-lisp)))
2077 (defun org-babel-read-list ()
2078 "Read the list at `point' into emacs-lisp."
2079 (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval))
2080 (cdr (org-list-to-lisp))))
2082 (defvar org-link-types-re)
2083 (defun org-babel-read-link ()
2084 "Read the link at `point' into emacs-lisp.
2085 If the path of the link is a file path it is expanded using
2086 `expand-file-name'."
2087 (let* ((case-fold-search t)
2088 (raw (and (looking-at org-bracket-link-regexp)
2089 (org-no-properties (match-string 1))))
2090 (type (and (string-match org-link-types-re raw)
2091 (match-string 1 raw))))
2092 (cond
2093 ((not type) (expand-file-name raw))
2094 ((string= type "file")
2095 (and (string-match "file\\(.*\\):\\(.+\\)" raw)
2096 (expand-file-name (match-string 2 raw))))
2097 (t raw))))
2099 (defun org-babel-format-result (result &optional sep)
2100 "Format RESULT for writing to file."
2101 (let ((echo-res (lambda (r) (if (stringp r) r (format "%S" r)))))
2102 (if (listp result)
2103 ;; table result
2104 (orgtbl-to-generic
2105 result (list :sep (or sep "\t") :fmt echo-res))
2106 ;; scalar result
2107 (funcall echo-res result))))
2109 (defun org-babel-insert-result
2110 (result &optional result-params info hash indent lang)
2111 "Insert RESULT into the current buffer.
2113 By default RESULT is inserted after the end of the current source
2114 block. The RESULT of an inline source block usually will be
2115 wrapped inside a `results' macro and placed on the same line as
2116 the inline source block. The macro is stripped upon export.
2117 Multiline and non-scalar RESULTS from inline source blocks are
2118 not allowed. With optional argument RESULT-PARAMS controls
2119 insertion of results in the Org mode file. RESULT-PARAMS can
2120 take the following values:
2122 replace - (default option) insert results after the source block
2123 or inline source block replacing any previously
2124 inserted results.
2126 silent -- no results are inserted into the Org-mode buffer but
2127 the results are echoed to the minibuffer and are
2128 ingested by Emacs (a potentially time consuming
2129 process).
2131 file ---- the results are interpreted as a file path, and are
2132 inserted into the buffer using the Org-mode file syntax.
2134 list ---- the results are interpreted as an Org-mode list.
2136 raw ----- results are added directly to the Org-mode file. This
2137 is a good option if you code block will output org-mode
2138 formatted text.
2140 drawer -- results are added directly to the Org-mode file as with
2141 \"raw\", but are wrapped in a RESULTS drawer or results
2142 macro, allowing them to later be replaced or removed
2143 automatically.
2145 org ----- results are added inside of a \"src_org{}\" or \"#+BEGIN_SRC
2146 org\" block depending on whether the current source block is
2147 inline or not. They are not comma-escaped when inserted,
2148 but Org syntax here will be discarded when exporting the
2149 file.
2151 html ---- results are added inside of a #+BEGIN_EXPORT HTML block
2152 or html export snippet depending on whether the current
2153 source block is inline or not. This is a good option
2154 if your code block will output html formatted text.
2156 latex --- results are added inside of a #+BEGIN_EXPORT LATEX
2157 block or latex export snippet depending on whether the
2158 current source block is inline or not. This is a good
2159 option if your code block will output latex formatted
2160 text.
2162 code ---- the results are extracted in the syntax of the source
2163 code of the language being evaluated and are added
2164 inside of a source block with the source-code language
2165 set appropriately. Also, source block inlining is
2166 preserved in this case. Note this relies on the
2167 optional LANG argument.
2169 list ---- the results are rendered as a list. This option not
2170 allowed for inline src blocks.
2172 table --- the results are rendered as a table. This option not
2173 allowed for inline src blocks.
2175 INFO may provide the values of these header arguments (in the
2176 `header-arguments-alist' see the docstring for
2177 `org-babel-get-src-block-info'):
2179 :file --- the name of the file to which output should be written.
2181 :wrap --- the effect is similar to `latex' in RESULT-PARAMS but
2182 using the argument supplied to specify the export block
2183 or snippet type."
2185 (if (stringp result)
2186 (progn
2187 (setq result (org-no-properties result))
2188 (when (member "file" result-params)
2189 (setq result (org-babel-result-to-file
2190 result (when (assoc :file-desc (nth 2 info))
2191 (or (cdr (assoc :file-desc (nth 2 info)))
2192 result))))))
2193 (unless (listp result) (setq result (format "%S" result))))
2194 (if (and result-params (member "silent" result-params))
2195 (progn
2196 (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
2197 result)
2198 (save-excursion
2199 (let* ((inlinep
2200 (save-excursion
2201 (when (or (org-babel-get-inline-src-block-matches)
2202 (org-babel-get-lob-one-liner-matches))
2203 (goto-char (match-end 0))
2204 (org-babel-remove-inline-result)
2205 (insert " ")
2206 (point))))
2207 (existing-result
2208 (unless inlinep
2209 (org-babel-where-is-src-block-result t info hash indent)))
2210 (bad-inline-p
2211 (when inlinep
2213 (and (member "table" result-params) "`:results table'")
2214 (and (listp result) "list result")
2215 (and (org-string-match-p "\n." result) "multiline result")
2216 (and (member "list" result-params) "`:results list'"))))
2217 (results-switches
2218 (cdr (assoc :results_switches (nth 2 info))))
2219 (visible-beg (point-min-marker))
2220 (visible-end (point-max-marker))
2221 ;; When results exist outside of the current visible
2222 ;; region of the buffer, be sure to widen buffer to
2223 ;; update them.
2224 (outside-scope-p (and existing-result
2225 (or (> visible-beg existing-result)
2226 (<= visible-end existing-result))))
2227 beg end)
2228 (when (and (stringp result) ; ensure results end in a newline
2229 (not inlinep)
2230 (> (length result) 0)
2231 (not (or (string-equal (substring result -1) "\n")
2232 (string-equal (substring result -1) "\r"))))
2233 (setq result (concat result "\n")))
2234 (unwind-protect
2235 (progn
2236 (when outside-scope-p (widen))
2237 (if (not existing-result)
2238 (setq beg (or inlinep (point)))
2239 (goto-char existing-result)
2240 (save-excursion
2241 (re-search-forward "#" nil t)
2242 (setq indent (- (current-column) 1)))
2243 (forward-line 1)
2244 (setq beg (point))
2245 (cond
2246 ((member "replace" result-params)
2247 (delete-region (point) (org-babel-result-end)))
2248 ((member "append" result-params)
2249 (goto-char (org-babel-result-end)) (setq beg (point-marker)))
2250 ((member "prepend" result-params)))) ; already there
2251 (setq results-switches
2252 (if results-switches (concat " " results-switches) ""))
2253 (let ((wrap (lambda (start finish &optional no-escape no-newlines
2254 inline-start inline-finish)
2255 (when inlinep
2256 (setq start inline-start)
2257 (setq finish inline-finish)
2258 (setq no-newlines t))
2259 (goto-char end)
2260 (insert (concat finish (unless no-newlines "\n")))
2261 (goto-char beg)
2262 (insert (concat start (unless no-newlines "\n")))
2263 (unless no-escape
2264 (org-escape-code-in-region (min (point) end) end))
2265 (goto-char end)
2266 (unless no-newlines (goto-char (point-at-eol)))
2267 (setq end (point-marker))))
2268 (tabulablep
2269 (lambda (r)
2270 ;; Non-nil when result R can be turned into
2271 ;; a table.
2272 (and (listp r)
2273 (null (cdr (last r)))
2274 (cl-every
2275 (lambda (e) (or (atom e) (null (cdr (last e)))))
2276 result)))))
2277 ;; insert results based on type
2278 (cond
2279 ;; Do nothing for an empty result.
2280 ((null result))
2281 ;; Illegal inline result or params.
2282 (bad-inline-p
2283 (error "Inline error: %s cannot be used" bad-inline-p))
2284 ;; insert a list if preferred
2285 ((member "list" result-params)
2286 (insert
2287 (org-babel-trim
2288 (org-list-to-generic
2289 (cons 'unordered
2290 (mapcar
2291 (lambda (e)
2292 (list (if (stringp e) e (format "%S" e))))
2293 (if (listp result) result
2294 (split-string result "\n" t))))
2295 '(:splicep nil :istart "- " :iend "\n")))
2296 "\n"))
2297 ;; Try hard to print RESULT as a table. Give up if
2298 ;; it contains an improper list.
2299 ((funcall tabulablep result)
2300 (goto-char beg)
2301 (insert (concat (orgtbl-to-orgtbl
2302 (if (cl-every
2303 (lambda (e)
2304 (or (eq e 'hline) (listp e)))
2305 result)
2306 result
2307 (list result))
2308 nil)
2309 "\n"))
2310 (goto-char beg)
2311 (when (org-at-table-p) (org-table-align))
2312 (goto-char (org-table-end)))
2313 ;; Print verbatim a list that cannot be turned into
2314 ;; a table.
2315 ((listp result) (insert (format "%s\n" result)))
2316 ((member "file" result-params)
2317 (when inlinep
2318 (goto-char inlinep)
2319 (setq result (org-macro-escape-arguments result)))
2320 (insert result))
2321 ((and inlinep
2322 (not (member "raw" result-params)))
2323 (goto-char inlinep)
2324 (insert (org-macro-escape-arguments
2325 (org-babel-chomp result "\n"))))
2326 (t (goto-char beg) (insert result)))
2327 (setq end (point-marker))
2328 ;; possibly wrap result
2329 (cond
2330 (bad-inline-p) ; Do nothing.
2331 ((assoc :wrap (nth 2 info))
2332 (let ((name (or (cdr (assoc :wrap (nth 2 info))) "RESULTS")))
2333 (funcall wrap (concat "#+BEGIN_" name)
2334 (concat "#+END_" (car (org-split-string name)))
2335 nil nil (concat "{{{results(@@" name ":") "@@)}}}")))
2336 ((member "html" result-params)
2337 (funcall wrap "#+BEGIN_EXPORT html" "#+END_EXPORT" nil nil
2338 "{{{results(@@html:" "@@)}}}"))
2339 ((member "latex" result-params)
2340 (funcall wrap "#+BEGIN_EXPORT latex" "#+END_EXPORT" nil nil
2341 "{{{results(@@latex:" "@@)}}}"))
2342 ((member "org" result-params)
2343 (goto-char beg) (if (org-at-table-p) (org-cycle))
2344 (funcall wrap "#+BEGIN_SRC org" "#+END_SRC" nil nil
2345 "{{{results(src_org{" "})}}}"))
2346 ((member "code" result-params)
2347 (let ((lang (or lang "none")))
2348 (funcall wrap (format "#+BEGIN_SRC %s%s" lang results-switches)
2349 "#+END_SRC" nil nil
2350 (format "{{{results(src_%s[%s]{" lang results-switches)
2351 "})}}}")))
2352 ((member "raw" result-params)
2353 (goto-char beg) (if (org-at-table-p) (org-cycle)))
2354 ((or (member "drawer" result-params)
2355 ;; Stay backward compatible with <7.9.2
2356 (member "wrap" result-params))
2357 (goto-char beg) (if (org-at-table-p) (org-cycle))
2358 (funcall wrap ":RESULTS:" ":END:" 'no-escape nil
2359 "{{{results(" ")}}}"))
2360 ((and inlinep (member "file" result-params))
2361 (funcall wrap nil nil nil nil "{{{results(" ")}}}"))
2362 ((and (not (funcall tabulablep result))
2363 (not (member "file" result-params)))
2364 (let ((org-babel-inline-result-wrap
2365 ;; Hard code {{{results(...)}}} on top of customization.
2366 (format "{{{results(%s)}}}" org-babel-inline-result-wrap)))
2367 (org-babel-examplify-region beg end results-switches)
2368 (setq end (point))))))
2369 ;; possibly indent the results to match the #+results line
2370 (when (and (not inlinep) (numberp indent) indent (> indent 0)
2371 ;; in this case `table-align' does the work for us
2372 (not (and (listp result)
2373 (member "append" result-params))))
2374 (indent-rigidly beg end indent))
2375 (if (null result)
2376 (if (member "value" result-params)
2377 (message "Code block returned no value.")
2378 (message "Code block produced no output."))
2379 (message "Code block evaluation complete.")))
2380 (when outside-scope-p (narrow-to-region visible-beg visible-end))
2381 (set-marker visible-beg nil)
2382 (set-marker visible-end nil))))))
2384 (defun org-babel-remove-result (&optional info keep-keyword)
2385 "Remove the result of the current source block."
2386 (interactive)
2387 (let ((location (org-babel-where-is-src-block-result nil info)))
2388 (when location
2389 (save-excursion
2390 (goto-char location)
2391 (when (looking-at (concat org-babel-result-regexp ".*$"))
2392 (delete-region
2393 (if keep-keyword (1+ (match-end 0)) (1- (match-beginning 0)))
2394 (progn (forward-line 1) (org-babel-result-end))))))))
2396 (defun org-babel-remove-inline-result ()
2397 "Remove the result of the current inline-src-block or babel call.
2398 The result must be wrapped in a `results' macro to be removed.
2399 Leading whitespace is trimmed."
2400 (interactive)
2401 (let* ((el (org-element-context))
2402 (post-blank (org-element-property :post-blank el)))
2403 (when (memq (org-element-type el) '(inline-src-block inline-babel-call))
2404 (org-with-wide-buffer
2405 (goto-char (org-element-property :end el))
2406 (let ((el (org-element-context)))
2407 (when (and (eq (org-element-type el) 'macro)
2408 (string= (org-element-property :key el) "results"))
2409 (delete-region ; And leading whitespace.
2410 (- (org-element-property :begin el) post-blank)
2411 (- (org-element-property :end el)
2412 (org-element-property :post-blank el)))))))))
2414 (defun org-babel-remove-result-one-or-many (x)
2415 "Remove the result of the current source block.
2416 If called with a prefix argument, remove all result blocks
2417 in the buffer."
2418 (interactive "P")
2419 (if x
2420 (org-babel-map-src-blocks nil (org-babel-remove-result))
2421 (org-babel-remove-result)))
2423 (defun org-babel-result-end ()
2424 "Return the point at the end of the current set of results."
2425 (save-excursion
2426 (cond
2427 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
2428 ((org-at-item-p) (let* ((struct (org-list-struct))
2429 (prvs (org-list-prevs-alist struct)))
2430 (org-list-get-list-end (point-at-bol) struct prvs)))
2431 ((let ((case-fold-search t)) (looking-at "^\\([ \t]*\\):results:"))
2432 (progn (re-search-forward (concat "^" (match-string 1) ":END:"))
2433 (forward-char 1) (point)))
2435 (let ((case-fold-search t))
2436 (if (looking-at (concat "[ \t]*#\\+begin_\\([^ \t\n\r]+\\)"))
2437 (progn (re-search-forward (concat "[ \t]*#\\+end_" (match-string 1))
2438 nil t)
2439 (forward-char 1))
2440 (while (looking-at "[ \t]*\\(: \\|:$\\|\\[\\[\\)")
2441 (forward-line 1))))
2442 (point)))))
2444 (defun org-babel-result-to-file (result &optional description)
2445 "Convert RESULT into an `org-mode' link with optional DESCRIPTION.
2446 If the `default-directory' is different from the containing
2447 file's directory then expand relative links."
2448 (when (stringp result)
2449 (format "[[file:%s]%s]"
2450 (if (and default-directory
2451 buffer-file-name
2452 (not (string= (expand-file-name default-directory)
2453 (expand-file-name
2454 (file-name-directory buffer-file-name)))))
2455 (expand-file-name result default-directory)
2456 result)
2457 (if description (concat "[" description "]") ""))))
2459 (defvar org-babel-capitalize-example-region-markers nil
2460 "Make true to capitalize begin/end example markers inserted by code blocks.")
2462 (define-obsolete-function-alias
2463 'org-babel-examplize-region
2464 'org-babel-examplify-region "25.1")
2466 (defun org-babel-examplify-region (beg end &optional results-switches)
2467 "Comment out region using the inline `==' or `: ' org example quote."
2468 (interactive "*r")
2469 (let ((chars-between (lambda (b e)
2470 (not (string-match "^[\\s]*$"
2471 (buffer-substring b e)))))
2472 (maybe-cap (lambda (str) (if org-babel-capitalize-example-region-markers
2473 (upcase str) str)))
2474 (beg-bol (save-excursion (goto-char beg) (point-at-bol)))
2475 (end-bol (save-excursion (goto-char end) (point-at-bol)))
2476 (end-eol (save-excursion (goto-char end) (point-at-eol))))
2477 (if (and (not (= end end-bol))
2478 (or (funcall chars-between beg-bol beg)
2479 (funcall chars-between end end-eol)))
2480 (save-excursion
2481 (goto-char beg)
2482 (insert (format org-babel-inline-result-wrap
2483 (prog1 (buffer-substring beg end)
2484 (delete-region beg end)))))
2485 (let ((size (count-lines beg end)))
2486 (save-excursion
2487 (cond ((= size 0)) ; do nothing for an empty result
2488 ((< size org-babel-min-lines-for-block-output)
2489 (goto-char beg)
2490 (dotimes (n size)
2491 (beginning-of-line 1) (insert ": ") (forward-line 1)))
2493 (goto-char beg)
2494 (insert (if results-switches
2495 (format "%s%s\n"
2496 (funcall maybe-cap "#+begin_example")
2497 results-switches)
2498 (funcall maybe-cap "#+begin_example\n")))
2499 (if (markerp end) (goto-char end) (forward-char (- end beg)))
2500 (insert (funcall maybe-cap "#+end_example\n")))))))))
2502 (defun org-babel-update-block-body (new-body)
2503 "Update the body of the current code block to NEW-BODY."
2504 (let ((element (org-element-at-point)))
2505 (unless (eq (org-element-type element) 'src-block)
2506 (error "Not in a source block"))
2507 (goto-char (org-babel-where-is-src-block-head element))
2508 (let* ((ind (org-get-indentation))
2509 (body-start (line-beginning-position 2))
2510 (body (org-element-normalize-string
2511 (if (or org-src-preserve-indentation
2512 (org-element-property :preserve-indent element))
2513 new-body
2514 (with-temp-buffer
2515 (insert (org-remove-indentation new-body))
2516 (indent-rigidly
2517 (point-min)
2518 (point-max)
2519 (+ ind org-edit-src-content-indentation))
2520 (buffer-string))))))
2521 (delete-region body-start
2522 (org-with-wide-buffer
2523 (goto-char (org-element-property :end element))
2524 (skip-chars-backward " \t\n")
2525 (line-beginning-position)))
2526 (goto-char body-start)
2527 (insert body))))
2529 (defun org-babel-merge-params (&rest plists)
2530 "Combine all parameter association lists in PLISTS.
2531 Later elements of PLISTS override the values of previous elements.
2532 This takes into account some special considerations for certain
2533 parameters when merging lists."
2534 (let* ((results-exclusive-groups
2535 (mapcar (lambda (group) (mapcar #'symbol-name group))
2536 (cdr (assoc 'results org-babel-common-header-args-w-values))))
2537 (exports-exclusive-groups
2538 (mapcar (lambda (group) (mapcar #'symbol-name group))
2539 (cdr (assoc 'exports org-babel-common-header-args-w-values))))
2540 (variable-index 0)
2541 (e-merge (lambda (exclusive-groups &rest result-params)
2542 ;; maintain exclusivity of mutually exclusive parameters
2543 (let (output)
2544 (mapc (lambda (new-params)
2545 (mapc (lambda (new-param)
2546 (mapc (lambda (exclusive-group)
2547 (when (member new-param exclusive-group)
2548 (mapcar (lambda (excluded-param)
2549 (setq output
2550 (delete
2551 excluded-param
2552 output)))
2553 exclusive-group)))
2554 exclusive-groups)
2555 (setq output (org-uniquify
2556 (cons new-param output))))
2557 new-params))
2558 result-params)
2559 output)))
2560 params results exports tangle noweb cache vars shebang comments padline
2561 clearnames)
2563 (mapc
2564 (lambda (plist)
2565 (mapc
2566 (lambda (pair)
2567 (case (car pair)
2568 (:var
2569 (let ((name (if (listp (cdr pair))
2570 (cadr pair)
2571 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
2572 (cdr pair))
2573 (intern (match-string 1 (cdr pair)))))))
2574 (if name
2575 (setq vars
2576 (append
2577 (if (member name (mapcar #'car vars))
2578 (progn
2579 (push name clearnames)
2580 (delq nil
2581 (mapcar
2582 (lambda (p)
2583 (unless (equal (car p) name) p))
2584 vars)))
2585 vars)
2586 (list (cons name pair))))
2587 ;; if no name is given and we already have named variables
2588 ;; then assign to named variables in order
2589 (if (and vars (nth variable-index vars))
2590 (let ((name (car (nth variable-index vars))))
2591 (push name clearnames) ; clear out colnames
2592 ; and rownames
2593 ; for replace vars
2594 (prog1 (setf (cddr (nth variable-index vars))
2595 (concat (symbol-name name) "=" (cdr pair)))
2596 (incf variable-index)))
2597 (error "Variable \"%s\" must be assigned a default value"
2598 (cdr pair))))))
2599 (:results
2600 (setq results (funcall e-merge results-exclusive-groups
2601 results
2602 (split-string
2603 (let ((r (cdr pair)))
2604 (if (stringp r) r (eval r)))))))
2605 (:file
2606 (when (cdr pair)
2607 (setq results (funcall e-merge results-exclusive-groups
2608 results '("file")))
2609 (unless (or (member "both" exports)
2610 (member "none" exports)
2611 (member "code" exports))
2612 (setq exports (funcall e-merge exports-exclusive-groups
2613 exports '("results"))))
2614 (setq params (cons pair (assq-delete-all (car pair) params)))))
2615 (:file-ext
2616 (when (cdr pair)
2617 (setq results (funcall e-merge results-exclusive-groups
2618 results '("file")))
2619 (unless (or (member "both" exports)
2620 (member "none" exports)
2621 (member "code" exports))
2622 (setq exports (funcall e-merge exports-exclusive-groups
2623 exports '("results"))))
2624 (setq params (cons pair (assq-delete-all (car pair) params)))))
2625 (:exports
2626 (setq exports (funcall e-merge exports-exclusive-groups
2627 exports
2628 (split-string (or (cdr pair) "")))))
2629 (:tangle ;; take the latest -- always overwrite
2630 (setq tangle (or (list (cdr pair)) tangle)))
2631 (:noweb
2632 (setq noweb (funcall e-merge
2633 '(("yes" "no" "tangle" "no-export"
2634 "strip-export" "eval"))
2635 noweb
2636 (split-string (or (cdr pair) "")))))
2637 (:cache
2638 (setq cache (funcall e-merge '(("yes" "no")) cache
2639 (split-string (or (cdr pair) "")))))
2640 (:padline
2641 (setq padline (funcall e-merge '(("yes" "no")) padline
2642 (split-string (or (cdr pair) "")))))
2643 (:shebang ;; take the latest -- always overwrite
2644 (setq shebang (or (list (cdr pair)) shebang)))
2645 (:comments
2646 (setq comments (funcall e-merge '(("yes" "no")) comments
2647 (split-string (or (cdr pair) "")))))
2648 (t ;; replace: this covers e.g. :session
2649 (setq params (cons pair (assq-delete-all (car pair) params))))))
2650 plist))
2651 plists)
2652 (setq vars (reverse vars))
2653 (while vars (setq params (cons (cons :var (cddr (pop vars))) params)))
2654 ;; clear out col-names and row-names for replaced variables
2655 (mapc
2656 (lambda (name)
2657 (mapc
2658 (lambda (param)
2659 (when (assoc param params)
2660 (setf (cdr (assoc param params))
2661 (cl-remove-if (lambda (pair) (equal (car pair) name))
2662 (cdr (assoc param params))))
2663 (setf params (cl-remove-if (lambda (pair) (and (equal (car pair) param)
2664 (null (cdr pair))))
2665 params))))
2666 (list :colname-names :rowname-names)))
2667 clearnames)
2668 (mapc
2669 (lambda (hd)
2670 (let ((key (intern (concat ":" (symbol-name hd))))
2671 (val (eval hd)))
2672 (setf params (cons (cons key (mapconcat 'identity val " ")) params))))
2673 '(results exports tangle noweb padline cache shebang comments))
2674 params))
2676 (defvar org-babel-use-quick-and-dirty-noweb-expansion nil
2677 "Set to true to use regular expressions to expand noweb references.
2678 This results in much faster noweb reference expansion but does
2679 not properly allow code blocks to inherit the \":noweb-ref\"
2680 header argument from buffer or subtree wide properties.")
2682 (defun org-babel-noweb-p (params context)
2683 "Check if PARAMS require expansion in CONTEXT.
2684 CONTEXT may be one of :tangle, :export or :eval."
2685 (let* (intersect
2686 (intersect (lambda (as bs)
2687 (when as
2688 (if (member (car as) bs)
2689 (car as)
2690 (funcall intersect (cdr as) bs))))))
2691 (funcall intersect (case context
2692 (:tangle '("yes" "tangle" "no-export" "strip-export"))
2693 (:eval '("yes" "no-export" "strip-export" "eval"))
2694 (:export '("yes")))
2695 (split-string (or (cdr (assoc :noweb params)) "")))))
2697 (defun org-babel-expand-noweb-references (&optional info parent-buffer)
2698 "Expand Noweb references in the body of the current source code block.
2700 For example the following reference would be replaced with the
2701 body of the source-code block named `example-block'.
2703 <<example-block>>
2705 Note that any text preceding the <<foo>> construct on a line will
2706 be interposed between the lines of the replacement text. So for
2707 example if <<foo>> is placed behind a comment, then the entire
2708 replacement text will also be commented.
2710 This function must be called from inside of the buffer containing
2711 the source-code block which holds BODY.
2713 In addition the following syntax can be used to insert the
2714 results of evaluating the source-code block named `example-block'.
2716 <<example-block()>>
2718 Any optional arguments can be passed to example-block by placing
2719 the arguments inside the parenthesis following the convention
2720 defined by `org-babel-lob'. For example
2722 <<example-block(a=9)>>
2724 would set the value of argument \"a\" equal to \"9\". Note that
2725 these arguments are not evaluated in the current source-code
2726 block but are passed literally to the \"example-block\"."
2727 (let* ((parent-buffer (or parent-buffer (current-buffer)))
2728 (info (or info (org-babel-get-src-block-info 'light)))
2729 (lang (nth 0 info))
2730 (body (nth 1 info))
2731 (ob-nww-start org-babel-noweb-wrap-start)
2732 (ob-nww-end org-babel-noweb-wrap-end)
2733 (comment (string= "noweb" (cdr (assoc :comments (nth 2 info)))))
2734 (rx-prefix (concat "\\(" org-babel-src-name-regexp "\\|"
2735 ":noweb-ref[ \t]+" "\\)"))
2736 (new-body "")
2737 (nb-add (lambda (text) (setq new-body (concat new-body text))))
2738 (c-wrap (lambda (text)
2739 (with-temp-buffer
2740 (funcall (intern (concat lang "-mode")))
2741 (comment-region (point) (progn (insert text) (point)))
2742 (org-babel-trim (buffer-string)))))
2743 index source-name evaluate prefix)
2744 (with-temp-buffer
2745 (setq-local org-babel-noweb-wrap-start ob-nww-start)
2746 (setq-local org-babel-noweb-wrap-end ob-nww-end)
2747 (insert body) (goto-char (point-min))
2748 (setq index (point))
2749 (while (and (re-search-forward (org-babel-noweb-wrap) nil t))
2750 (save-match-data (setf source-name (match-string 1)))
2751 (save-match-data (setq evaluate (string-match "(.*)" source-name)))
2752 (save-match-data
2753 (setq prefix
2754 (buffer-substring (match-beginning 0)
2755 (save-excursion
2756 (beginning-of-line 1) (point)))))
2757 ;; add interval to new-body (removing noweb reference)
2758 (goto-char (match-beginning 0))
2759 (funcall nb-add (buffer-substring index (point)))
2760 (goto-char (match-end 0))
2761 (setq index (point))
2762 (funcall
2763 nb-add
2764 (with-current-buffer parent-buffer
2765 (save-restriction
2766 (widen)
2767 (mapconcat ;; Interpose PREFIX between every line.
2768 #'identity
2769 (split-string
2770 (if evaluate
2771 (let ((raw (org-babel-ref-resolve source-name)))
2772 (if (stringp raw) raw (format "%S" raw)))
2774 ;; Retrieve from the library of babel.
2775 (nth 2 (assoc (intern source-name)
2776 org-babel-library-of-babel))
2777 ;; Return the contents of headlines literally.
2778 (save-excursion
2779 (when (org-babel-ref-goto-headline-id source-name)
2780 (org-babel-ref-headline-body)))
2781 ;; Find the expansion of reference in this buffer.
2782 (let ((rx (concat rx-prefix source-name "[ \t\n]"))
2783 expansion)
2784 (save-excursion
2785 (goto-char (point-min))
2786 (if org-babel-use-quick-and-dirty-noweb-expansion
2787 (while (re-search-forward rx nil t)
2788 (let* ((i (org-babel-get-src-block-info 'light))
2789 (body (org-babel-expand-noweb-references i))
2790 (sep (or (cdr (assoc :noweb-sep (nth 2 i)))
2791 "\n"))
2792 (full (if comment
2793 (let ((cs (org-babel-tangle-comment-links i)))
2794 (concat (funcall c-wrap (car cs)) "\n"
2795 body "\n"
2796 (funcall c-wrap (cadr cs))))
2797 body)))
2798 (setq expansion (cons sep (cons full expansion)))))
2799 (org-babel-map-src-blocks nil
2800 (let ((i (org-babel-get-src-block-info 'light)))
2801 (when (equal (or (cdr (assoc :noweb-ref (nth 2 i)))
2802 (nth 4 i))
2803 source-name)
2804 (let* ((body (org-babel-expand-noweb-references i))
2805 (sep (or (cdr (assoc :noweb-sep (nth 2 i)))
2806 "\n"))
2807 (full (if comment
2808 (let ((cs (org-babel-tangle-comment-links i)))
2809 (concat (funcall c-wrap (car cs)) "\n"
2810 body "\n"
2811 (funcall c-wrap (cadr cs))))
2812 body)))
2813 (setq expansion
2814 (cons sep (cons full expansion)))))))))
2815 (and expansion
2816 (mapconcat #'identity (nreverse (cdr expansion)) "")))
2817 ;; Possibly raise an error if named block doesn't exist.
2818 (if (or org-babel-noweb-error-all-langs
2819 (member lang org-babel-noweb-error-langs))
2820 (error "%s" (concat
2821 (org-babel-noweb-wrap source-name)
2822 "could not be resolved (see "
2823 "`org-babel-noweb-error-langs')"))
2824 "")))
2825 "[\n\r]") (concat "\n" prefix))))))
2826 (funcall nb-add (buffer-substring index (point-max))))
2827 new-body))
2829 (defun org-babel--script-escape-inner (str)
2830 (let (in-single in-double backslash out)
2831 (mapc
2832 (lambda (ch)
2833 (setq
2835 (if backslash
2836 (progn
2837 (setq backslash nil)
2838 (cond
2839 ((and in-single (eq ch ?'))
2840 ;; Escaped single quote inside single quoted string:
2841 ;; emit just a single quote, since we've changed the
2842 ;; outer quotes to double.
2843 (cons ch out))
2844 ((eq ch ?\")
2845 ;; Escaped double quote
2846 (if in-single
2847 ;; This should be interpreted as backslash+quote,
2848 ;; not an escape. Emit a three backslashes
2849 ;; followed by a quote (because one layer of
2850 ;; quoting will be stripped by `org-babel-read').
2851 (append (list ch ?\\ ?\\ ?\\) out)
2852 ;; Otherwise we are in a double-quoted string. Emit
2853 ;; a single escaped quote
2854 (append (list ch ?\\) out)))
2855 ((eq ch ?\\)
2856 ;; Escaped backslash: emit a single escaped backslash
2857 (append (list ?\\ ?\\) out))
2858 ;; Other: emit a quoted backslash followed by whatever
2859 ;; the character was (because one layer of quoting will
2860 ;; be stripped by `org-babel-read').
2861 (t (append (list ch ?\\ ?\\) out))))
2862 (case ch
2863 (?\[ (if (or in-double in-single)
2864 (cons ?\[ out)
2865 (cons ?\( out)))
2866 (?\] (if (or in-double in-single)
2867 (cons ?\] out)
2868 (cons ?\) out)))
2869 (?\{ (if (or in-double in-single)
2870 (cons ?\{ out)
2871 (cons ?\( out)))
2872 (?\} (if (or in-double in-single)
2873 (cons ?\} out)
2874 (cons ?\) out)))
2875 (?, (if (or in-double in-single)
2876 (cons ?, out) (cons ?\s out)))
2877 (?\' (if in-double
2878 (cons ?\' out)
2879 (setq in-single (not in-single)) (cons ?\" out)))
2880 (?\" (if in-single
2881 (append (list ?\" ?\\) out)
2882 (setq in-double (not in-double)) (cons ?\" out)))
2883 (?\\ (unless (or in-single in-double)
2884 (error "Can't handle backslash outside string in `org-babel-script-escape'"))
2885 (setq backslash t)
2886 out)
2887 (t (cons ch out))))))
2888 (string-to-list str))
2889 (when (or in-single in-double)
2890 (error "Unterminated string in `org-babel-script-escape'"))
2891 (apply #'string (reverse out))))
2893 (defun org-babel-script-escape (str &optional force)
2894 "Safely convert tables into elisp lists."
2895 (unless (stringp str)
2896 (error "`org-babel-script-escape' expects a string"))
2897 (let ((escaped
2898 (cond
2899 ((and (> (length str) 2)
2900 (or (and (string-equal "[" (substring str 0 1))
2901 (string-equal "]" (substring str -1)))
2902 (and (string-equal "{" (substring str 0 1))
2903 (string-equal "}" (substring str -1)))
2904 (and (string-equal "(" (substring str 0 1))
2905 (string-equal ")" (substring str -1)))))
2907 (concat "'" (org-babel--script-escape-inner str)))
2908 ((or force
2909 (and (> (length str) 2)
2910 (or (and (string-equal "'" (substring str 0 1))
2911 (string-equal "'" (substring str -1)))
2912 ;; We need to pass double-quoted strings
2913 ;; through the backslash-twiddling bits, even
2914 ;; though we don't need to change their
2915 ;; delimiters.
2916 (and (string-equal "\"" (substring str 0 1))
2917 (string-equal "\"" (substring str -1))))))
2918 (org-babel--script-escape-inner str))
2919 (t str))))
2920 (condition-case nil (org-babel-read escaped) (error escaped))))
2922 (defun org-babel-read (cell &optional inhibit-lisp-eval)
2923 "Convert the string value of CELL to a number if appropriate.
2924 Otherwise if CELL looks like lisp (meaning it starts with a
2925 \"(\", \"\\='\", \"\\=`\" or a \"[\") then read and evaluate it as
2926 lisp, otherwise return it unmodified as a string. Optional
2927 argument INHIBIT-LISP-EVAL inhibits lisp evaluation for
2928 situations in which is it not appropriate."
2929 (if (and (stringp cell) (not (equal cell "")))
2930 (or (org-babel-number-p cell)
2931 (if (and (not inhibit-lisp-eval)
2932 (or (member (substring cell 0 1) '("(" "'" "`" "["))
2933 (string= cell "*this*")))
2934 (eval (read cell))
2935 (if (string= (substring cell 0 1) "\"")
2936 (read cell)
2937 (progn (set-text-properties 0 (length cell) nil cell) cell))))
2938 cell))
2940 (defun org-babel-number-p (string)
2941 "If STRING represents a number return its value."
2942 (if (and (string-match "[0-9]+" string)
2943 (string-match "^-?[0-9]*\\.?[0-9]*$" string)
2944 (= (length (substring string (match-beginning 0)
2945 (match-end 0)))
2946 (length string)))
2947 (string-to-number string)))
2949 (defun org-babel-import-elisp-from-file (file-name &optional separator)
2950 "Read the results located at FILE-NAME into an elisp table.
2951 If the table is trivial, then return it as a scalar."
2952 (let (result)
2953 (save-window-excursion
2954 (with-temp-buffer
2955 (condition-case err
2956 (progn
2957 (org-table-import file-name separator)
2958 (delete-file file-name)
2959 (setq result (mapcar (lambda (row)
2960 (mapcar #'org-babel-string-read row))
2961 (org-table-to-lisp))))
2962 (error (message "Error reading results: %s" err) nil)))
2963 (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
2964 (if (consp (car result))
2965 (if (null (cdr (car result)))
2966 (caar result)
2967 result)
2968 (car result))
2969 result))))
2971 (defun org-babel-string-read (cell)
2972 "Strip nested \"s from around strings."
2973 (org-babel-read (or (and (stringp cell)
2974 (string-match "\\\"\\(.+\\)\\\"" cell)
2975 (match-string 1 cell))
2976 cell) t))
2978 (defun org-babel-chomp (string &optional regexp)
2979 "Strip a trailing space or carriage return from STRING.
2980 The default regexp used is \"[ \\f\\t\\n\\r\\v]\" but another one
2981 can be specified as the REGEXP argument."
2982 (let ((regexp (or regexp "[ \f\t\n\r\v]")))
2983 (while (and (> (length string) 0)
2984 (string-match regexp (substring string -1)))
2985 (setq string (substring string 0 -1)))
2986 string))
2988 (defun org-babel-trim (string &optional regexp)
2989 "Strip a leading and trailing space or carriage return from STRING.
2990 Like `org-babel-chomp', but run on both the first and last
2991 character of the string."
2992 (org-babel-chomp
2993 (org-reverse-string
2994 (org-babel-chomp (org-reverse-string string) regexp)) regexp))
2996 (defun org-babel-tramp-handle-call-process-region
2997 (start end program &optional delete buffer display &rest args)
2998 "Use Tramp to handle `call-process-region'.
2999 Fixes a bug in `tramp-handle-call-process-region'."
3000 (if (and (featurep 'tramp) (file-remote-p default-directory))
3001 (let ((tmpfile (tramp-compat-make-temp-file "")))
3002 (write-region start end tmpfile)
3003 (when delete (delete-region start end))
3004 (unwind-protect
3005 ;; (apply 'call-process program tmpfile buffer display args)
3006 ;; bug in tramp
3007 (apply 'process-file program tmpfile buffer display args)
3008 (delete-file tmpfile)))
3009 ;; org-babel-call-process-region-original is the original emacs
3010 ;; definition. It is in scope from the let binding in
3011 ;; org-babel-execute-src-block
3012 (apply org-babel-call-process-region-original
3013 start end program delete buffer display args)))
3015 (defun org-babel-local-file-name (file)
3016 "Return the local name component of FILE."
3017 (or (file-remote-p file 'localname) file))
3019 (defun org-babel-process-file-name (name &optional no-quote-p)
3020 "Prepare NAME to be used in an external process.
3021 If NAME specifies a remote location, the remote portion of the
3022 name is removed, since in that case the process will be executing
3023 remotely. The file name is then processed by `expand-file-name'.
3024 Unless second argument NO-QUOTE-P is non-nil, the file name is
3025 additionally processed by `shell-quote-argument'"
3026 (let ((f (org-babel-local-file-name (expand-file-name name))))
3027 (if no-quote-p f (shell-quote-argument f))))
3029 (defvar org-babel-temporary-directory)
3030 (unless (or noninteractive (boundp 'org-babel-temporary-directory))
3031 (defvar org-babel-temporary-directory
3032 (or (and (boundp 'org-babel-temporary-directory)
3033 (file-exists-p org-babel-temporary-directory)
3034 org-babel-temporary-directory)
3035 (make-temp-file "babel-" t))
3036 "Directory to hold temporary files created to execute code blocks.
3037 Used by `org-babel-temp-file'. This directory will be removed on
3038 Emacs shutdown."))
3040 (defcustom org-babel-remote-temporary-directory "/tmp/"
3041 "Directory to hold temporary files on remote hosts."
3042 :group 'org-babel
3043 :type 'string)
3045 (defmacro org-babel-result-cond (result-params scalar-form &rest table-forms)
3046 "Call the code to parse raw string results according to RESULT-PARAMS."
3047 (declare (indent 1)
3048 (debug (form form &rest form)))
3049 (org-with-gensyms (params)
3050 `(let ((,params ,result-params))
3051 (unless (member "none" ,params)
3052 (if (or (member "scalar" ,params)
3053 (member "verbatim" ,params)
3054 (member "html" ,params)
3055 (member "code" ,params)
3056 (member "pp" ,params)
3057 (member "file" ,params)
3058 (and (or (member "output" ,params)
3059 (member "raw" ,params)
3060 (member "org" ,params)
3061 (member "drawer" ,params))
3062 (not (member "table" ,params))))
3063 ,scalar-form
3064 ,@table-forms)))))
3065 (def-edebug-spec org-babel-result-cond (form form body))
3067 (defun org-babel-temp-file (prefix &optional suffix)
3068 "Create a temporary file in the `org-babel-temporary-directory'.
3069 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
3070 value of `temporary-file-directory' temporarily set to the value
3071 of `org-babel-temporary-directory'."
3072 (if (file-remote-p default-directory)
3073 (let ((prefix
3074 (concat (file-remote-p default-directory)
3075 (expand-file-name
3076 prefix org-babel-remote-temporary-directory))))
3077 (make-temp-file prefix nil suffix))
3078 (let ((temporary-file-directory
3079 (or (and (boundp 'org-babel-temporary-directory)
3080 (file-exists-p org-babel-temporary-directory)
3081 org-babel-temporary-directory)
3082 temporary-file-directory)))
3083 (make-temp-file prefix nil suffix))))
3085 (defun org-babel-remove-temporary-directory ()
3086 "Remove `org-babel-temporary-directory' on Emacs shutdown."
3087 (when (and (boundp 'org-babel-temporary-directory)
3088 (file-exists-p org-babel-temporary-directory))
3089 ;; taken from `delete-directory' in files.el
3090 (condition-case nil
3091 (progn
3092 (mapc (lambda (file)
3093 ;; This test is equivalent to
3094 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
3095 ;; but more efficient
3096 (if (eq t (car (file-attributes file)))
3097 (delete-directory file)
3098 (delete-file file)))
3099 ;; We do not want to delete "." and "..".
3100 (directory-files org-babel-temporary-directory 'full
3101 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
3102 (delete-directory org-babel-temporary-directory))
3103 (error
3104 (message "Failed to remove temporary Org-babel directory %s"
3105 (if (boundp 'org-babel-temporary-directory)
3106 org-babel-temporary-directory
3107 "[directory not defined]"))))))
3109 (add-hook 'kill-emacs-hook 'org-babel-remove-temporary-directory)
3111 (defun org-babel-one-header-arg-safe-p (pair safe-list)
3112 "Determine if the PAIR is a safe babel header arg according to SAFE-LIST.
3114 For the format of SAFE-LIST, see `org-babel-safe-header-args'."
3115 (and (consp pair)
3116 (keywordp (car pair))
3117 (stringp (cdr pair))
3119 (memq (car pair) safe-list)
3120 (let ((entry (assq (car pair) safe-list)))
3121 (and entry
3122 (consp entry)
3123 (cond ((functionp (cdr entry))
3124 (funcall (cdr entry) (cdr pair)))
3125 ((listp (cdr entry))
3126 (member (cdr pair) (cdr entry)))
3127 (t nil)))))))
3129 (defun org-babel-generate-file-param (src-name params)
3130 "Calculate the filename for source block results.
3132 The directory is calculated from the :output-dir property of the
3133 source block; if not specified, use the current directory.
3135 If the source block has a #+NAME and the :file parameter does not
3136 contain any period characters, then the :file parameter is
3137 treated as an extension, and the output file name is the
3138 concatenation of the directory (as calculated above), the block
3139 name, a period, and the parameter value as a file extension.
3140 Otherwise, the :file parameter is treated as a full file name,
3141 and the output file name is the directory (as calculated above)
3142 plus the parameter value."
3143 (let* ((file-cons (assq :file params))
3144 (file-ext-cons (assq :file-ext params))
3145 (file-ext (cdr-safe file-ext-cons))
3146 (dir (cdr-safe (assq :output-dir params)))
3147 fname)
3148 ;; create the output-dir if it does not exist
3149 (when dir
3150 (make-directory dir t))
3151 (if file-cons
3152 ;; :file given; add :output-dir if given
3153 (when dir
3154 (setcdr file-cons (concat (file-name-as-directory dir) (cdr file-cons))))
3155 ;; :file not given; compute from name and :file-ext if possible
3156 (when (and src-name file-ext)
3157 (if dir
3158 (setq fname (concat (file-name-as-directory (or dir ""))
3159 src-name "." file-ext))
3160 (setq fname (concat src-name "." file-ext)))
3161 (setq params (cons (cons :file fname) params))))
3162 params))
3164 ;;; Used by backends: R, Maxima, Octave.
3165 (defun org-babel-graphical-output-file (params)
3166 "File where a babel block should send graphical output, per PARAMS."
3167 (unless (assq :file params)
3168 (if (assq :file-ext params)
3169 (user-error ":file-ext given but no :file generated; did you forget to give a block a #+NAME?")
3170 (user-error "No :file header argument given; cannot create graphical result.")))
3171 (and (member "graphics" (cdr (assq :result-params params)))
3172 (cdr (assq :file params))))
3174 (provide 'ob-core)
3176 ;; Local variables:
3177 ;; generated-autoload-file: "org-loaddefs.el"
3178 ;; End:
3180 ;;; ob-core.el ends here