Merge branch 'origin-maint'
[org-mode.git] / lisp / ob.el
blobe420ef67c589b7f1365597f1e5147fccc726dbb4
1 ;;; ob.el --- working with code blocks in org-mode
3 ;; Copyright (C) 2009-2012 Free Software Foundation, Inc.
5 ;; Author: 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)
31 (defvar org-babel-call-process-region-original)
32 (defvar org-src-lang-modes)
33 (defvar org-babel-library-of-babel)
34 (declare-function show-all "outline" ())
35 (declare-function org-reduce "org" (CL-FUNC CL-SEQ &rest CL-KEYS))
36 (declare-function tramp-compat-make-temp-file "tramp-compat"
37 (filename &optional dir-flag))
38 (declare-function tramp-dissect-file-name "tramp" (name &optional nodefault))
39 (declare-function tramp-file-name-user "tramp" (vec))
40 (declare-function tramp-file-name-host "tramp" (vec))
41 (declare-function with-parsed-tramp-file-name "tramp" (filename var &rest body))
42 (declare-function org-icompleting-read "org" (&rest args))
43 (declare-function org-edit-src-code "org-src"
44 (&optional context code edit-buffer-name quietp))
45 (declare-function org-edit-src-exit "org-src" (&optional context))
46 (declare-function org-open-at-point "org" (&optional in-emacs reference-buffer))
47 (declare-function org-save-outline-visibility "org" (use-markers &rest body))
48 (declare-function org-outline-overlay-data "org" (&optional use-markers))
49 (declare-function org-set-outline-overlay-data "org" (data))
50 (declare-function org-narrow-to-subtree "org" ())
51 (declare-function org-entry-get "org"
52 (pom property &optional inherit literal-nil))
53 (declare-function org-make-options-regexp "org" (kwds &optional extra))
54 (declare-function org-do-remove-indentation "org" (&optional n))
55 (declare-function org-show-context "org" (&optional key))
56 (declare-function org-at-table-p "org" (&optional table-type))
57 (declare-function org-cycle "org" (&optional arg))
58 (declare-function org-uniquify "org" (list))
59 (declare-function org-current-level "org" ())
60 (declare-function org-table-import "org-table" (file arg))
61 (declare-function org-add-hook "org-compat"
62 (hook function &optional append local))
63 (declare-function org-table-align "org-table" ())
64 (declare-function org-table-end "org-table" (&optional table-type))
65 (declare-function orgtbl-to-generic "org-table" (table params))
66 (declare-function orgtbl-to-orgtbl "org-table" (table params))
67 (declare-function org-babel-tangle-comment-links "ob-tangle" (&optional info))
68 (declare-function org-babel-lob-get-info "ob-lob" nil)
69 (declare-function org-babel-ref-split-args "ob-ref" (arg-string))
70 (declare-function org-babel-ref-parse "ob-ref" (assignment))
71 (declare-function org-babel-ref-resolve "ob-ref" (ref))
72 (declare-function org-babel-ref-goto-headline-id "ob-ref" (id))
73 (declare-function org-babel-ref-headline-body "ob-ref" ())
74 (declare-function org-babel-lob-execute-maybe "ob-lob" ())
75 (declare-function org-number-sequence "org-compat" (from &optional to inc))
76 (declare-function org-at-item-p "org-list" ())
77 (declare-function org-list-parse-list "org-list" (&optional delete))
78 (declare-function org-list-to-generic "org-list" (LIST PARAMS))
79 (declare-function org-list-struct "org-list" ())
80 (declare-function org-list-prevs-alist "org-list" (struct))
81 (declare-function org-list-get-list-end "org-list" (item struct prevs))
83 (defgroup org-babel nil
84 "Code block evaluation and management in `org-mode' documents."
85 :tag "Babel"
86 :group 'org)
88 (defcustom org-confirm-babel-evaluate t
89 "Confirm before evaluation.
90 Require confirmation before interactively evaluating code
91 blocks in Org-mode buffers. The default value of this variable
92 is t, meaning confirmation is required for any code block
93 evaluation. This variable can be set to nil to inhibit any
94 future confirmation requests. This variable can also be set to a
95 function which takes two arguments the language of the code block
96 and the body of the code block. Such a function should then
97 return a non-nil value if the user should be prompted for
98 execution or nil if no prompt is required.
100 Warning: Disabling confirmation may result in accidental
101 evaluation of potentially harmful code. It may be advisable
102 remove code block execution from C-c C-c as further protection
103 against accidental code block evaluation. The
104 `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
105 remove code block execution from the C-c C-c keybinding."
106 :group 'org-babel
107 :type '(choice boolean function))
108 ;; don't allow this variable to be changed through file settings
109 (put 'org-confirm-babel-evaluate 'safe-local-variable (lambda (x) (eq x t)))
111 (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
112 "Remove code block evaluation from the C-c C-c key binding."
113 :group 'org-babel
114 :type 'boolean)
116 (defcustom org-babel-results-keyword "RESULTS"
117 "Keyword used to name results generated by code blocks.
118 Should be either RESULTS or NAME however any capitalization may
119 be used."
120 :group 'org-babel
121 :type 'string)
123 (defcustom org-babel-noweb-wrap-start "<<"
124 "String used to begin a noweb reference in a code block.
125 See also `org-babel-noweb-wrap-end'."
126 :group 'org-babel
127 :type 'string)
129 (defcustom org-babel-noweb-wrap-end ">>"
130 "String used to end a noweb reference in a code block.
131 See also `org-babel-noweb-wrap-start'."
132 :group 'org-babel
133 :type 'string)
135 (defun org-babel-noweb-wrap (regexp)
136 (concat org-babel-noweb-wrap-start regexp org-babel-noweb-wrap-end))
138 (defvar org-babel-src-name-regexp
139 "^[ \t]*#\\+name:[ \t]*"
140 "Regular expression used to match a source name line.")
142 (defvar org-babel-multi-line-header-regexp
143 "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
144 "Regular expression used to match multi-line header arguments.")
146 (defvar org-babel-src-name-w-name-regexp
147 (concat org-babel-src-name-regexp
148 "\\("
149 org-babel-multi-line-header-regexp
150 "\\)*"
151 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)")
152 "Regular expression matching source name lines with a name.")
154 (defvar org-babel-src-block-regexp
155 (concat
156 ;; (1) indentation (2) lang
157 "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
158 ;; (3) switches
159 "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
160 ;; (4) header arguments
161 "\\([^\n]*\\)\n"
162 ;; (5) body
163 "\\([^\000]*?\n\\)?[ \t]*#\\+end_src")
164 "Regexp used to identify code blocks.")
166 (defvar org-babel-inline-src-block-regexp
167 (concat
168 ;; (1) replacement target (2) lang
169 "\\(?:^\\|[^-[:alnum:]]\\)\\(src_\\([^ \f\t\n\r\v]+\\)"
170 ;; (3,4) (unused, headers)
171 "\\(\\|\\[\\(.*?\\)\\]\\)"
172 ;; (5) body
173 "{\\([^\f\n\r\v]+?\\)}\\)")
174 "Regexp used to identify inline src-blocks.")
176 (defun org-babel-get-header (params key &optional others)
177 "Select only header argument of type KEY from a list.
178 Optional argument OTHERS indicates that only the header that do
179 not match KEY should be returned."
180 (delq nil
181 (mapcar
182 (lambda (p) (when (funcall (if others #'not #'identity) (eq (car p) key)) p))
183 params)))
185 (defun org-babel-get-inline-src-block-matches()
186 "Set match data if within body of an inline source block.
187 Returns non-nil if match-data set"
188 (let ((src-at-0-p (save-excursion
189 (beginning-of-line 1)
190 (string= "src" (thing-at-point 'word))))
191 (first-line-p (= 1 (line-number-at-pos)))
192 (orig (point)))
193 (let ((search-for (cond ((and src-at-0-p first-line-p "src_"))
194 (first-line-p "[[:punct:] \t]src_")
195 (t "[[:punct:] \f\t\n\r\v]src_")))
196 (lower-limit (if first-line-p
198 (- (point-at-bol) 1))))
199 (save-excursion
200 (when (or (and src-at-0-p (bobp))
201 (and (re-search-forward "}" (point-at-eol) t)
202 (re-search-backward search-for lower-limit t)
203 (> orig (point))))
204 (when (looking-at org-babel-inline-src-block-regexp)
205 t ))))))
207 (defvar org-babel-inline-lob-one-liner-regexp)
208 (defun org-babel-get-lob-one-liner-matches()
209 "Set match data if on line of an lob one liner.
210 Returns non-nil if match-data set"
211 (save-excursion
212 (unless (= (point) (point-at-bol)) ;; move before inline block
213 (re-search-backward "[ \f\t\n\r\v]" nil t))
214 (if (looking-at org-babel-inline-lob-one-liner-regexp)
216 nil)))
218 (defun org-babel-get-src-block-info (&optional light)
219 "Get information on the current source block.
221 Optional argument LIGHT does not resolve remote variable
222 references; a process which could likely result in the execution
223 of other code blocks.
225 Returns a list
226 (language body header-arguments-alist switches name indent)."
227 (let ((case-fold-search t) head info name indent)
228 ;; full code block
229 (if (setq head (org-babel-where-is-src-block-head))
230 (save-excursion
231 (goto-char head)
232 (setq info (org-babel-parse-src-block-match))
233 (setq indent (car (last info)))
234 (setq info (butlast info))
235 (while (and (forward-line -1)
236 (looking-at org-babel-multi-line-header-regexp))
237 (setf (nth 2 info)
238 (org-babel-merge-params
239 (nth 2 info)
240 (org-babel-parse-header-arguments (match-string 1)))))
241 (when (looking-at org-babel-src-name-w-name-regexp)
242 (setq name (org-babel-clean-text-properties (match-string 3)))
243 (when (and (match-string 5) (> (length (match-string 5)) 0))
244 (setf (nth 2 info) ;; merge functional-syntax vars and header-args
245 (org-babel-merge-params
246 (mapcar
247 (lambda (ref) (cons :var ref))
248 (mapcar
249 (lambda (var) ;; check that each variable is initialized
250 (if (string-match ".+=.+" var)
252 (error
253 "variable \"%s\"%s must be assigned a default value"
254 var (if name (format " in block \"%s\"" name) ""))))
255 (org-babel-ref-split-args (match-string 5))))
256 (nth 2 info))))))
257 ;; inline source block
258 (when (org-babel-get-inline-src-block-matches)
259 (setq info (org-babel-parse-inline-src-block-match))))
260 ;; resolve variable references and add summary parameters
261 (when (and info (not light))
262 (setf (nth 2 info) (org-babel-process-params (nth 2 info))))
263 (when info (append info (list name indent)))))
265 (defvar org-current-export-file) ; dynamically bound
266 (defun org-babel-confirm-evaluate (info)
267 "Confirm evaluation of the code block INFO.
268 This behavior can be suppressed by setting the value of
269 `org-confirm-babel-evaluate' to nil, in which case all future
270 interactive code block evaluations will proceed without any
271 confirmation from the user.
273 Note disabling confirmation may result in accidental evaluation
274 of potentially harmful code."
275 (let* ((eval (or (cdr (assoc :eval (nth 2 info)))
276 (when (assoc :noeval (nth 2 info)) "no")))
277 (query (cond ((equal eval "query") t)
278 ((and org-current-export-file
279 (equal eval "query-export")) t)
280 ((functionp org-confirm-babel-evaluate)
281 (funcall org-confirm-babel-evaluate
282 (nth 0 info) (nth 1 info)))
283 (t org-confirm-babel-evaluate))))
284 (if (or (equal eval "never") (equal eval "no")
285 (and org-current-export-file (or (equal eval "no-export")
286 (equal eval "never-export")))
287 (and query
288 (not (yes-or-no-p
289 (format "Evaluate this%scode block%son your system? "
290 (if info (format " %s " (nth 0 info)) " ")
291 (if (nth 4 info)
292 (format " (%s) " (nth 4 info)) " "))))))
293 (prog1 nil (message "Evaluation %s"
294 (if (or (equal eval "never") (equal eval "no")
295 (equal eval "no-export")
296 (equal eval "never-export"))
297 "Disabled" "Aborted")))
298 t)))
300 ;;;###autoload
301 (defun org-babel-execute-safely-maybe ()
302 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
303 (org-babel-execute-maybe)))
305 (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-execute-safely-maybe)
307 ;;;###autoload
308 (defun org-babel-execute-maybe ()
309 (interactive)
310 (or (org-babel-execute-src-block-maybe)
311 (org-babel-lob-execute-maybe)))
313 (defun org-babel-execute-src-block-maybe ()
314 "Conditionally execute a source block.
315 Detect if this is context for a Babel src-block and if so
316 then run `org-babel-execute-src-block'."
317 (interactive)
318 (let ((info (org-babel-get-src-block-info)))
319 (if info
320 (progn (org-babel-eval-wipe-error-buffer)
321 (org-babel-execute-src-block current-prefix-arg info) t) nil)))
323 ;;;###autoload
324 (defun org-babel-view-src-block-info ()
325 "Display information on the current source block.
326 This includes header arguments, language and name, and is largely
327 a window into the `org-babel-get-src-block-info' function."
328 (interactive)
329 (let ((info (org-babel-get-src-block-info 'light)))
330 (flet ((full (it) (> (length it) 0))
331 (printf (fmt &rest args) (princ (apply #'format fmt args))))
332 (when info
333 (with-help-window (help-buffer)
334 (let ((name (nth 4 info))
335 (lang (nth 0 info))
336 (switches (nth 3 info))
337 (header-args (nth 2 info)))
338 (when name (printf "Name: %s\n" name))
339 (when lang (printf "Lang: %s\n" lang))
340 (when (full switches) (printf "Switches: %s\n" switches))
341 (printf "Header Arguments:\n")
342 (dolist (pair (sort header-args
343 (lambda (a b) (string< (symbol-name (car a))
344 (symbol-name (car b))))))
345 (when (full (cdr pair))
346 (printf "\t%S%s\t%s\n"
347 (car pair)
348 (if (> (length (format "%S" (car pair))) 7) "" "\t")
349 (cdr pair))))))))))
351 ;;;###autoload
352 (defun org-babel-expand-src-block-maybe ()
353 "Conditionally expand a source block.
354 Detect if this is context for a org-babel src-block and if so
355 then run `org-babel-expand-src-block'."
356 (interactive)
357 (let ((info (org-babel-get-src-block-info)))
358 (if info
359 (progn (org-babel-expand-src-block current-prefix-arg info) t)
360 nil)))
362 ;;;###autoload
363 (defun org-babel-load-in-session-maybe ()
364 "Conditionally load a source block in a session.
365 Detect if this is context for a org-babel src-block and if so
366 then run `org-babel-load-in-session'."
367 (interactive)
368 (let ((info (org-babel-get-src-block-info)))
369 (if info
370 (progn (org-babel-load-in-session current-prefix-arg info) t)
371 nil)))
373 (add-hook 'org-metaup-hook 'org-babel-load-in-session-maybe)
375 ;;;###autoload
376 (defun org-babel-pop-to-session-maybe ()
377 "Conditionally pop to a session.
378 Detect if this is context for a org-babel src-block and if so
379 then run `org-babel-pop-to-session'."
380 (interactive)
381 (let ((info (org-babel-get-src-block-info)))
382 (if info (progn (org-babel-pop-to-session current-prefix-arg info) t) nil)))
384 (add-hook 'org-metadown-hook 'org-babel-pop-to-session-maybe)
386 (defconst org-babel-common-header-args-w-values
387 '((cache . ((no yes)))
388 (cmdline . :any)
389 (colnames . ((nil no yes)))
390 (comments . ((no link yes org both noweb)))
391 (dir . :any)
392 (eval . ((never query)))
393 (exports . ((code results both none)))
394 (file . :any)
395 (hlines . ((no yes)))
396 (mkdirp . ((yes no)))
397 (no-expand)
398 (noeval)
399 (noweb . ((yes no tangle)))
400 (noweb-ref . :any)
401 (noweb-sep . :any)
402 (padline . ((yes no)))
403 (results . ((file list vector table scalar verbatim)
404 (raw org html latex code pp wrap)
405 (replace silent append prepend)
406 (output value)))
407 (rownames . ((no yes)))
408 (sep . :any)
409 (session . :any)
410 (shebang . :any)
411 (tangle . ((tangle yes no :any)))
412 (var . :any)
413 (wrap . :any)))
415 (defconst org-babel-header-arg-names
416 (mapcar #'car org-babel-common-header-args-w-values)
417 "Common header arguments used by org-babel.
418 Note that individual languages may define their own language
419 specific header arguments as well.")
421 (defvar org-babel-default-header-args
422 '((:session . "none") (:results . "replace") (:exports . "code")
423 (:cache . "no") (:noweb . "no") (:hlines . "no") (:tangle . "no")
424 (:padnewline . "yes"))
425 "Default arguments to use when evaluating a source block.")
427 (defvar org-babel-default-inline-header-args
428 '((:session . "none") (:results . "replace") (:exports . "results"))
429 "Default arguments to use when evaluating an inline source block.")
431 (defvar org-babel-data-names '("TBLNAME" "RESULTS" "NAME"))
433 (defvar org-babel-result-regexp
434 (concat "^[ \t]*#\\+"
435 (regexp-opt org-babel-data-names t)
436 "\\(\\[\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*")
437 "Regular expression used to match result lines.
438 If the results are associated with a hash key then the hash will
439 be saved in the second match data.")
441 (defvar org-babel-result-w-name-regexp
442 (concat org-babel-result-regexp
443 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
445 (defvar org-babel-min-lines-for-block-output 10
446 "The minimum number of lines for block output.
447 If number of lines of output is equal to or exceeds this
448 value, the output is placed in a #+begin_example...#+end_example
449 block. Otherwise the output is marked as literal by inserting
450 colons at the starts of the lines. This variable only takes
451 effect if the :results output option is in effect.")
453 (defvar org-babel-noweb-error-langs nil
454 "Languages for which Babel will raise literate programming errors.
455 List of languages for which errors should be raised when the
456 source code block satisfying a noweb reference in this language
457 can not be resolved.")
459 (defvar org-babel-hash-show 4
460 "Number of initial characters to show of a hidden results hash.")
462 (defvar org-babel-after-execute-hook nil
463 "Hook for functions to be called after `org-babel-execute-src-block'")
465 (defun org-babel-named-src-block-regexp-for-name (name)
466 "This generates a regexp used to match a src block named NAME."
467 (concat org-babel-src-name-regexp (regexp-quote name)
468 "\\([ \t]\\|$\\|(\\)" ".*[\r\n]"
469 (substring org-babel-src-block-regexp 1)))
471 (defun org-babel-named-data-regexp-for-name (name)
472 "This generates a regexp used to match data named NAME."
473 (concat org-babel-result-regexp (regexp-quote name) "\\([ \t]\\|$\\)"))
475 ;;; functions
476 (defvar call-process-region)
477 ;;;###autoload
479 (defun org-babel-execute-src-block (&optional arg info params)
480 "Execute the current source code block.
481 Insert the results of execution into the buffer. Source code
482 execution and the collection and formatting of results can be
483 controlled through a variety of header arguments.
485 With prefix argument ARG, force re-execution even if an existing
486 result cached in the buffer would otherwise have been returned.
488 Optionally supply a value for INFO in the form returned by
489 `org-babel-get-src-block-info'.
491 Optionally supply a value for PARAMS which will be merged with
492 the header arguments specified at the front of the source code
493 block."
494 (interactive)
495 (let ((info (or info (org-babel-get-src-block-info))))
496 (when (org-babel-confirm-evaluate
497 (let ((i info))
498 (setf (nth 2 i) (org-babel-merge-params (nth 2 info) params))
500 (let* ((lang (nth 0 info))
501 (params (if params
502 (org-babel-process-params
503 (org-babel-merge-params (nth 2 info) params))
504 (nth 2 info)))
505 (cache? (and (not arg) (cdr (assoc :cache params))
506 (string= "yes" (cdr (assoc :cache params)))))
507 (result-params (cdr (assoc :result-params params)))
508 (new-hash (when cache? (org-babel-sha1-hash info)))
509 (old-hash (when cache? (org-babel-current-result-hash)))
510 (body (setf (nth 1 info)
511 (if (org-babel-noweb-p params :eval)
512 (org-babel-expand-noweb-references info)
513 (nth 1 info))))
514 (dir (cdr (assoc :dir params)))
515 (default-directory
516 (or (and dir (file-name-as-directory dir)) default-directory))
517 (org-babel-call-process-region-original
518 (if (boundp 'org-babel-call-process-region-original)
519 org-babel-call-process-region-original
520 (symbol-function 'call-process-region)))
521 (indent (car (last info)))
522 result cmd)
523 (unwind-protect
524 (flet ((call-process-region (&rest args)
525 (apply 'org-babel-tramp-handle-call-process-region args)))
526 (flet ((lang-check (f)
527 (let ((f (intern (concat "org-babel-execute:" f))))
528 (when (fboundp f) f))))
529 (setq cmd
530 (or (lang-check lang)
531 (lang-check (symbol-name
532 (cdr (assoc lang org-src-lang-modes))))
533 (error "No org-babel-execute function for %s!" lang))))
534 (if (and (not arg) new-hash (equal new-hash old-hash))
535 (save-excursion ;; return cached result
536 (goto-char (org-babel-where-is-src-block-result nil info))
537 (end-of-line 1) (forward-char 1)
538 (setq result (org-babel-read-result))
539 (message (replace-regexp-in-string
540 "%" "%%" (format "%S" result))) result)
541 (message "executing %s code block%s..."
542 (capitalize lang)
543 (if (nth 4 info) (format " (%s)" (nth 4 info)) ""))
544 (setq result
545 ((lambda (result)
546 (if (and (eq (cdr (assoc :result-type params)) 'value)
547 (or (member "vector" result-params)
548 (member "table" result-params))
549 (not (listp result)))
550 (list (list result)) result))
551 (funcall cmd body params)))
552 ;; if non-empty result and :file then write to :file
553 (when (cdr (assoc :file params))
554 (when result
555 (with-temp-file (cdr (assoc :file params))
556 (insert
557 (org-babel-format-result
558 result (cdr (assoc :sep (nth 2 info)))))))
559 (setq result (cdr (assoc :file params))))
560 (org-babel-insert-result
561 result result-params info new-hash indent lang)
562 (run-hooks 'org-babel-after-execute-hook)
563 result))
564 (setq call-process-region 'org-babel-call-process-region-original))))))
566 (defun org-babel-expand-body:generic (body params &optional var-lines)
567 "Expand BODY with PARAMS.
568 Expand a block of code with org-babel according to its header
569 arguments. This generic implementation of body expansion is
570 called for languages which have not defined their own specific
571 org-babel-expand-body:lang function."
572 (mapconcat #'identity (append var-lines (list body)) "\n"))
574 ;;;###autoload
575 (defun org-babel-expand-src-block (&optional arg info params)
576 "Expand the current source code block.
577 Expand according to the source code block's header
578 arguments and pop open the results in a preview buffer."
579 (interactive)
580 (let* ((info (or info (org-babel-get-src-block-info)))
581 (lang (nth 0 info))
582 (params (setf (nth 2 info)
583 (sort (org-babel-merge-params (nth 2 info) params)
584 (lambda (el1 el2) (string< (symbol-name (car el1))
585 (symbol-name (car el2)))))))
586 (body (setf (nth 1 info)
587 (if (org-babel-noweb-p params :eval)
588 (org-babel-expand-noweb-references info) (nth 1 info))))
589 (expand-cmd (intern (concat "org-babel-expand-body:" lang)))
590 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
591 lang)))
592 (expanded
593 (if (fboundp expand-cmd) (funcall expand-cmd body params)
594 (org-babel-expand-body:generic
595 body params (and (fboundp assignments-cmd)
596 (funcall assignments-cmd params))))))
597 (org-edit-src-code
598 nil expanded (concat "*Org-Babel Preview " (buffer-name) "[ " lang " ]*"))))
600 (defun org-babel-edit-distance (s1 s2)
601 "Return the edit (levenshtein) distance between strings S1 S2."
602 (let* ((l1 (length s1))
603 (l2 (length s2))
604 (dist (map 'vector (lambda (_) (make-vector (1+ l2) nil))
605 (number-sequence 1 (1+ l1)))))
606 (flet ((in (i j) (aref (aref dist i) j))
607 (mmin (&rest lst) (apply #'min (remove nil lst))))
608 (setf (aref (aref dist 0) 0) 0)
609 (dolist (i (number-sequence 1 l1))
610 (dolist (j (number-sequence 1 l2))
611 (setf (aref (aref dist i) j)
612 (+ (if (equal (aref s1 (1- i)) (aref s2 (1- j))) 0 1)
613 (mmin (in (1- i) j) (in i (1- j)) (in (1- i) (1- j)))))))
614 (in l1 l2))))
616 ;;;###autoload
617 (defun org-babel-check-src-block ()
618 "Check for misspelled header arguments in the current code block."
619 (interactive)
620 ;; TODO: report malformed code block
621 ;; TODO: report incompatible combinations of header arguments
622 ;; TODO: report uninitialized variables
623 (let ((too-close 2) ;; <- control closeness to report potential match
624 (names (mapcar #'symbol-name org-babel-header-arg-names)))
625 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg)) 1))
626 (and (org-babel-where-is-src-block-head)
627 (org-babel-parse-header-arguments
628 (org-babel-clean-text-properties
629 (match-string 4))))))
630 (dolist (name names)
631 (when (and (not (string= header name))
632 (<= (org-babel-edit-distance header name) too-close)
633 (not (member header names)))
634 (error "supplied header \"%S\" is suspiciously close to \"%S\""
635 header name))))
636 (message "No suspicious header arguments found.")))
638 ;;;###autoload
639 (defun org-babel-insert-header-arg ()
640 "Insert a header argument selecting from lists of common args and values."
641 (interactive)
642 (let* ((lang (car (org-babel-get-src-block-info 'light)))
643 (lang-headers (intern (concat "org-babel-header-arg-names:" lang)))
644 (headers (append (if (boundp lang-headers)
645 (mapcar (lambda (h) (cons h :any))
646 (eval lang-headers))
647 nil)
648 org-babel-common-header-args-w-values))
649 (arg (org-icompleting-read
650 "Header Arg: "
651 (mapcar
652 (lambda (header-spec) (symbol-name (car header-spec)))
653 headers))))
654 (insert ":" arg)
655 (let ((vals (cdr (assoc (intern arg) headers))))
656 (when vals
657 (insert
659 (cond
660 ((eq vals :any)
661 (read-from-minibuffer "value: "))
662 ((listp vals)
663 (mapconcat
664 (lambda (group)
665 (let ((arg (org-icompleting-read
666 "value: "
667 (cons "default" (mapcar #'symbol-name group)))))
668 (if (and arg (not (string= "default" arg)))
669 (concat arg " ")
670 "")))
671 vals ""))))))))
673 ;;;###autoload
674 (defun org-babel-load-in-session (&optional arg info)
675 "Load the body of the current source-code block.
676 Evaluate the header arguments for the source block before
677 entering the session. After loading the body this pops open the
678 session."
679 (interactive)
680 (let* ((info (or info (org-babel-get-src-block-info)))
681 (lang (nth 0 info))
682 (params (nth 2 info))
683 (body (setf (nth 1 info)
684 (if (org-babel-noweb-p params :eval)
685 (org-babel-expand-noweb-references info)
686 (nth 1 info))))
687 (session (cdr (assoc :session params)))
688 (dir (cdr (assoc :dir params)))
689 (default-directory
690 (or (and dir (file-name-as-directory dir)) default-directory))
691 (cmd (intern (concat "org-babel-load-session:" lang))))
692 (unless (fboundp cmd)
693 (error "No org-babel-load-session function for %s!" lang))
694 (pop-to-buffer (funcall cmd session body params))
695 (end-of-line 1)))
697 ;;;###autoload
698 (defun org-babel-initiate-session (&optional arg info)
699 "Initiate session for current code block.
700 If called with a prefix argument then resolve any variable
701 references in the header arguments and assign these variables in
702 the session. Copy the body of the code block to the kill ring."
703 (interactive "P")
704 (let* ((info (or info (org-babel-get-src-block-info (not arg))))
705 (lang (nth 0 info))
706 (body (nth 1 info))
707 (params (nth 2 info))
708 (session (cdr (assoc :session params)))
709 (dir (cdr (assoc :dir params)))
710 (default-directory
711 (or (and dir (file-name-as-directory dir)) default-directory))
712 (init-cmd (intern (format "org-babel-%s-initiate-session" lang)))
713 (prep-cmd (intern (concat "org-babel-prep-session:" lang))))
714 (if (and (stringp session) (string= session "none"))
715 (error "This block is not using a session!"))
716 (unless (fboundp init-cmd)
717 (error "No org-babel-initiate-session function for %s!" lang))
718 (with-temp-buffer (insert (org-babel-trim body))
719 (copy-region-as-kill (point-min) (point-max)))
720 (when arg
721 (unless (fboundp prep-cmd)
722 (error "No org-babel-prep-session function for %s!" lang))
723 (funcall prep-cmd session params))
724 (funcall init-cmd session params)))
726 ;;;###autoload
727 (defun org-babel-switch-to-session (&optional arg info)
728 "Switch to the session of the current code block.
729 Uses `org-babel-initiate-session' to start the session. If called
730 with a prefix argument then this is passed on to
731 `org-babel-initiate-session'."
732 (interactive "P")
733 (pop-to-buffer (org-babel-initiate-session arg info))
734 (end-of-line 1))
736 (defalias 'org-babel-pop-to-session 'org-babel-switch-to-session)
738 ;;;###autoload
739 (defun org-babel-switch-to-session-with-code (&optional arg info)
740 "Switch to code buffer and display session."
741 (interactive "P")
742 (flet ((swap-windows
744 (let ((other-window-buffer (window-buffer (next-window))))
745 (set-window-buffer (next-window) (current-buffer))
746 (set-window-buffer (selected-window) other-window-buffer))
747 (other-window 1)))
748 (let ((info (org-babel-get-src-block-info))
749 (org-src-window-setup 'reorganize-frame))
750 (save-excursion
751 (org-babel-switch-to-session arg info))
752 (org-edit-src-code))
753 (swap-windows)))
755 (defmacro org-babel-do-in-edit-buffer (&rest body)
756 "Evaluate BODY in edit buffer if there is a code block at point.
757 Return t if a code block was found at point, nil otherwise."
758 `(let ((org-src-window-setup 'switch-invisibly))
759 (when (and (org-babel-where-is-src-block-head)
760 (org-edit-src-code nil nil nil))
761 (unwind-protect (progn ,@body)
762 (if (org-bound-and-true-p org-edit-src-from-org-mode)
763 (org-edit-src-exit)))
764 t)))
765 (def-edebug-spec org-babel-do-in-edit-buffer (body))
767 (defun org-babel-do-key-sequence-in-edit-buffer (key)
768 "Read key sequence and execute the command in edit buffer.
769 Enter a key sequence to be executed in the language major-mode
770 edit buffer. For example, TAB will alter the contents of the
771 Org-mode code block according to the effect of TAB in the
772 language major-mode buffer. For languages that support
773 interactive sessions, this can be used to send code from the Org
774 buffer to the session for evaluation using the native major-mode
775 evaluation mechanisms."
776 (interactive "kEnter key-sequence to execute in edit buffer: ")
777 (org-babel-do-in-edit-buffer
778 (call-interactively
779 (key-binding (or key (read-key-sequence nil))))))
781 (defvar org-bracket-link-regexp)
782 ;;;###autoload
783 (defun org-babel-open-src-block-result (&optional re-run)
784 "If `point' is on a src block then open the results of the
785 source code block, otherwise return nil. With optional prefix
786 argument RE-RUN the source-code block is evaluated even if
787 results already exist."
788 (interactive "P")
789 (let ((info (org-babel-get-src-block-info)))
790 (when info
791 (save-excursion
792 ;; go to the results, if there aren't any then run the block
793 (goto-char (or (and (not re-run) (org-babel-where-is-src-block-result))
794 (progn (org-babel-execute-src-block)
795 (org-babel-where-is-src-block-result))))
796 (end-of-line 1)
797 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
798 ;; open the results
799 (if (looking-at org-bracket-link-regexp)
800 ;; file results
801 (org-open-at-point)
802 (let ((r (org-babel-format-result
803 (org-babel-read-result) (cdr (assoc :sep (nth 2 info))))))
804 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
805 (delete-region (point-min) (point-max))
806 (insert r)))
807 t))))
809 ;;;###autoload
810 (defmacro org-babel-map-src-blocks (file &rest body)
811 "Evaluate BODY forms on each source-block in FILE.
812 If FILE is nil evaluate BODY forms on source blocks in current
813 buffer. During evaluation of BODY the following local variables
814 are set relative to the currently matched code block.
816 full-block ------- string holding the entirety of the code block
817 beg-block -------- point at the beginning of the code block
818 end-block -------- point at the end of the matched code block
819 lang ------------- string holding the language of the code block
820 beg-lang --------- point at the beginning of the lang
821 end-lang --------- point at the end of the lang
822 switches --------- string holding the switches
823 beg-switches ----- point at the beginning of the switches
824 end-switches ----- point at the end of the switches
825 header-args ------ string holding the header-args
826 beg-header-args -- point at the beginning of the header-args
827 end-header-args -- point at the end of the header-args
828 body ------------- string holding the body of the code block
829 beg-body --------- point at the beginning of the body
830 end-body --------- point at the end of the body"
831 (declare (indent 1))
832 (let ((tempvar (make-symbol "file")))
833 `(let* ((,tempvar ,file)
834 (visited-p (or (null ,tempvar)
835 (get-file-buffer (expand-file-name ,tempvar))))
836 (point (point)) to-be-removed)
837 (save-window-excursion
838 (when ,tempvar (find-file ,tempvar))
839 (setq to-be-removed (current-buffer))
840 (goto-char (point-min))
841 (while (re-search-forward org-babel-src-block-regexp nil t)
842 (goto-char (match-beginning 0))
843 (let ((full-block (match-string 0))
844 (beg-block (match-beginning 0))
845 (end-block (match-end 0))
846 (lang (match-string 2))
847 (beg-lang (match-beginning 2))
848 (end-lang (match-end 2))
849 (switches (match-string 3))
850 (beg-switches (match-beginning 3))
851 (end-switches (match-end 3))
852 (header-args (match-string 4))
853 (beg-header-args (match-beginning 4))
854 (end-header-args (match-end 4))
855 (body (match-string 5))
856 (beg-body (match-beginning 5))
857 (end-body (match-end 5)))
858 ,@body
859 (goto-char end-block))))
860 (unless visited-p (kill-buffer to-be-removed))
861 (goto-char point))))
862 (def-edebug-spec org-babel-map-src-blocks (form body))
864 ;;;###autoload
865 (defmacro org-babel-map-inline-src-blocks (file &rest body)
866 "Evaluate BODY forms on each inline source-block in FILE.
867 If FILE is nil evaluate BODY forms on source blocks in current
868 buffer."
869 (declare (indent 1))
870 (let ((tempvar (make-symbol "file")))
871 `(let* ((,tempvar ,file)
872 (visited-p (or (null ,tempvar)
873 (get-file-buffer (expand-file-name ,tempvar))))
874 (point (point)) to-be-removed)
875 (save-window-excursion
876 (when ,tempvar (find-file ,tempvar))
877 (setq to-be-removed (current-buffer))
878 (goto-char (point-min))
879 (while (re-search-forward org-babel-inline-src-block-regexp nil t)
880 (goto-char (match-beginning 1))
881 (save-match-data ,@body)
882 (goto-char (match-end 0))))
883 (unless visited-p (kill-buffer to-be-removed))
884 (goto-char point))))
885 (def-edebug-spec org-babel-map-inline-src-blocks (form body))
887 (defvar org-babel-lob-one-liner-regexp)
888 ;;;###autoload
889 (defmacro org-babel-map-call-lines (file &rest body)
890 "Evaluate BODY forms on each call line in FILE.
891 If FILE is nil evaluate BODY forms on source blocks in current
892 buffer."
893 (declare (indent 1))
894 (let ((tempvar (make-symbol "file")))
895 `(let* ((,tempvar ,file)
896 (visited-p (or (null ,tempvar)
897 (get-file-buffer (expand-file-name ,tempvar))))
898 (point (point)) to-be-removed)
899 (save-window-excursion
900 (when ,tempvar (find-file ,tempvar))
901 (setq to-be-removed (current-buffer))
902 (goto-char (point-min))
903 (while (re-search-forward org-babel-lob-one-liner-regexp nil t)
904 (goto-char (match-beginning 1))
905 (save-match-data ,@body)
906 (goto-char (match-end 0))))
907 (unless visited-p (kill-buffer to-be-removed))
908 (goto-char point))))
909 (def-edebug-spec org-babel-map-call-lines (form body))
911 ;;;###autoload
912 (defmacro org-babel-map-executables (file &rest body)
913 (declare (indent 1))
914 (let ((tempvar (make-symbol "file"))
915 (rx (make-symbol "rx")))
916 `(let* ((,tempvar ,file)
917 (,rx (concat "\\(" org-babel-src-block-regexp
918 "\\|" org-babel-inline-src-block-regexp
919 "\\|" org-babel-lob-one-liner-regexp "\\)"))
920 (visited-p (or (null ,tempvar)
921 (get-file-buffer (expand-file-name ,tempvar))))
922 (point (point)) to-be-removed)
923 (save-window-excursion
924 (when ,tempvar (find-file ,tempvar))
925 (setq to-be-removed (current-buffer))
926 (goto-char (point-min))
927 (while (re-search-forward ,rx nil t)
928 (goto-char (match-beginning 1))
929 (when (looking-at org-babel-inline-src-block-regexp)(forward-char 1))
930 (save-match-data ,@body)
931 (goto-char (match-end 0))))
932 (unless visited-p (kill-buffer to-be-removed))
933 (goto-char point))))
934 (def-edebug-spec org-babel-map-executables (form body))
936 ;;;###autoload
937 (defun org-babel-execute-buffer (&optional arg)
938 "Execute source code blocks in a buffer.
939 Call `org-babel-execute-src-block' on every source block in
940 the current buffer."
941 (interactive "P")
942 (org-babel-eval-wipe-error-buffer)
943 (org-save-outline-visibility t
944 (org-babel-map-executables nil
945 (if (looking-at org-babel-lob-one-liner-regexp)
946 (org-babel-lob-execute-maybe)
947 (org-babel-execute-src-block arg)))))
949 ;;;###autoload
950 (defun org-babel-execute-subtree (&optional arg)
951 "Execute source code blocks in a subtree.
952 Call `org-babel-execute-src-block' on every source block in
953 the current subtree."
954 (interactive "P")
955 (save-restriction
956 (save-excursion
957 (org-narrow-to-subtree)
958 (org-babel-execute-buffer arg)
959 (widen))))
961 ;;;###autoload
962 (defun org-babel-sha1-hash (&optional info)
963 "Generate an sha1 hash based on the value of info."
964 (interactive)
965 (let ((print-level nil)
966 (info (or info (org-babel-get-src-block-info))))
967 (setf (nth 2 info)
968 (sort (copy-sequence (nth 2 info))
969 (lambda (a b) (string< (car a) (car b)))))
970 (labels ((rm (lst)
971 (dolist (p '("replace" "silent" "append" "prepend"))
972 (setq lst (remove p lst)))
973 lst)
974 (norm (arg)
975 (let ((v (if (and (listp (cdr arg)) (null (cddr arg)))
976 (copy-sequence (cdr arg))
977 (cdr arg))))
978 (when (and v (not (and (sequencep v)
979 (not (consp v))
980 (= (length v) 0))))
981 (cond
982 ((and (listp v) ; lists are sorted
983 (member (car arg) '(:result-params)))
984 (sort (rm v) #'string<))
985 ((and (stringp v) ; strings are sorted
986 (member (car arg) '(:results :exports)))
987 (mapconcat #'identity (sort (rm (split-string v))
988 #'string<) " "))
989 (t v))))))
990 ((lambda (hash)
991 (when (org-called-interactively-p 'interactive) (message hash)) hash)
992 (let ((it (format "%s-%s"
993 (mapconcat
994 #'identity
995 (delq nil (mapcar (lambda (arg)
996 (let ((normalized (norm arg)))
997 (when normalized
998 (format "%S" normalized))))
999 (nth 2 info))) ":")
1000 (nth 1 info))))
1001 (sha1 it))))))
1003 (defun org-babel-current-result-hash ()
1004 "Return the in-buffer hash associated with INFO."
1005 (org-babel-where-is-src-block-result)
1006 (org-babel-clean-text-properties (match-string 3)))
1008 (defun org-babel-hide-hash ()
1009 "Hide the hash in the current results line.
1010 Only the initial `org-babel-hash-show' characters of the hash
1011 will remain visible."
1012 (add-to-invisibility-spec '(org-babel-hide-hash . t))
1013 (save-excursion
1014 (when (and (re-search-forward org-babel-result-regexp nil t)
1015 (match-string 3))
1016 (let* ((start (match-beginning 3))
1017 (hide-start (+ org-babel-hash-show start))
1018 (end (match-end 3))
1019 (hash (match-string 3))
1020 ov1 ov2)
1021 (setq ov1 (make-overlay start hide-start))
1022 (setq ov2 (make-overlay hide-start end))
1023 (overlay-put ov2 'invisible 'org-babel-hide-hash)
1024 (overlay-put ov1 'babel-hash hash)))))
1026 (defun org-babel-hide-all-hashes ()
1027 "Hide the hash in the current buffer.
1028 Only the initial `org-babel-hash-show' characters of each hash
1029 will remain visible. This function should be called as part of
1030 the `org-mode-hook'."
1031 (save-excursion
1032 (while (re-search-forward org-babel-result-regexp nil t)
1033 (goto-char (match-beginning 0))
1034 (org-babel-hide-hash)
1035 (goto-char (match-end 0)))))
1036 (add-hook 'org-mode-hook 'org-babel-hide-all-hashes)
1038 (defun org-babel-hash-at-point (&optional point)
1039 "Return the value of the hash at POINT.
1040 The hash is also added as the last element of the kill ring.
1041 This can be called with C-c C-c."
1042 (interactive)
1043 (let ((hash (car (delq nil (mapcar
1044 (lambda (ol) (overlay-get ol 'babel-hash))
1045 (overlays-at (or point (point))))))))
1046 (when hash (kill-new hash) (message hash))))
1047 (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-hash-at-point)
1049 (defun org-babel-result-hide-spec ()
1050 "Hide portions of results lines.
1051 Add `org-babel-hide-result' as an invisibility spec for hiding
1052 portions of results lines."
1053 (add-to-invisibility-spec '(org-babel-hide-result . t)))
1054 (add-hook 'org-mode-hook 'org-babel-result-hide-spec)
1056 (defvar org-babel-hide-result-overlays nil
1057 "Overlays hiding results.")
1059 (defun org-babel-result-hide-all ()
1060 "Fold all results in the current buffer."
1061 (interactive)
1062 (org-babel-show-result-all)
1063 (save-excursion
1064 (while (re-search-forward org-babel-result-regexp nil t)
1065 (save-excursion (goto-char (match-beginning 0))
1066 (org-babel-hide-result-toggle-maybe)))))
1068 (defun org-babel-show-result-all ()
1069 "Unfold all results in the current buffer."
1070 (mapc 'delete-overlay org-babel-hide-result-overlays)
1071 (setq org-babel-hide-result-overlays nil))
1073 ;;;###autoload
1074 (defun org-babel-hide-result-toggle-maybe ()
1075 "Toggle visibility of result at point."
1076 (interactive)
1077 (let ((case-fold-search t))
1078 (if (save-excursion
1079 (beginning-of-line 1)
1080 (looking-at org-babel-result-regexp))
1081 (progn (org-babel-hide-result-toggle)
1082 t) ;; to signal that we took action
1083 nil))) ;; to signal that we did not
1085 (defun org-babel-hide-result-toggle (&optional force)
1086 "Toggle the visibility of the current result."
1087 (interactive)
1088 (save-excursion
1089 (beginning-of-line)
1090 (if (re-search-forward org-babel-result-regexp nil t)
1091 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
1092 (end (progn
1093 (while (looking-at org-babel-multi-line-header-regexp)
1094 (forward-line 1))
1095 (goto-char (- (org-babel-result-end) 1)) (point)))
1097 (if (memq t (mapcar (lambda (overlay)
1098 (eq (overlay-get overlay 'invisible)
1099 'org-babel-hide-result))
1100 (overlays-at start)))
1101 (if (or (not force) (eq force 'off))
1102 (mapc (lambda (ov)
1103 (when (member ov org-babel-hide-result-overlays)
1104 (setq org-babel-hide-result-overlays
1105 (delq ov org-babel-hide-result-overlays)))
1106 (when (eq (overlay-get ov 'invisible)
1107 'org-babel-hide-result)
1108 (delete-overlay ov)))
1109 (overlays-at start)))
1110 (setq ov (make-overlay start end))
1111 (overlay-put ov 'invisible 'org-babel-hide-result)
1112 ;; make the block accessible to isearch
1113 (overlay-put
1114 ov 'isearch-open-invisible
1115 (lambda (ov)
1116 (when (member ov org-babel-hide-result-overlays)
1117 (setq org-babel-hide-result-overlays
1118 (delq ov org-babel-hide-result-overlays)))
1119 (when (eq (overlay-get ov 'invisible)
1120 'org-babel-hide-result)
1121 (delete-overlay ov))))
1122 (push ov org-babel-hide-result-overlays)))
1123 (error "Not looking at a result line"))))
1125 ;; org-tab-after-check-for-cycling-hook
1126 (add-hook 'org-tab-first-hook 'org-babel-hide-result-toggle-maybe)
1127 ;; Remove overlays when changing major mode
1128 (add-hook 'org-mode-hook
1129 (lambda () (org-add-hook 'change-major-mode-hook
1130 'org-babel-show-result-all 'append 'local)))
1132 (defvar org-file-properties)
1133 (defun org-babel-params-from-properties (&optional lang)
1134 "Retrieve parameters specified as properties.
1135 Return an association list of any source block params which
1136 may be specified in the properties of the current outline entry."
1137 (save-match-data
1138 (let (val sym)
1139 (org-babel-parse-multiple-vars
1140 (delq nil
1141 (mapcar
1142 (lambda (header-arg)
1143 (and (setq val (org-entry-get (point) header-arg t))
1144 (cons (intern (concat ":" header-arg))
1145 (org-babel-read val))))
1146 (mapcar
1147 'symbol-name
1148 (append
1149 org-babel-header-arg-names
1150 (progn
1151 (setq sym (intern (concat "org-babel-header-arg-names:"
1152 lang)))
1153 (and (boundp sym) (eval sym)))))))))))
1155 (defvar org-src-preserve-indentation)
1156 (defun org-babel-parse-src-block-match ()
1157 "Parse the results from a match of the `org-babel-src-block-regexp'."
1158 (let* ((block-indentation (length (match-string 1)))
1159 (lang (org-babel-clean-text-properties (match-string 2)))
1160 (lang-headers (intern (concat "org-babel-default-header-args:" lang)))
1161 (switches (match-string 3))
1162 (body (org-babel-clean-text-properties
1163 (let* ((body (match-string 5))
1164 (sub-length (- (length body) 1)))
1165 (if (and (> sub-length 0)
1166 (string= "\n" (substring body sub-length)))
1167 (substring body 0 sub-length)
1168 (or body "")))))
1169 (preserve-indentation (or org-src-preserve-indentation
1170 (string-match "-i\\>" switches))))
1171 (list lang
1172 ;; get block body less properties, protective commas, and indentation
1173 (with-temp-buffer
1174 (save-match-data
1175 (insert (org-babel-strip-protective-commas body))
1176 (unless preserve-indentation (org-do-remove-indentation))
1177 (buffer-string)))
1178 (org-babel-merge-params
1179 org-babel-default-header-args
1180 (org-babel-params-from-properties lang)
1181 (if (boundp lang-headers) (eval lang-headers) nil)
1182 (org-babel-parse-header-arguments
1183 (org-babel-clean-text-properties (or (match-string 4) ""))))
1184 switches
1185 block-indentation)))
1187 (defun org-babel-parse-inline-src-block-match ()
1188 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
1189 (let* ((lang (org-babel-clean-text-properties (match-string 2)))
1190 (lang-headers (intern (concat "org-babel-default-header-args:" lang))))
1191 (list lang
1192 (org-babel-strip-protective-commas
1193 (org-babel-clean-text-properties (match-string 5)))
1194 (org-babel-merge-params
1195 org-babel-default-inline-header-args
1196 (org-babel-params-from-properties lang)
1197 (if (boundp lang-headers) (eval lang-headers) nil)
1198 (org-babel-parse-header-arguments
1199 (org-babel-clean-text-properties (or (match-string 4) "")))))))
1201 (defun org-babel-balanced-split (string alts)
1202 "Split STRING on instances of ALTS.
1203 ALTS is a cons of two character options where each option may be
1204 either the numeric code of a single character or a list of
1205 character alternatives. For example to split on balanced
1206 instances of \"[ \t]:\" set ALTS to '((32 9) . 58)."
1207 (flet ((matches (ch spec) (if (listp spec) (member ch spec) (equal spec ch)))
1208 (matched (ch last)
1209 (if (consp alts)
1210 (and (matches ch (cdr alts))
1211 (matches last (car alts)))
1212 (matches ch alts))))
1213 (let ((balance 0) (quote nil) (partial nil) (lst nil) (last 0))
1214 (mapc (lambda (ch) ; split on [], (), "" balanced instances of [ \t]:
1215 (setq balance (+ balance
1216 (cond ((or (equal 91 ch) (equal 40 ch)) 1)
1217 ((or (equal 93 ch) (equal 41 ch)) -1)
1218 (t 0))))
1219 (when (and (equal 34 ch) (not (equal 92 last)))
1220 (setq quote (not quote)))
1221 (setq partial (cons ch partial))
1222 (when (and (= balance 0) (not quote) (matched ch last))
1223 (setq lst (cons (apply #'string (nreverse
1224 (if (consp alts)
1225 (cddr partial)
1226 (cdr partial))))
1227 lst))
1228 (setq partial nil))
1229 (setq last ch))
1230 (string-to-list string))
1231 (nreverse (cons (apply #'string (nreverse partial)) lst)))))
1233 (defun org-babel-join-splits-near-ch (ch list)
1234 "Join splits where \"=\" is on either end of the split."
1235 (flet ((last= (str) (= ch (aref str (1- (length str)))))
1236 (first= (str) (= ch (aref str 0))))
1237 (reverse
1238 (org-reduce (lambda (acc el)
1239 (let ((head (car acc)))
1240 (if (and head (or (last= head) (first= el)))
1241 (cons (concat head el) (cdr acc))
1242 (cons el acc))))
1243 list :initial-value nil))))
1245 (defun org-babel-parse-header-arguments (arg-string)
1246 "Parse a string of header arguments returning an alist."
1247 (when (> (length arg-string) 0)
1248 (org-babel-parse-multiple-vars
1249 (delq nil
1250 (mapcar
1251 (lambda (arg)
1252 (if (string-match
1253 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1254 arg)
1255 (cons (intern (match-string 1 arg))
1256 (org-babel-read (org-babel-chomp (match-string 2 arg))))
1257 (cons (intern (org-babel-chomp arg)) nil)))
1258 ((lambda (raw)
1259 (cons (car raw) (mapcar (lambda (r) (concat ":" r)) (cdr raw))))
1260 (org-babel-balanced-split arg-string '((32 9) . 58))))))))
1262 (defun org-babel-parse-multiple-vars (header-arguments)
1263 "Expand multiple variable assignments behind a single :var keyword.
1265 This allows expression of multiple variables with one :var as
1266 shown below.
1268 #+PROPERTY: var foo=1, bar=2"
1269 (let (results)
1270 (mapc (lambda (pair)
1271 (if (eq (car pair) :var)
1272 (mapcar (lambda (v) (push (cons :var (org-babel-trim v)) results))
1273 (org-babel-join-splits-near-ch
1274 61 (org-babel-balanced-split (cdr pair) 32)))
1275 (push pair results)))
1276 header-arguments)
1277 (nreverse results)))
1279 (defun org-babel-process-params (params)
1280 "Expand variables in PARAMS and add summary parameters."
1281 (let* ((processed-vars (mapcar (lambda (el)
1282 (if (consp (cdr el))
1283 (cdr el)
1284 (org-babel-ref-parse (cdr el))))
1285 (org-babel-get-header params :var)))
1286 (vars-and-names (if (and (assoc :colname-names params)
1287 (assoc :rowname-names params))
1288 (list processed-vars)
1289 (org-babel-disassemble-tables
1290 processed-vars
1291 (cdr (assoc :hlines params))
1292 (cdr (assoc :colnames params))
1293 (cdr (assoc :rownames params)))))
1294 (raw-result (or (cdr (assoc :results params)) ""))
1295 (result-params (append
1296 (split-string (if (stringp raw-result)
1297 raw-result
1298 (eval raw-result)))
1299 (cdr (assoc :result-params params)))))
1300 (append
1301 (mapcar (lambda (var) (cons :var var)) (car vars-and-names))
1302 (list
1303 (cons :colname-names (or (cdr (assoc :colname-names params))
1304 (cadr vars-and-names)))
1305 (cons :rowname-names (or (cdr (assoc :rowname-names params))
1306 (caddr vars-and-names)))
1307 (cons :result-params result-params)
1308 (cons :result-type (cond ((member "output" result-params) 'output)
1309 ((member "value" result-params) 'value)
1310 (t 'value))))
1311 (org-babel-get-header params :var 'other))))
1313 ;; row and column names
1314 (defun org-babel-del-hlines (table)
1315 "Remove all 'hlines from TABLE."
1316 (remove 'hline table))
1318 (defun org-babel-get-colnames (table)
1319 "Return the column names of TABLE.
1320 Return a cons cell, the `car' of which contains the TABLE less
1321 colnames, and the `cdr' of which contains a list of the column
1322 names."
1323 (if (equal 'hline (nth 1 table))
1324 (cons (cddr table) (car table))
1325 (cons (cdr table) (car table))))
1327 (defun org-babel-get-rownames (table)
1328 "Return the row names of TABLE.
1329 Return a cons cell, the `car' of which contains the TABLE less
1330 colnames, and the `cdr' of which contains a list of the column
1331 names. Note: this function removes any hlines in TABLE."
1332 (flet ((trans (table) (apply #'mapcar* #'list table)))
1333 (let* ((width (apply 'max
1334 (mapcar (lambda (el) (if (listp el) (length el) 0)) table)))
1335 (table (trans (mapcar (lambda (row)
1336 (if (not (equal row 'hline))
1338 (setq row '())
1339 (dotimes (n width)
1340 (setq row (cons 'hline row)))
1341 row))
1342 table))))
1343 (cons (mapcar (lambda (row) (if (equal (car row) 'hline) 'hline row))
1344 (trans (cdr table)))
1345 (remove 'hline (car table))))))
1347 (defun org-babel-put-colnames (table colnames)
1348 "Add COLNAMES to TABLE if they exist."
1349 (if colnames (apply 'list colnames 'hline table) table))
1351 (defun org-babel-put-rownames (table rownames)
1352 "Add ROWNAMES to TABLE if they exist."
1353 (if rownames
1354 (mapcar (lambda (row)
1355 (if (listp row)
1356 (cons (or (pop rownames) "") row)
1357 row)) table)
1358 table))
1360 (defun org-babel-pick-name (names selector)
1361 "Select one out of an alist of row or column names.
1362 SELECTOR can be either a list of names in which case those names
1363 will be returned directly, or an index into the list NAMES in
1364 which case the indexed names will be return."
1365 (if (listp selector)
1366 selector
1367 (when names
1368 (if (and selector (symbolp selector) (not (equal t selector)))
1369 (cdr (assoc selector names))
1370 (if (integerp selector)
1371 (nth (- selector 1) names)
1372 (cdr (car (last names))))))))
1374 (defun org-babel-disassemble-tables (vars hlines colnames rownames)
1375 "Parse tables for further processing.
1376 Process the variables in VARS according to the HLINES,
1377 ROWNAMES and COLNAMES header arguments. Return a list consisting
1378 of the vars, cnames and rnames."
1379 (let (cnames rnames)
1380 (list
1381 (mapcar
1382 (lambda (var)
1383 (when (listp (cdr var))
1384 (when (and (not (equal colnames "no"))
1385 (or colnames (and (equal (nth 1 (cdr var)) 'hline)
1386 (not (member 'hline (cddr (cdr var)))))))
1387 (let ((both (org-babel-get-colnames (cdr var))))
1388 (setq cnames (cons (cons (car var) (cdr both))
1389 cnames))
1390 (setq var (cons (car var) (car both)))))
1391 (when (and rownames (not (equal rownames "no")))
1392 (let ((both (org-babel-get-rownames (cdr var))))
1393 (setq rnames (cons (cons (car var) (cdr both))
1394 rnames))
1395 (setq var (cons (car var) (car both)))))
1396 (when (and hlines (not (equal hlines "yes")))
1397 (setq var (cons (car var) (org-babel-del-hlines (cdr var))))))
1398 var)
1399 vars)
1400 (reverse cnames) (reverse rnames))))
1402 (defun org-babel-reassemble-table (table colnames rownames)
1403 "Add column and row names to a table.
1404 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1405 to the table for reinsertion to org-mode."
1406 (if (listp table)
1407 ((lambda (table)
1408 (if (and colnames (listp (car table)) (= (length (car table))
1409 (length colnames)))
1410 (org-babel-put-colnames table colnames) table))
1411 (if (and rownames (= (length table) (length rownames)))
1412 (org-babel-put-rownames table rownames) table))
1413 table))
1415 (defun org-babel-where-is-src-block-head ()
1416 "Find where the current source block begins.
1417 Return the point at the beginning of the current source
1418 block. Specifically at the beginning of the #+BEGIN_SRC line.
1419 If the point is not on a source block then return nil."
1420 (let ((initial (point)) top bottom)
1422 (save-excursion ;; on a source name line or a #+header line
1423 (beginning-of-line 1)
1424 (and (or (looking-at org-babel-src-name-regexp)
1425 (looking-at org-babel-multi-line-header-regexp))
1426 (progn
1427 (while (and (forward-line 1)
1428 (looking-at org-babel-multi-line-header-regexp)))
1429 (looking-at org-babel-src-block-regexp))
1430 (point)))
1431 (save-excursion ;; on a #+begin_src line
1432 (beginning-of-line 1)
1433 (and (looking-at org-babel-src-block-regexp)
1434 (point)))
1435 (save-excursion ;; inside a src block
1436 (and
1437 (re-search-backward "^[ \t]*#\\+begin_src" nil t) (setq top (point))
1438 (re-search-forward "^[ \t]*#\\+end_src" nil t) (setq bottom (point))
1439 (< top initial) (< initial bottom)
1440 (progn (goto-char top) (beginning-of-line 1)
1441 (looking-at org-babel-src-block-regexp))
1442 (point))))))
1444 ;;;###autoload
1445 (defun org-babel-goto-src-block-head ()
1446 "Go to the beginning of the current code block."
1447 (interactive)
1448 ((lambda (head)
1449 (if head (goto-char head) (error "not currently in a code block")))
1450 (org-babel-where-is-src-block-head)))
1452 ;;;###autoload
1453 (defun org-babel-goto-named-src-block (name)
1454 "Go to a named source-code block."
1455 (interactive
1456 (let ((completion-ignore-case t))
1457 (list (org-icompleting-read "source-block name: "
1458 (org-babel-src-block-names) nil t))))
1459 (let ((point (org-babel-find-named-block name)))
1460 (if point
1461 ;; taken from `org-open-at-point'
1462 (progn (goto-char point) (org-show-context))
1463 (message "source-code block '%s' not found in this buffer" name))))
1465 (defun org-babel-find-named-block (name)
1466 "Find a named source-code block.
1467 Return the location of the source block identified by source
1468 NAME, or nil if no such block exists. Set match data according to
1469 org-babel-named-src-block-regexp."
1470 (save-excursion
1471 (let ((case-fold-search t)
1472 (regexp (org-babel-named-src-block-regexp-for-name name)) msg)
1473 (goto-char (point-min))
1474 (when (or (re-search-forward regexp nil t)
1475 (re-search-backward regexp nil t))
1476 (match-beginning 0)))))
1478 (defun org-babel-src-block-names (&optional file)
1479 "Returns the names of source blocks in FILE or the current buffer."
1480 (save-excursion
1481 (when file (find-file file)) (goto-char (point-min))
1482 (let (names)
1483 (while (re-search-forward org-babel-src-name-w-name-regexp nil t)
1484 (setq names (cons (match-string 3) names)))
1485 names)))
1487 ;;;###autoload
1488 (defun org-babel-goto-named-result (name)
1489 "Go to a named result."
1490 (interactive
1491 (let ((completion-ignore-case t))
1492 (list (org-icompleting-read "source-block name: "
1493 (org-babel-result-names) nil t))))
1494 (let ((point (org-babel-find-named-result name)))
1495 (if point
1496 ;; taken from `org-open-at-point'
1497 (progn (goto-char point) (org-show-context))
1498 (message "result '%s' not found in this buffer" name))))
1500 (defun org-babel-find-named-result (name &optional point)
1501 "Find a named result.
1502 Return the location of the result named NAME in the current
1503 buffer or nil if no such result exists."
1504 (save-excursion
1505 (goto-char (or point (point-min)))
1506 (catch 'is-a-code-block
1507 (when (re-search-forward
1508 (concat org-babel-result-regexp
1509 "[ \t]" (regexp-quote name) "[ \t\n\f\v\r]") nil t)
1510 (when (and (string= "name" (downcase (match-string 1)))
1511 (or (looking-at org-babel-src-block-regexp)
1512 (looking-at org-babel-multi-line-header-regexp)))
1513 (throw 'is-a-code-block (org-babel-find-named-result name (point))))
1514 (beginning-of-line 0) (point)))))
1516 (defun org-babel-result-names (&optional file)
1517 "Returns the names of results in FILE or the current buffer."
1518 (save-excursion
1519 (when file (find-file file)) (goto-char (point-min))
1520 (let (names)
1521 (while (re-search-forward org-babel-result-w-name-regexp nil t)
1522 (setq names (cons (match-string 4) names)))
1523 names)))
1525 ;;;###autoload
1526 (defun org-babel-next-src-block (&optional arg)
1527 "Jump to the next source block.
1528 With optional prefix argument ARG, jump forward ARG many source blocks."
1529 (interactive "P")
1530 (when (looking-at org-babel-src-block-regexp) (forward-char 1))
1531 (condition-case nil
1532 (re-search-forward org-babel-src-block-regexp nil nil (or arg 1))
1533 (error (error "No further code blocks")))
1534 (goto-char (match-beginning 0)) (org-show-context))
1536 ;;;###autoload
1537 (defun org-babel-previous-src-block (&optional arg)
1538 "Jump to the previous source block.
1539 With optional prefix argument ARG, jump backward ARG many source blocks."
1540 (interactive "P")
1541 (condition-case nil
1542 (re-search-backward org-babel-src-block-regexp nil nil (or arg 1))
1543 (error (error "No previous code blocks")))
1544 (goto-char (match-beginning 0)) (org-show-context))
1546 (defvar org-babel-load-languages)
1548 ;;;###autoload
1549 (defun org-babel-mark-block ()
1550 "Mark current src block"
1551 (interactive)
1552 ((lambda (head)
1553 (when head
1554 (save-excursion
1555 (goto-char head)
1556 (looking-at org-babel-src-block-regexp))
1557 (push-mark (match-end 5) nil t)
1558 (goto-char (match-beginning 5))))
1559 (org-babel-where-is-src-block-head)))
1561 (defun org-babel-demarcate-block (&optional arg)
1562 "Wrap or split the code in the region or on the point.
1563 When called from inside of a code block the current block is
1564 split. When called from outside of a code block a new code block
1565 is created. In both cases if the region is demarcated and if the
1566 region is not active then the point is demarcated."
1567 (interactive "P")
1568 (let ((info (org-babel-get-src-block-info 'light))
1569 (headers (progn (org-babel-where-is-src-block-head)
1570 (match-string 4)))
1571 (stars (concat (make-string (or (org-current-level) 1) ?*) " ")))
1572 (if info
1573 (mapc
1574 (lambda (place)
1575 (save-excursion
1576 (goto-char place)
1577 (let ((lang (nth 0 info))
1578 (indent (make-string (nth 5 info) ? )))
1579 (when (string-match "^[[:space:]]*$"
1580 (buffer-substring (point-at-bol)
1581 (point-at-eol)))
1582 (delete-region (point-at-bol) (point-at-eol)))
1583 (insert (concat
1584 (if (looking-at "^") "" "\n")
1585 indent "#+end_src\n"
1586 (if arg stars indent) "\n"
1587 indent "#+begin_src " lang
1588 (if (> (length headers) 1)
1589 (concat " " headers) headers)
1590 (if (looking-at "[\n\r]")
1592 (concat "\n" (make-string (current-column) ? )))))))
1593 (move-end-of-line 2))
1594 (sort (if (region-active-p) (list (mark) (point)) (list (point))) #'>))
1595 (let ((start (point))
1596 (lang (org-icompleting-read "Lang: "
1597 (mapcar (lambda (el) (symbol-name (car el)))
1598 org-babel-load-languages)))
1599 (body (delete-and-extract-region
1600 (if (region-active-p) (mark) (point)) (point))))
1601 (insert (concat (if (looking-at "^") "" "\n")
1602 (if arg (concat stars "\n") "")
1603 "#+begin_src " lang "\n"
1604 body
1605 (if (or (= (length body) 0)
1606 (string-match "[\r\n]$" body)) "" "\n")
1607 "#+end_src\n"))
1608 (goto-char start) (move-end-of-line 1)))))
1610 (defvar org-babel-lob-one-liner-regexp)
1611 (defun org-babel-where-is-src-block-result (&optional insert info hash indent)
1612 "Find where the current source block results begin.
1613 Return the point at the beginning of the result of the current
1614 source block. Specifically at the beginning of the results line.
1615 If no result exists for this block then create a results line
1616 following the source block."
1617 (save-excursion
1618 (let* ((on-lob-line (save-excursion
1619 (beginning-of-line 1)
1620 (looking-at org-babel-lob-one-liner-regexp)))
1621 (inlinep (when (org-babel-get-inline-src-block-matches)
1622 (match-end 0)))
1623 (name (if on-lob-line
1624 (nth 0 (org-babel-lob-get-info))
1625 (nth 4 (or info (org-babel-get-src-block-info 'light)))))
1626 (head (unless on-lob-line (org-babel-where-is-src-block-head)))
1627 found beg end)
1628 (when head (goto-char head))
1629 (setq
1630 found ;; was there a result (before we potentially insert one)
1632 inlinep
1633 (and
1634 ;; named results:
1635 ;; - return t if it is found, else return nil
1636 ;; - if it does not need to be rebuilt, then don't set end
1637 ;; - if it does need to be rebuilt then do set end
1638 name (setq beg (org-babel-find-named-result name))
1639 (prog1 beg
1640 (when (and hash (not (string= hash (match-string 3))))
1641 (goto-char beg) (setq end beg) ;; beginning of result
1642 (forward-line 1)
1643 (delete-region end (org-babel-result-end)) nil)))
1644 (and
1645 ;; unnamed results:
1646 ;; - return t if it is found, else return nil
1647 ;; - if it is found, and the hash doesn't match, delete and set end
1648 (or on-lob-line (re-search-forward "^[ \t]*#\\+end_src" nil t))
1649 (progn (end-of-line 1)
1650 (if (eobp) (insert "\n") (forward-char 1))
1651 (setq end (point))
1652 (or (and (not name)
1653 (progn ;; unnamed results line already exists
1654 (re-search-forward "[^ \f\t\n\r\v]" nil t)
1655 (beginning-of-line 1)
1656 (looking-at
1657 (concat org-babel-result-regexp "\n")))
1658 (prog1 (point)
1659 ;; must remove and rebuild if hash!=old-hash
1660 (if (and hash (not (string= hash (match-string 3))))
1661 (prog1 nil
1662 (forward-line 1)
1663 (delete-region
1664 end (org-babel-result-end)))
1665 (setq end nil)))))))))
1666 (if (and insert end)
1667 (progn
1668 (goto-char end)
1669 (unless beg
1670 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1671 (insert (concat
1672 (if indent
1673 (mapconcat
1674 (lambda (el) " ")
1675 (org-number-sequence 1 indent) "")
1677 "#+" org-babel-results-keyword
1678 (when hash (concat "["hash"]"))
1680 (when name (concat " " name)) "\n"))
1681 (unless beg (insert "\n") (backward-char))
1682 (beginning-of-line 0)
1683 (if hash (org-babel-hide-hash))
1684 (point))
1685 found))))
1687 (defvar org-block-regexp)
1688 (defun org-babel-read-result ()
1689 "Read the result at `point' into emacs-lisp."
1690 (let ((case-fold-search t) result-string)
1691 (cond
1692 ((org-at-table-p) (org-babel-read-table))
1693 ((org-at-item-p) (org-babel-read-list))
1694 ((looking-at org-bracket-link-regexp) (org-babel-read-link))
1695 ((looking-at org-block-regexp) (org-babel-trim (match-string 4)))
1696 ((looking-at "^[ \t]*: ")
1697 (setq result-string
1698 (org-babel-trim
1699 (mapconcat (lambda (line)
1700 (if (and (> (length line) 1)
1701 (string-match "^[ \t]*: \\(.+\\)" line))
1702 (match-string 1 line)
1703 line))
1704 (split-string
1705 (buffer-substring
1706 (point) (org-babel-result-end)) "[\r\n]+")
1707 "\n")))
1708 (or (org-babel-number-p result-string) result-string))
1709 ((looking-at org-babel-result-regexp)
1710 (save-excursion (forward-line 1) (org-babel-read-result))))))
1712 (defun org-babel-read-table ()
1713 "Read the table at `point' into emacs-lisp."
1714 (mapcar (lambda (row)
1715 (if (and (symbolp row) (equal row 'hline)) row
1716 (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval)) row)))
1717 (org-table-to-lisp)))
1719 (defun org-babel-read-list ()
1720 "Read the list at `point' into emacs-lisp."
1721 (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval))
1722 (mapcar #'cadr (cdr (org-list-parse-list)))))
1724 (defvar org-link-types-re)
1725 (defun org-babel-read-link ()
1726 "Read the link at `point' into emacs-lisp.
1727 If the path of the link is a file path it is expanded using
1728 `expand-file-name'."
1729 (let* ((case-fold-search t)
1730 (raw (and (looking-at org-bracket-link-regexp)
1731 (org-babel-clean-text-properties (match-string 1))))
1732 (type (and (string-match org-link-types-re raw)
1733 (match-string 1 raw))))
1734 (cond
1735 ((not type) (expand-file-name raw))
1736 ((string= type "file")
1737 (and (string-match "file\\(.*\\):\\(.+\\)" raw)
1738 (expand-file-name (match-string 2 raw))))
1739 (t raw))))
1741 (defun org-babel-format-result (result &optional sep)
1742 "Format RESULT for writing to file."
1743 (flet ((echo-res (result)
1744 (if (stringp result) result (format "%S" result))))
1745 (if (listp result)
1746 ;; table result
1747 (orgtbl-to-generic
1748 result
1749 (list
1750 :sep (or sep "\t")
1751 :fmt 'echo-res))
1752 ;; scalar result
1753 (echo-res result))))
1755 (defun org-babel-insert-result
1756 (result &optional result-params info hash indent lang)
1757 "Insert RESULT into the current buffer.
1758 By default RESULT is inserted after the end of the
1759 current source block. With optional argument RESULT-PARAMS
1760 controls insertion of results in the org-mode file.
1761 RESULT-PARAMS can take the following values...
1763 replace - (default option) insert results after the source block
1764 replacing any previously inserted results
1766 silent -- no results are inserted
1768 file ---- the results are interpreted as a file path, and are
1769 inserted into the buffer using the Org-mode file syntax
1771 list ---- the results are interpreted as an Org-mode list.
1773 raw ----- results are added directly to the Org-mode file. This
1774 is a good option if you code block will output org-mode
1775 formatted text.
1777 wrap ---- results are added directly to the Org-mode file as with
1778 \"raw\", but are wrapped in a RESULTS drawer, allowing
1779 them to later be replaced or removed automatically.
1781 org ----- similar in effect to raw, only the results are wrapped
1782 in an org code block. Similar to the raw option, on
1783 export the results will be interpreted as org-formatted
1784 text, however by wrapping the results in an org code
1785 block they can be replaced upon re-execution of the
1786 code block.
1788 html ---- results are added inside of a #+BEGIN_HTML block. This
1789 is a good option if you code block will output html
1790 formatted text.
1792 latex --- results are added inside of a #+BEGIN_LATEX block.
1793 This is a good option if you code block will output
1794 latex formatted text.
1796 code ---- the results are extracted in the syntax of the source
1797 code of the language being evaluated and are added
1798 inside of a #+BEGIN_SRC block with the source-code
1799 language set appropriately. Note this relies on the
1800 optional LANG argument."
1801 (if (stringp result)
1802 (progn
1803 (setq result (org-babel-clean-text-properties result))
1804 (when (member "file" result-params)
1805 (setq result (org-babel-result-to-file result))))
1806 (unless (listp result) (setq result (format "%S" result))))
1807 (if (and result-params (member "silent" result-params))
1808 (progn
1809 (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
1810 result)
1811 (save-excursion
1812 (let* ((inlinep
1813 (save-excursion
1814 (when (or (org-babel-get-inline-src-block-matches)
1815 (org-babel-get-lob-one-liner-matches))
1816 (goto-char (match-end 0))
1817 (insert (if (listp result) "\n" " "))
1818 (point))))
1819 (existing-result (unless inlinep
1820 (org-babel-where-is-src-block-result
1821 t info hash indent)))
1822 (results-switches
1823 (cdr (assoc :results_switches (nth 2 info))))
1824 beg end)
1825 (when (and (stringp result) ; ensure results end in a newline
1826 (not inlinep)
1827 (> (length result) 0)
1828 (not (or (string-equal (substring result -1) "\n")
1829 (string-equal (substring result -1) "\r"))))
1830 (setq result (concat result "\n")))
1831 (if (not existing-result)
1832 (setq beg (or inlinep (point)))
1833 (goto-char existing-result)
1834 (save-excursion
1835 (re-search-forward "#" nil t)
1836 (setq indent (- (current-column) 1)))
1837 (forward-line 1)
1838 (setq beg (point))
1839 (cond
1840 ((member "replace" result-params)
1841 (delete-region (point) (org-babel-result-end)))
1842 ((member "append" result-params)
1843 (goto-char (org-babel-result-end)) (setq beg (point-marker)))
1844 ((member "prepend" result-params)))) ; already there
1845 (setq results-switches
1846 (if results-switches (concat " " results-switches) ""))
1847 (flet ((wrap (start finish)
1848 (goto-char beg) (insert (concat start "\n"))
1849 (goto-char end) (insert (concat finish "\n"))
1850 (setq end (point-marker)))
1851 (proper-list-p (it) (and (listp it) (null (cdr (last it))))))
1852 ;; insert results based on type
1853 (cond
1854 ;; do nothing for an empty result
1855 ((null result))
1856 ;; insert a list if preferred
1857 ((member "list" result-params)
1858 (insert
1859 (org-babel-trim
1860 (org-list-to-generic
1861 (cons 'unordered
1862 (mapcar
1863 (lambda (el) (list nil (if (stringp el) el (format "%S" el))))
1864 (if (listp result) result (list result))))
1865 '(:splicep nil :istart "- " :iend "\n")))
1866 "\n"))
1867 ;; assume the result is a table if it's not a string
1868 ((proper-list-p result)
1869 (goto-char beg)
1870 (insert (concat (orgtbl-to-orgtbl
1871 (if (or (eq 'hline (car result))
1872 (and (listp (car result))
1873 (listp (cdr (car result)))))
1874 result (list result))
1875 '(:fmt (lambda (cell) (format "%s" cell)))) "\n"))
1876 (goto-char beg) (when (org-at-table-p) (org-table-align)))
1877 ((and (listp result) (not (proper-list-p result)))
1878 (insert (format "%s\n" result)))
1879 ((member "file" result-params)
1880 (when inlinep (goto-char inlinep))
1881 (insert result))
1882 (t (goto-char beg) (insert result)))
1883 (when (proper-list-p result) (goto-char (org-table-end)))
1884 (setq end (point-marker))
1885 ;; possibly wrap result
1886 (cond
1887 ((assoc :wrap (nth 2 info))
1888 (let ((name (or (cdr (assoc :wrap (nth 2 info))) "RESULTS")))
1889 (wrap (concat "#+BEGIN_" name) (concat "#+END_" name))))
1890 ((member "html" result-params)
1891 (wrap "#+BEGIN_HTML" "#+END_HTML"))
1892 ((member "latex" result-params)
1893 (wrap "#+BEGIN_LaTeX" "#+END_LaTeX"))
1894 ((member "code" result-params)
1895 (wrap (format "#+BEGIN_SRC %s%s" (or lang "none") results-switches)
1896 "#+END_SRC"))
1897 ((member "org" result-params)
1898 (wrap "#+BEGIN_ORG" "#+END_ORG"))
1899 ((member "raw" result-params)
1900 (goto-char beg) (if (org-at-table-p) (org-cycle)))
1901 ((member "wrap" result-params)
1902 (wrap ":RESULTS:" ":END:"))
1903 ((and (not (proper-list-p result))
1904 (not (member "file" result-params)))
1905 (org-babel-examplize-region beg end results-switches)
1906 (setq end (point)))))
1907 ;; possibly indent the results to match the #+results line
1908 (when (and (not inlinep) (numberp indent) indent (> indent 0)
1909 ;; in this case `table-align' does the work for us
1910 (not (and (listp result)
1911 (member "append" result-params))))
1912 (indent-rigidly beg end indent))))
1913 (if (null result)
1914 (if (member "value" result-params)
1915 (message "Code block returned no value.")
1916 (message "Code block produced no output."))
1917 (message "Code block evaluation complete."))))
1919 (defun org-babel-remove-result (&optional info)
1920 "Remove the result of the current source block."
1921 (interactive)
1922 (let ((location (org-babel-where-is-src-block-result nil info)) start)
1923 (when location
1924 (setq start (- location 1))
1925 (save-excursion
1926 (goto-char location) (forward-line 1)
1927 (delete-region start (org-babel-result-end))))))
1929 (defun org-babel-result-end ()
1930 "Return the point at the end of the current set of results"
1931 (save-excursion
1932 (cond
1933 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
1934 ((org-at-item-p) (let* ((struct (org-list-struct))
1935 (prvs (org-list-prevs-alist struct)))
1936 (org-list-get-list-end (point-at-bol) struct prvs)))
1937 ((looking-at "^\\([ \t]*\\):RESULTS:")
1938 (progn (re-search-forward (concat "^" (match-string 1) ":END:"))
1939 (forward-char 1) (point)))
1941 (let ((case-fold-search t))
1942 (if (looking-at (concat "[ \t]*#\\+begin_\\([^ \t\n\r]+\\)"))
1943 (progn (re-search-forward (concat "[ \t]*#\\+end_" (match-string 1))
1944 nil t)
1945 (forward-char 1))
1946 (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
1947 (forward-line 1))))
1948 (point)))))
1950 (defun org-babel-result-to-file (result)
1951 "Convert RESULT into an `org-mode' link.
1952 If the `default-directory' is different from the containing
1953 file's directory then expand relative links."
1954 (flet ((cond-exp (file)
1955 (if (and default-directory
1956 buffer-file-name
1957 (not (string= (expand-file-name default-directory)
1958 (expand-file-name
1959 (file-name-directory buffer-file-name)))))
1960 (expand-file-name file default-directory)
1961 file)))
1962 (if (stringp result)
1963 (format "[[file:%s]]" (cond-exp result))
1964 (when (and (listp result) (= 2 (length result))
1965 (stringp (car result)) (stringp (cadr result)))
1966 (format "[[file:%s][%s]]" (car result) (cadr result))))))
1968 (defun org-babel-examplize-region (beg end &optional results-switches)
1969 "Comment out region using the inline '==' or ': ' org example quote."
1970 (interactive "*r")
1971 (flet ((chars-between (b e) (string-match "[\\S]" (buffer-substring b e))))
1972 (if (or (chars-between (save-excursion (goto-char beg) (point-at-bol)) beg)
1973 (chars-between end (save-excursion (goto-char end) (point-at-eol))))
1974 (save-excursion
1975 (goto-char beg)
1976 (insert (format "=%s=" (prog1 (buffer-substring beg end)
1977 (delete-region beg end)))))
1978 (let ((size (count-lines beg end)))
1979 (save-excursion
1980 (cond ((= size 0)) ; do nothing for an empty result
1981 ((< size org-babel-min-lines-for-block-output)
1982 (goto-char beg)
1983 (dotimes (n size)
1984 (beginning-of-line 1) (insert ": ") (forward-line 1)))
1986 (goto-char beg)
1987 (insert (if results-switches
1988 (format "#+begin_example%s\n" results-switches)
1989 "#+begin_example\n"))
1990 (if (markerp end) (goto-char end) (forward-char (- end beg)))
1991 (insert "#+end_example\n"))))))))
1993 (defun org-babel-update-block-body (new-body)
1994 "Update the body of the current code block to NEW-BODY."
1995 (if (not (org-babel-where-is-src-block-head))
1996 (error "not in source block")
1997 (save-match-data
1998 (replace-match (concat (org-babel-trim new-body) "\n") nil t nil 5))
1999 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
2001 (defun org-babel-merge-params (&rest plists)
2002 "Combine all parameter association lists in PLISTS.
2003 Later elements of PLISTS override the values of previous elements.
2004 This takes into account some special considerations for certain
2005 parameters when merging lists."
2006 (let ((results-exclusive-groups
2007 (mapcar (lambda (group) (mapcar #'symbol-name group))
2008 (cdr (assoc 'results org-babel-common-header-args-w-values))))
2009 (exports-exclusive-groups
2010 (mapcar (lambda (group) (mapcar #'symbol-name group))
2011 (cdr (assoc 'exports org-babel-common-header-args-w-values))))
2012 (variable-index 0)
2013 params results exports tangle noweb cache vars shebang comments padline)
2014 (flet ((e-merge (exclusive-groups &rest result-params)
2015 ;; maintain exclusivity of mutually exclusive parameters
2016 (let (output)
2017 (mapc (lambda (new-params)
2018 (mapc (lambda (new-param)
2019 (mapc (lambda (exclusive-group)
2020 (when (member new-param exclusive-group)
2021 (mapcar (lambda (excluded-param)
2022 (setq output
2023 (delete
2024 excluded-param
2025 output)))
2026 exclusive-group)))
2027 exclusive-groups)
2028 (setq output (org-uniquify
2029 (cons new-param output))))
2030 new-params))
2031 result-params)
2032 output)))
2033 (mapc
2034 (lambda (plist)
2035 (mapc
2036 (lambda (pair)
2037 (case (car pair)
2038 (:var
2039 (let ((name (if (listp (cdr pair))
2040 (cadr pair)
2041 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
2042 (cdr pair))
2043 (intern (match-string 1 (cdr pair)))))))
2044 (if name
2045 (setq vars
2046 (append
2047 (if (member name (mapcar #'car vars))
2048 (delq nil
2049 (mapcar
2050 (lambda (p)
2051 (unless (equal (car p) name) p))
2052 vars))
2053 vars)
2054 (list (cons name pair))))
2055 ;; if no name is given and we already have named variables
2056 ;; then assign to named variables in order
2057 (if (and vars (nth variable-index vars))
2058 (prog1 (setf (cddr (nth variable-index vars))
2059 (concat (symbol-name
2060 (car (nth variable-index vars)))
2061 "=" (cdr pair)))
2062 (incf variable-index))
2063 (error "variable \"%s\" must be assigned a default value"
2064 (cdr pair))))))
2065 (:results
2066 (setq results (e-merge results-exclusive-groups
2067 results
2068 (split-string
2069 (let ((r (cdr pair)))
2070 (if (stringp r) r (eval r)))))))
2071 (:file
2072 (when (cdr pair)
2073 (setq results (e-merge results-exclusive-groups
2074 results '("file")))
2075 (unless (or (member "both" exports)
2076 (member "none" exports)
2077 (member "code" exports))
2078 (setq exports (e-merge exports-exclusive-groups
2079 exports '("results"))))
2080 (setq params (cons pair (assq-delete-all (car pair) params)))))
2081 (:exports
2082 (setq exports (e-merge exports-exclusive-groups
2083 exports (split-string (cdr pair)))))
2084 (:tangle ;; take the latest -- always overwrite
2085 (setq tangle (or (list (cdr pair)) tangle)))
2086 (:noweb
2087 (setq noweb (e-merge '(("yes" "no" "tangle" "no-export")) noweb
2088 (split-string (or (cdr pair) "")))))
2089 (:cache
2090 (setq cache (e-merge '(("yes" "no")) cache
2091 (split-string (or (cdr pair) "")))))
2092 (:padline
2093 (setq padline (e-merge '(("yes" "no")) padline
2094 (split-string (or (cdr pair) "")))))
2095 (:shebang ;; take the latest -- always overwrite
2096 (setq shebang (or (list (cdr pair)) shebang)))
2097 (:comments
2098 (setq comments (e-merge '(("yes" "no")) comments
2099 (split-string (or (cdr pair) "")))))
2100 (t ;; replace: this covers e.g. :session
2101 (setq params (cons pair (assq-delete-all (car pair) params))))))
2102 plist))
2103 plists))
2104 (setq vars (reverse vars))
2105 (while vars (setq params (cons (cons :var (cddr (pop vars))) params)))
2106 (mapc
2107 (lambda (hd)
2108 (let ((key (intern (concat ":" (symbol-name hd))))
2109 (val (eval hd)))
2110 (setf params (cons (cons key (mapconcat 'identity val " ")) params))))
2111 '(results exports tangle noweb padline cache shebang comments))
2112 params))
2114 (defvar *org-babel-use-quick-and-dirty-noweb-expansion* nil
2115 "Set to true to use regular expressions to expand noweb references.
2116 This results in much faster noweb reference expansion but does
2117 not properly allow code blocks to inherit the \":noweb-ref\"
2118 header argument from buffer or subtree wide properties.")
2120 (defun org-babel-noweb-p (params context)
2121 "Check if PARAMS require expansion in CONTEXT.
2122 CONTEXT may be one of :tangle, :export or :eval."
2123 (flet ((intersect (as bs)
2124 (when as
2125 (if (member (car as) bs)
2126 (car as)
2127 (intersect (cdr as) bs)))))
2128 (intersect (case context
2129 (:tangle '("yes" "tangle" "no-export"))
2130 (:eval '("yes" "no-export"))
2131 (:export '("yes")))
2132 (split-string (or (cdr (assoc :noweb params)) "")))))
2134 (defun org-babel-expand-noweb-references (&optional info parent-buffer)
2135 "Expand Noweb references in the body of the current source code block.
2137 For example the following reference would be replaced with the
2138 body of the source-code block named 'example-block'.
2140 <<example-block>>
2142 Note that any text preceding the <<foo>> construct on a line will
2143 be interposed between the lines of the replacement text. So for
2144 example if <<foo>> is placed behind a comment, then the entire
2145 replacement text will also be commented.
2147 This function must be called from inside of the buffer containing
2148 the source-code block which holds BODY.
2150 In addition the following syntax can be used to insert the
2151 results of evaluating the source-code block named 'example-block'.
2153 <<example-block()>>
2155 Any optional arguments can be passed to example-block by placing
2156 the arguments inside the parenthesis following the convention
2157 defined by `org-babel-lob'. For example
2159 <<example-block(a=9)>>
2161 would set the value of argument \"a\" equal to \"9\". Note that
2162 these arguments are not evaluated in the current source-code
2163 block but are passed literally to the \"example-block\"."
2164 (let* ((parent-buffer (or parent-buffer (current-buffer)))
2165 (info (or info (org-babel-get-src-block-info)))
2166 (lang (nth 0 info))
2167 (body (nth 1 info))
2168 (comment (string= "noweb" (cdr (assoc :comments (nth 2 info)))))
2169 (rx-prefix (concat "\\(" org-babel-src-name-regexp "\\|"
2170 ":noweb-ref[ \t]+" "\\)"))
2171 (new-body "") index source-name evaluate prefix blocks-in-buffer)
2172 (flet ((nb-add (text) (setq new-body (concat new-body text)))
2173 (c-wrap (text)
2174 (with-temp-buffer
2175 (funcall (intern (concat lang "-mode")))
2176 (comment-region (point) (progn (insert text) (point)))
2177 (org-babel-trim (buffer-string)))))
2178 (with-temp-buffer
2179 (insert body) (goto-char (point-min))
2180 (setq index (point))
2181 (while (and (re-search-forward (org-babel-noweb-wrap
2182 "\\([^ \t].+?[^ \t]\\|[^ \t]\\)")
2183 nil t))
2184 (save-match-data (setf source-name (match-string 1)))
2185 (save-match-data (setq evaluate (string-match "\(.*\)" source-name)))
2186 (save-match-data
2187 (setq prefix
2188 (buffer-substring (match-beginning 0)
2189 (save-excursion
2190 (beginning-of-line 1) (point)))))
2191 ;; add interval to new-body (removing noweb reference)
2192 (goto-char (match-beginning 0))
2193 (nb-add (buffer-substring index (point)))
2194 (goto-char (match-end 0))
2195 (setq index (point))
2196 (nb-add
2197 (with-current-buffer parent-buffer
2198 (mapconcat ;; interpose PREFIX between every line
2199 #'identity
2200 (split-string
2201 (if evaluate
2202 (let ((raw (org-babel-ref-resolve source-name)))
2203 (if (stringp raw) raw (format "%S" raw)))
2205 ;; retrieve from the library of babel
2206 (nth 2 (assoc (intern source-name)
2207 org-babel-library-of-babel))
2208 ;; return the contents of headlines literally
2209 (save-excursion
2210 (when (org-babel-ref-goto-headline-id source-name)
2211 (org-babel-ref-headline-body)))
2212 ;; find the expansion of reference in this buffer
2213 (let ((rx (concat rx-prefix source-name))
2214 expansion)
2215 (save-excursion
2216 (goto-char (point-min))
2217 (if *org-babel-use-quick-and-dirty-noweb-expansion*
2218 (while (re-search-forward rx nil t)
2219 (let* ((i (org-babel-get-src-block-info 'light))
2220 (body (org-babel-expand-noweb-references i))
2221 (sep (or (cdr (assoc :noweb-sep (nth 2 i)))
2222 "\n"))
2223 (full (if comment
2224 ((lambda (cs)
2225 (concat (c-wrap (car cs)) "\n"
2226 body "\n"
2227 (c-wrap (cadr cs))))
2228 (org-babel-tangle-comment-links i))
2229 body)))
2230 (setq expansion (cons sep (cons full expansion)))))
2231 (org-babel-map-src-blocks nil
2232 (let ((i (org-babel-get-src-block-info 'light)))
2233 (when (equal (or (cdr (assoc :noweb-ref (nth 2 i)))
2234 (nth 4 i))
2235 source-name)
2236 (let* ((body (org-babel-expand-noweb-references i))
2237 (sep (or (cdr (assoc :noweb-sep (nth 2 i)))
2238 "\n"))
2239 (full (if comment
2240 ((lambda (cs)
2241 (concat (c-wrap (car cs)) "\n"
2242 body "\n"
2243 (c-wrap (cadr cs))))
2244 (org-babel-tangle-comment-links i))
2245 body)))
2246 (setq expansion
2247 (cons sep (cons full expansion)))))))))
2248 (and expansion
2249 (mapconcat #'identity (nreverse (cdr expansion)) "")))
2250 ;; possibly raise an error if named block doesn't exist
2251 (if (member lang org-babel-noweb-error-langs)
2252 (error "%s" (concat
2253 (org-babel-noweb-wrap source-name)
2254 "could not be resolved (see "
2255 "`org-babel-noweb-error-langs')"))
2256 "")))
2257 "[\n\r]") (concat "\n" prefix)))))
2258 (nb-add (buffer-substring index (point-max)))))
2259 new-body))
2261 (defun org-babel-clean-text-properties (text)
2262 "Strip all properties from text return."
2263 (when text
2264 (set-text-properties 0 (length text) nil text) text))
2266 (defun org-babel-strip-protective-commas (body)
2267 "Strip protective commas from bodies of source blocks."
2268 (when body
2269 (replace-regexp-in-string "^,#" "#" body)))
2271 (defun org-babel-script-escape (str &optional force)
2272 "Safely convert tables into elisp lists."
2273 (let (in-single in-double out)
2274 ((lambda (escaped) (condition-case nil (org-babel-read escaped) (error escaped)))
2275 (if (or force
2276 (and (stringp str)
2277 (> (length str) 2)
2278 (or (and (string-equal "[" (substring str 0 1))
2279 (string-equal "]" (substring str -1)))
2280 (and (string-equal "{" (substring str 0 1))
2281 (string-equal "}" (substring str -1)))
2282 (and (string-equal "(" (substring str 0 1))
2283 (string-equal ")" (substring str -1))))))
2284 (org-babel-read
2285 (concat
2287 (progn
2288 (mapc
2289 (lambda (ch)
2290 (setq
2292 (case ch
2293 (91 (if (or in-double in-single) ; [
2294 (cons 91 out)
2295 (cons 40 out)))
2296 (93 (if (or in-double in-single) ; ]
2297 (cons 93 out)
2298 (cons 41 out)))
2299 (123 (if (or in-double in-single) ; {
2300 (cons 123 out)
2301 (cons 40 out)))
2302 (125 (if (or in-double in-single) ; }
2303 (cons 125 out)
2304 (cons 41 out)))
2305 (44 (if (or in-double in-single) ; ,
2306 (cons 44 out) (cons 32 out)))
2307 (39 (if in-double ; '
2308 (cons 39 out)
2309 (setq in-single (not in-single)) (cons 34 out)))
2310 (34 (if in-single ; "
2311 (append (list 34 32) out)
2312 (setq in-double (not in-double)) (cons 34 out)))
2313 (t (cons ch out)))))
2314 (string-to-list str))
2315 (apply #'string (reverse out)))))
2316 str))))
2318 (defun org-babel-read (cell &optional inhibit-lisp-eval)
2319 "Convert the string value of CELL to a number if appropriate.
2320 Otherwise if cell looks like lisp (meaning it starts with a
2321 \"(\", \"'\", \"`\" or a \"[\") then read it as lisp, otherwise
2322 return it unmodified as a string. Optional argument NO-LISP-EVAL
2323 inhibits lisp evaluation for situations in which is it not
2324 appropriate."
2325 (if (and (stringp cell) (not (equal cell "")))
2326 (or (org-babel-number-p cell)
2327 (if (and (not inhibit-lisp-eval)
2328 (member (substring cell 0 1) '("(" "'" "`" "[")))
2329 (eval (read cell))
2330 (if (string= (substring cell 0 1) "\"")
2331 (read cell)
2332 (progn (set-text-properties 0 (length cell) nil cell) cell))))
2333 cell))
2335 (defun org-babel-number-p (string)
2336 "If STRING represents a number return its value."
2337 (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string)
2338 (= (length (substring string (match-beginning 0)
2339 (match-end 0)))
2340 (length string)))
2341 (string-to-number string)))
2343 (defun org-babel-import-elisp-from-file (file-name &optional separator)
2344 "Read the results located at FILE-NAME into an elisp table.
2345 If the table is trivial, then return it as a scalar."
2346 (let (result)
2347 (save-window-excursion
2348 (with-temp-buffer
2349 (condition-case nil
2350 (progn
2351 (org-table-import file-name separator)
2352 (delete-file file-name)
2353 (setq result (mapcar (lambda (row)
2354 (mapcar #'org-babel-string-read row))
2355 (org-table-to-lisp))))
2356 (error nil)))
2357 (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
2358 (if (consp (car result))
2359 (if (null (cdr (car result)))
2360 (caar result)
2361 result)
2362 (car result))
2363 result))))
2365 (defun org-babel-string-read (cell)
2366 "Strip nested \"s from around strings."
2367 (org-babel-read (or (and (stringp cell)
2368 (string-match "\\\"\\(.+\\)\\\"" cell)
2369 (match-string 1 cell))
2370 cell)))
2372 (defun org-babel-reverse-string (string)
2373 "Return the reverse of STRING."
2374 (apply 'string (reverse (string-to-list string))))
2376 (defun org-babel-chomp (string &optional regexp)
2377 "Strip trailing spaces and carriage returns from STRING.
2378 Default regexp used is \"[ \f\t\n\r\v]\" but can be
2379 overwritten by specifying a regexp as a second argument."
2380 (let ((regexp (or regexp "[ \f\t\n\r\v]")))
2381 (while (and (> (length string) 0)
2382 (string-match regexp (substring string -1)))
2383 (setq string (substring string 0 -1)))
2384 string))
2386 (defun org-babel-trim (string &optional regexp)
2387 "Strip leading and trailing spaces and carriage returns from STRING.
2388 Like `org-babel-chomp' only it runs on both the front and back
2389 of the string."
2390 (org-babel-chomp (org-babel-reverse-string
2391 (org-babel-chomp (org-babel-reverse-string string) regexp))
2392 regexp))
2394 (defvar org-babel-org-babel-call-process-region-original nil)
2395 (defun org-babel-tramp-handle-call-process-region
2396 (start end program &optional delete buffer display &rest args)
2397 "Use tramp to handle call-process-region.
2398 Fixes a bug in `tramp-handle-call-process-region'."
2399 (if (and (featurep 'tramp) (file-remote-p default-directory))
2400 (let ((tmpfile (tramp-compat-make-temp-file "")))
2401 (write-region start end tmpfile)
2402 (when delete (delete-region start end))
2403 (unwind-protect
2404 ;; (apply 'call-process program tmpfile buffer display args)
2405 ;; bug in tramp
2406 (apply 'process-file program tmpfile buffer display args)
2407 (delete-file tmpfile)))
2408 ;; org-babel-call-process-region-original is the original emacs
2409 ;; definition. It is in scope from the let binding in
2410 ;; org-babel-execute-src-block
2411 (apply org-babel-call-process-region-original
2412 start end program delete buffer display args)))
2414 (defun org-babel-local-file-name (file)
2415 "Return the local name component of FILE."
2416 (if (file-remote-p file)
2417 (let (localname)
2418 (with-parsed-tramp-file-name file nil
2419 localname))
2420 file))
2422 (defun org-babel-process-file-name (name &optional no-quote-p)
2423 "Prepare NAME to be used in an external process.
2424 If NAME specifies a remote location, the remote portion of the
2425 name is removed, since in that case the process will be executing
2426 remotely. The file name is then processed by
2427 `expand-file-name'. Unless second argument NO-QUOTE-P is non-nil,
2428 the file name is additionally processed by
2429 `shell-quote-argument'"
2430 ((lambda (f) (if no-quote-p f (shell-quote-argument f)))
2431 (expand-file-name (org-babel-local-file-name name))))
2433 (defvar org-babel-temporary-directory)
2434 (unless (or noninteractive (boundp 'org-babel-temporary-directory))
2435 (defvar org-babel-temporary-directory
2436 (or (and (boundp 'org-babel-temporary-directory)
2437 (file-exists-p org-babel-temporary-directory)
2438 org-babel-temporary-directory)
2439 (make-temp-file "babel-" t))
2440 "Directory to hold temporary files created to execute code blocks.
2441 Used by `org-babel-temp-file'. This directory will be removed on
2442 Emacs shutdown."))
2444 (defun org-babel-temp-file (prefix &optional suffix)
2445 "Create a temporary file in the `org-babel-temporary-directory'.
2446 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2447 value of `temporary-file-directory' temporarily set to the value
2448 of `org-babel-temporary-directory'."
2449 (if (file-remote-p default-directory)
2450 (make-temp-file
2451 (concat (file-remote-p default-directory)
2452 (expand-file-name
2453 prefix temporary-file-directory)
2454 nil suffix))
2455 (let ((temporary-file-directory
2456 (or (and (boundp 'org-babel-temporary-directory)
2457 (file-exists-p org-babel-temporary-directory)
2458 org-babel-temporary-directory)
2459 temporary-file-directory)))
2460 (make-temp-file prefix nil suffix))))
2462 (defun org-babel-remove-temporary-directory ()
2463 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2464 (when (and (boundp 'org-babel-temporary-directory)
2465 (file-exists-p org-babel-temporary-directory))
2466 ;; taken from `delete-directory' in files.el
2467 (condition-case nil
2468 (progn
2469 (mapc (lambda (file)
2470 ;; This test is equivalent to
2471 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2472 ;; but more efficient
2473 (if (eq t (car (file-attributes file)))
2474 (delete-directory file)
2475 (delete-file file)))
2476 ;; We do not want to delete "." and "..".
2477 (directory-files org-babel-temporary-directory 'full
2478 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2479 (delete-directory org-babel-temporary-directory))
2480 (error
2481 (message "Failed to remove temporary Org-babel directory %s"
2482 (if (boundp 'org-babel-temporary-directory)
2483 org-babel-temporary-directory
2484 "[directory not defined]"))))))
2486 (add-hook 'kill-emacs-hook 'org-babel-remove-temporary-directory)
2488 (provide 'ob)
2492 ;;; ob.el ends here