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