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