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