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