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