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