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