org.el: Fix bug when matching the face property before following a link.
[org-mode/org-kjn.git] / lisp / ob.el
blob4438ee85f81fc7b254b8973891d71c954fed5c34
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 (defvar org-babel-inline-lob-one-liner-regexp)
185 (defun org-babel-get-lob-one-liner-matches()
186 "Set match data if on line of an lob one liner.
187 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 (org-babel-parse-multiple-vars
1051 (delq nil
1052 (mapcar
1053 (lambda (header-arg)
1054 (and (setq val (org-entry-get (point) header-arg t))
1055 (cons (intern (concat ":" header-arg))
1056 (org-babel-read val))))
1057 (mapcar
1058 'symbol-name
1059 (append
1060 org-babel-header-arg-names
1061 (progn
1062 (setq sym (intern (concat "org-babel-header-arg-names:"
1063 lang)))
1064 (and (boundp sym) (eval sym)))))))))))
1066 (defvar org-src-preserve-indentation)
1067 (defun org-babel-parse-src-block-match ()
1068 "Parse the results from a match of the `org-babel-src-block-regexp'."
1069 (let* ((block-indentation (length (match-string 1)))
1070 (lang (org-babel-clean-text-properties (match-string 2)))
1071 (lang-headers (intern (concat "org-babel-default-header-args:" lang)))
1072 (switches (match-string 3))
1073 (body (org-babel-clean-text-properties
1074 (let* ((body (match-string 5))
1075 (sub-length (- (length body) 1)))
1076 (if (and (> sub-length 0)
1077 (string= "\n" (substring body sub-length)))
1078 (substring body 0 sub-length)
1079 (or body "")))))
1080 (preserve-indentation (or org-src-preserve-indentation
1081 (string-match "-i\\>" switches))))
1082 (list lang
1083 ;; get block body less properties, protective commas, and indentation
1084 (with-temp-buffer
1085 (save-match-data
1086 (insert (org-babel-strip-protective-commas body))
1087 (unless preserve-indentation (org-do-remove-indentation))
1088 (buffer-string)))
1089 (org-babel-merge-params
1090 org-babel-default-header-args
1091 (org-babel-params-from-properties lang)
1092 (if (boundp lang-headers) (eval lang-headers) nil)
1093 (org-babel-parse-header-arguments
1094 (org-babel-clean-text-properties (or (match-string 4) ""))))
1095 switches
1096 block-indentation)))
1098 (defun org-babel-parse-inline-src-block-match ()
1099 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
1100 (let* ((lang (org-babel-clean-text-properties (match-string 2)))
1101 (lang-headers (intern (concat "org-babel-default-header-args:" lang))))
1102 (list lang
1103 (org-babel-strip-protective-commas
1104 (org-babel-clean-text-properties (match-string 5)))
1105 (org-babel-merge-params
1106 org-babel-default-inline-header-args
1107 (org-babel-params-from-properties lang)
1108 (if (boundp lang-headers) (eval lang-headers) nil)
1109 (org-babel-parse-header-arguments
1110 (org-babel-clean-text-properties (or (match-string 4) "")))))))
1112 (defun org-babel-balanced-split (string alts)
1113 "Split STRING on instances of ALTS.
1114 ALTS is a cons of two character options where each option may be
1115 either the numeric code of a single character or a list of
1116 character alternatives. For example to split on balanced
1117 instances of \"[ \t]:\" set ALTS to '((32 9) . 58)."
1118 (flet ((matches (ch spec) (or (and (numberp spec) (= spec ch))
1119 (member ch spec)))
1120 (matched (ch last)
1121 (and (matches ch (cdr alts))
1122 (matches last (car alts)))))
1123 (let ((balance 0) (partial nil) (lst nil) (last 0))
1124 (mapc (lambda (ch) ; split on [] or () balanced instances of [ \t]:
1125 (setq balance (+ balance
1126 (cond ((or (equal 91 ch) (equal 40 ch)) 1)
1127 ((or (equal 93 ch) (equal 41 ch)) -1)
1128 (t 0))))
1129 (setq partial (cons ch partial))
1130 (when (and (= balance 0) (matched ch last))
1131 (setq lst (cons (apply #'string (nreverse (cddr partial)))
1132 lst))
1133 (setq partial nil))
1134 (setq last ch))
1135 (string-to-list string))
1136 (nreverse (cons (apply #'string (nreverse partial)) lst)))))
1138 (defun org-babel-parse-header-arguments (arg-string)
1139 "Parse a string of header arguments returning an alist."
1140 (when (> (length arg-string) 0)
1141 (org-babel-parse-multiple-vars
1142 (delq nil
1143 (mapcar
1144 (lambda (arg)
1145 (if (string-match
1146 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1147 arg)
1148 (cons (intern (match-string 1 arg))
1149 (org-babel-read (org-babel-chomp (match-string 2 arg))))
1150 (cons (intern (org-babel-chomp arg)) nil)))
1151 ((lambda (raw)
1152 (cons (car raw) (mapcar (lambda (r) (concat ":" r)) (cdr raw))))
1153 (org-babel-balanced-split arg-string '((32 9) . 58))))))))
1155 (defun org-babel-parse-multiple-vars (header-arguments)
1156 "Expand multiple variable assignments behind a single :var keyword.
1158 This allows expression of multiple variables with one :var as
1159 shown below.
1161 #+PROPERTY: var foo=1, bar=2"
1162 (let (results)
1163 (mapc (lambda (pair)
1164 (if (eq (car pair) :var)
1165 (mapcar (lambda (spec) (push (cons :var spec) results))
1166 (org-babel-balanced-split (cdr pair) '(44 . (32 9))))
1167 (push pair results)))
1168 header-arguments)
1169 (nreverse results)))
1171 (defun org-babel-process-params (params)
1172 "Expand variables in PARAMS and add summary parameters."
1173 (let* ((vars-and-names (org-babel-disassemble-tables
1174 (mapcar (lambda (el)
1175 (if (consp (cdr el))
1176 (cdr el) (org-babel-ref-parse (cdr el))))
1177 (org-babel-get-header params :var))
1178 (cdr (assoc :hlines params))
1179 (cdr (assoc :colnames params))
1180 (cdr (assoc :rownames params))))
1181 (raw-result (or (cdr (assoc :results params)) ""))
1182 (result-params (append
1183 (split-string (if (stringp raw-result)
1184 raw-result
1185 (eval raw-result)))
1186 (cdr (assoc :result-params params)))))
1187 (append
1188 (mapcar (lambda (var) (cons :var var)) (car vars-and-names))
1189 (list
1190 (cons :colname-names (or (cdr (assoc :colname-names params))
1191 (cadr vars-and-names)))
1192 (cons :rowname-names (or (cdr (assoc :rowname-names params))
1193 (caddr vars-and-names)))
1194 (cons :result-params result-params)
1195 (cons :result-type (cond ((member "output" result-params) 'output)
1196 ((member "value" result-params) 'value)
1197 (t 'value))))
1198 (org-babel-get-header params :var 'other))))
1200 ;; row and column names
1201 (defun org-babel-del-hlines (table)
1202 "Remove all 'hlines from TABLE."
1203 (remove 'hline table))
1205 (defun org-babel-get-colnames (table)
1206 "Return the column names of TABLE.
1207 Return a cons cell, the `car' of which contains the TABLE less
1208 colnames, and the `cdr' of which contains a list of the column
1209 names."
1210 (if (equal 'hline (nth 1 table))
1211 (cons (cddr table) (car table))
1212 (cons (cdr table) (car table))))
1214 (defun org-babel-get-rownames (table)
1215 "Return the row names of TABLE.
1216 Return a cons cell, the `car' of which contains the TABLE less
1217 colnames, and the `cdr' of which contains a list of the column
1218 names. Note: this function removes any hlines in TABLE."
1219 (flet ((trans (table) (apply #'mapcar* #'list table)))
1220 (let* ((width (apply 'max
1221 (mapcar (lambda (el) (if (listp el) (length el) 0)) table)))
1222 (table (trans (mapcar (lambda (row)
1223 (if (not (equal row 'hline))
1225 (setq row '())
1226 (dotimes (n width)
1227 (setq row (cons 'hline row)))
1228 row))
1229 table))))
1230 (cons (mapcar (lambda (row) (if (equal (car row) 'hline) 'hline row))
1231 (trans (cdr table)))
1232 (remove 'hline (car table))))))
1234 (defun org-babel-put-colnames (table colnames)
1235 "Add COLNAMES to TABLE if they exist."
1236 (if colnames (apply 'list colnames 'hline table) table))
1238 (defun org-babel-put-rownames (table rownames)
1239 "Add ROWNAMES to TABLE if they exist."
1240 (if rownames
1241 (mapcar (lambda (row)
1242 (if (listp row)
1243 (cons (or (pop rownames) "") row)
1244 row)) table)
1245 table))
1247 (defun org-babel-pick-name (names selector)
1248 "Select one out of an alist of row or column names.
1249 SELECTOR can be either a list of names in which case those names
1250 will be returned directly, or an index into the list NAMES in
1251 which case the indexed names will be return."
1252 (if (listp selector)
1253 selector
1254 (when names
1255 (if (and selector (symbolp selector) (not (equal t selector)))
1256 (cdr (assoc selector names))
1257 (if (integerp selector)
1258 (nth (- selector 1) names)
1259 (cdr (car (last names))))))))
1261 (defun org-babel-disassemble-tables (vars hlines colnames rownames)
1262 "Parse tables for further processing.
1263 Process the variables in VARS according to the HLINES,
1264 ROWNAMES and COLNAMES header arguments. Return a list consisting
1265 of the vars, cnames and rnames."
1266 (let (cnames rnames)
1267 (list
1268 (mapcar
1269 (lambda (var)
1270 (when (listp (cdr var))
1271 (when (and (not (equal colnames "no"))
1272 (or colnames (and (equal (nth 1 (cdr var)) 'hline)
1273 (not (member 'hline (cddr (cdr var)))))))
1274 (let ((both (org-babel-get-colnames (cdr var))))
1275 (setq cnames (cons (cons (car var) (cdr both))
1276 cnames))
1277 (setq var (cons (car var) (car both)))))
1278 (when (and rownames (not (equal rownames "no")))
1279 (let ((both (org-babel-get-rownames (cdr var))))
1280 (setq rnames (cons (cons (car var) (cdr both))
1281 rnames))
1282 (setq var (cons (car var) (car both)))))
1283 (when (and hlines (not (equal hlines "yes")))
1284 (setq var (cons (car var) (org-babel-del-hlines (cdr var))))))
1285 var)
1286 vars)
1287 (reverse cnames) (reverse rnames))))
1289 (defun org-babel-reassemble-table (table colnames rownames)
1290 "Add column and row names to a table.
1291 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1292 to the table for reinsertion to org-mode."
1293 (if (listp table)
1294 ((lambda (table)
1295 (if (and colnames (listp (car table)) (= (length (car table))
1296 (length colnames)))
1297 (org-babel-put-colnames table colnames) table))
1298 (if (and rownames (= (length table) (length rownames)))
1299 (org-babel-put-rownames table rownames) table))
1300 table))
1302 (defun org-babel-where-is-src-block-head ()
1303 "Find where the current source block begins.
1304 Return the point at the beginning of the current source
1305 block. Specifically at the beginning of the #+BEGIN_SRC line.
1306 If the point is not on a source block then return nil."
1307 (let ((initial (point)) top bottom)
1309 (save-excursion ;; on a source name line or a #+header line
1310 (beginning-of-line 1)
1311 (and (or (looking-at org-babel-src-name-regexp)
1312 (looking-at org-babel-multi-line-header-regexp))
1313 (progn
1314 (while (and (forward-line 1)
1315 (looking-at org-babel-multi-line-header-regexp)))
1316 (looking-at org-babel-src-block-regexp))
1317 (point)))
1318 (save-excursion ;; on a #+begin_src line
1319 (beginning-of-line 1)
1320 (and (looking-at org-babel-src-block-regexp)
1321 (point)))
1322 (save-excursion ;; inside a src block
1323 (and
1324 (re-search-backward "^[ \t]*#\\+begin_src" nil t) (setq top (point))
1325 (re-search-forward "^[ \t]*#\\+end_src" nil t) (setq bottom (point))
1326 (< top initial) (< initial bottom)
1327 (progn (goto-char top) (beginning-of-line 1)
1328 (looking-at org-babel-src-block-regexp))
1329 (point))))))
1331 ;;;###autoload
1332 (defun org-babel-goto-src-block-head ()
1333 "Go to the beginning of the current code block."
1334 (interactive)
1335 ((lambda (head)
1336 (if head (goto-char head) (error "not currently in a code block")))
1337 (org-babel-where-is-src-block-head)))
1339 ;;;###autoload
1340 (defun org-babel-goto-named-src-block (name)
1341 "Go to a named source-code block."
1342 (interactive
1343 (let ((completion-ignore-case t))
1344 (list (org-icompleting-read "source-block name: "
1345 (org-babel-src-block-names) nil t))))
1346 (let ((point (org-babel-find-named-block name)))
1347 (if point
1348 ;; taken from `org-open-at-point'
1349 (progn (goto-char point) (org-show-context))
1350 (message "source-code block '%s' not found in this buffer" name))))
1352 (defun org-babel-find-named-block (name)
1353 "Find a named source-code block.
1354 Return the location of the source block identified by source
1355 NAME, or nil if no such block exists. Set match data according to
1356 org-babel-named-src-block-regexp."
1357 (save-excursion
1358 (let ((case-fold-search t)
1359 (regexp (org-babel-named-src-block-regexp-for-name name)) msg)
1360 (goto-char (point-min))
1361 (when (or (re-search-forward regexp nil t)
1362 (re-search-backward regexp nil t))
1363 (match-beginning 0)))))
1365 (defun org-babel-src-block-names (&optional file)
1366 "Returns the names of source blocks in FILE or the current buffer."
1367 (save-excursion
1368 (when file (find-file file)) (goto-char (point-min))
1369 (let (names)
1370 (while (re-search-forward org-babel-src-name-w-name-regexp nil t)
1371 (setq names (cons (match-string 4) names)))
1372 names)))
1374 ;;;###autoload
1375 (defun org-babel-goto-named-result (name)
1376 "Go to a named result."
1377 (interactive
1378 (let ((completion-ignore-case t))
1379 (list (org-icompleting-read "source-block name: "
1380 (org-babel-result-names) nil t))))
1381 (let ((point (org-babel-find-named-result name)))
1382 (if point
1383 ;; taken from `org-open-at-point'
1384 (progn (goto-char point) (org-show-context))
1385 (message "result '%s' not found in this buffer" name))))
1387 (defun org-babel-find-named-result (name)
1388 "Find a named result.
1389 Return the location of the result named NAME in the current
1390 buffer or nil if no such result exists."
1391 (save-excursion
1392 (goto-char (point-min))
1393 (when (re-search-forward
1394 (concat org-babel-result-regexp
1395 "[ \t]" (regexp-quote name) "[ \t\n\f\v\r]") nil t)
1396 (beginning-of-line 0) (point))))
1398 (defun org-babel-result-names (&optional file)
1399 "Returns the names of results in FILE or the current buffer."
1400 (save-excursion
1401 (when file (find-file file)) (goto-char (point-min))
1402 (let (names)
1403 (while (re-search-forward org-babel-result-w-name-regexp nil t)
1404 (setq names (cons (match-string 4) names)))
1405 names)))
1407 ;;;###autoload
1408 (defun org-babel-next-src-block (&optional arg)
1409 "Jump to the next source block.
1410 With optional prefix argument ARG, jump forward ARG many source blocks."
1411 (interactive "P")
1412 (when (looking-at org-babel-src-block-regexp) (forward-char 1))
1413 (condition-case nil
1414 (re-search-forward org-babel-src-block-regexp nil nil (or arg 1))
1415 (error (error "No further code blocks")))
1416 (goto-char (match-beginning 0)) (org-show-context))
1418 ;;;###autoload
1419 (defun org-babel-previous-src-block (&optional arg)
1420 "Jump to the previous source block.
1421 With optional prefix argument ARG, jump backward ARG many source blocks."
1422 (interactive "P")
1423 (condition-case nil
1424 (re-search-backward org-babel-src-block-regexp nil nil (or arg 1))
1425 (error (error "No previous code blocks")))
1426 (goto-char (match-beginning 0)) (org-show-context))
1428 (defvar org-babel-load-languages)
1430 ;;;###autoload
1431 (defun org-babel-mark-block ()
1432 "Mark current src block"
1433 (interactive)
1434 ((lambda (head)
1435 (when head
1436 (save-excursion
1437 (goto-char head)
1438 (looking-at org-babel-src-block-regexp))
1439 (push-mark (match-end 5) nil t)
1440 (goto-char (match-beginning 5))))
1441 (org-babel-where-is-src-block-head)))
1443 (defun org-babel-demarcate-block (&optional arg)
1444 "Wrap or split the code in the region or on the point.
1445 When called from inside of a code block the current block is
1446 split. When called from outside of a code block a new code block
1447 is created. In both cases if the region is demarcated and if the
1448 region is not active then the point is demarcated."
1449 (interactive "P")
1450 (let ((info (org-babel-get-src-block-info 'light))
1451 (headers (progn (org-babel-where-is-src-block-head)
1452 (match-string 4)))
1453 (stars (concat (make-string (or (org-current-level) 1) ?*) " ")))
1454 (if info
1455 (mapc
1456 (lambda (place)
1457 (save-excursion
1458 (goto-char place)
1459 (let ((lang (nth 0 info))
1460 (indent (make-string (nth 5 info) ? )))
1461 (when (string-match "^[[:space:]]*$"
1462 (buffer-substring (point-at-bol)
1463 (point-at-eol)))
1464 (delete-region (point-at-bol) (point-at-eol)))
1465 (insert (concat
1466 (if (looking-at "^") "" "\n")
1467 indent "#+end_src\n"
1468 (if arg stars indent) "\n"
1469 indent "#+begin_src " lang
1470 (if (> (length headers) 1)
1471 (concat " " headers) headers)
1472 (if (looking-at "[\n\r]")
1474 (concat "\n" (make-string (current-column) ? )))))))
1475 (move-end-of-line 2))
1476 (sort (if (region-active-p) (list (mark) (point)) (list (point))) #'>))
1477 (let ((start (point))
1478 (lang (org-icompleting-read "Lang: "
1479 (mapcar (lambda (el) (symbol-name (car el)))
1480 org-babel-load-languages)))
1481 (body (delete-and-extract-region
1482 (if (region-active-p) (mark) (point)) (point))))
1483 (insert (concat (if (looking-at "^") "" "\n")
1484 (if arg (concat stars "\n") "")
1485 "#+begin_src " lang "\n"
1486 body
1487 (if (or (= (length body) 0)
1488 (string-match "[\r\n]$" body)) "" "\n")
1489 "#+end_src\n"))
1490 (goto-char start) (move-end-of-line 1)))))
1492 (defvar org-babel-lob-one-liner-regexp)
1493 (defun org-babel-where-is-src-block-result (&optional insert info hash indent)
1494 "Find where the current source block results begin.
1495 Return the point at the beginning of the result of the current
1496 source block. Specifically at the beginning of the results line.
1497 If no result exists for this block then create a results line
1498 following the source block."
1499 (save-excursion
1500 (let* ((on-lob-line (save-excursion
1501 (beginning-of-line 1)
1502 (looking-at org-babel-lob-one-liner-regexp)))
1503 (inlinep (when (org-babel-get-inline-src-block-matches)
1504 (match-end 0)))
1505 (name (if on-lob-line
1506 (nth 0 (org-babel-lob-get-info))
1507 (nth 4 (or info (org-babel-get-src-block-info 'light)))))
1508 (head (unless on-lob-line (org-babel-where-is-src-block-head)))
1509 found beg end)
1510 (when head (goto-char head))
1511 (setq
1512 found ;; was there a result (before we potentially insert one)
1514 inlinep
1515 (and
1516 ;; named results:
1517 ;; - return t if it is found, else return nil
1518 ;; - if it does not need to be rebuilt, then don't set end
1519 ;; - if it does need to be rebuilt then do set end
1520 name (setq beg (org-babel-find-named-result name))
1521 (prog1 beg
1522 (when (and hash (not (string= hash (match-string 3))))
1523 (goto-char beg) (setq end beg) ;; beginning of result
1524 (forward-line 1)
1525 (delete-region end (org-babel-result-end)) nil)))
1526 (and
1527 ;; unnamed results:
1528 ;; - return t if it is found, else return nil
1529 ;; - if it is found, and the hash doesn't match, delete and set end
1530 (or on-lob-line (re-search-forward "^[ \t]*#\\+end_src" nil t))
1531 (progn (end-of-line 1)
1532 (if (eobp) (insert "\n") (forward-char 1))
1533 (setq end (point))
1534 (or (and (not name)
1535 (progn ;; unnamed results line already exists
1536 (re-search-forward "[^ \f\t\n\r\v]" nil t)
1537 (beginning-of-line 1)
1538 (looking-at
1539 (concat org-babel-result-regexp "\n")))
1540 (prog1 (point)
1541 ;; must remove and rebuild if hash!=old-hash
1542 (if (and hash (not (string= hash (match-string 3))))
1543 (prog1 nil
1544 (forward-line 1)
1545 (delete-region
1546 end (org-babel-result-end)))
1547 (setq end nil)))))))))
1548 (if (and insert end)
1549 (progn
1550 (goto-char end)
1551 (unless beg
1552 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1553 (insert (concat
1554 (if indent
1555 (mapconcat
1556 (lambda (el) " ")
1557 (org-number-sequence 1 indent) "")
1559 "#+results"
1560 (when hash (concat "["hash"]"))
1562 (when name (concat " " name)) "\n"))
1563 (unless beg (insert "\n") (backward-char))
1564 (beginning-of-line 0)
1565 (if hash (org-babel-hide-hash))
1566 (point))
1567 found))))
1569 (defvar org-block-regexp)
1570 (defun org-babel-read-result ()
1571 "Read the result at `point' into emacs-lisp."
1572 (let ((case-fold-search t) result-string)
1573 (cond
1574 ((org-at-table-p) (org-babel-read-table))
1575 ((org-at-item-p) (org-babel-read-list))
1576 ((looking-at org-bracket-link-regexp) (org-babel-read-link))
1577 ((looking-at org-block-regexp) (org-babel-trim (match-string 4)))
1578 ((looking-at "^[ \t]*: ")
1579 (setq result-string
1580 (org-babel-trim
1581 (mapconcat (lambda (line)
1582 (if (and (> (length line) 1)
1583 (string-match "^[ \t]*: \\(.+\\)" line))
1584 (match-string 1 line)
1585 line))
1586 (split-string
1587 (buffer-substring
1588 (point) (org-babel-result-end)) "[\r\n]+")
1589 "\n")))
1590 (or (org-babel-number-p result-string) result-string))
1591 ((looking-at org-babel-result-regexp)
1592 (save-excursion (forward-line 1) (org-babel-read-result))))))
1594 (defun org-babel-read-table ()
1595 "Read the table at `point' into emacs-lisp."
1596 (mapcar (lambda (row)
1597 (if (and (symbolp row) (equal row 'hline)) row
1598 (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval)) row)))
1599 (org-table-to-lisp)))
1601 (defun org-babel-read-list ()
1602 "Read the list at `point' into emacs-lisp."
1603 (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval))
1604 (mapcar #'cadr (cdr (org-list-parse-list)))))
1606 (defvar org-link-types-re)
1607 (defun org-babel-read-link ()
1608 "Read the link at `point' into emacs-lisp.
1609 If the path of the link is a file path it is expanded using
1610 `expand-file-name'."
1611 (let* ((case-fold-search t)
1612 (raw (and (looking-at org-bracket-link-regexp)
1613 (org-babel-clean-text-properties (match-string 1))))
1614 (type (and (string-match org-link-types-re raw)
1615 (match-string 1 raw))))
1616 (cond
1617 ((not type) (expand-file-name raw))
1618 ((string= type "file")
1619 (and (string-match "file\\(.*\\):\\(.+\\)" raw)
1620 (expand-file-name (match-string 2 raw))))
1621 (t raw))))
1623 (defun org-babel-format-result (result &optional sep)
1624 "Format RESULT for writing to file."
1625 (flet ((echo-res (result)
1626 (if (stringp result) result (format "%S" result))))
1627 (if (listp result)
1628 ;; table result
1629 (orgtbl-to-generic
1630 result
1631 (list
1632 :sep (or sep "\t")
1633 :fmt 'echo-res))
1634 ;; scalar result
1635 (echo-res result))))
1637 (defun org-babel-insert-result
1638 (result &optional result-params info hash indent lang)
1639 "Insert RESULT into the current buffer.
1640 By default RESULT is inserted after the end of the
1641 current source block. With optional argument RESULT-PARAMS
1642 controls insertion of results in the org-mode file.
1643 RESULT-PARAMS can take the following values...
1645 replace - (default option) insert results after the source block
1646 replacing any previously inserted results
1648 silent -- no results are inserted
1650 file ---- the results are interpreted as a file path, and are
1651 inserted into the buffer using the Org-mode file syntax
1653 list ---- the results are interpreted as an Org-mode list.
1655 raw ----- results are added directly to the Org-mode file. This
1656 is a good option if you code block will output org-mode
1657 formatted text.
1659 org ----- similar in effect to raw, only the results are wrapped
1660 in an org code block. Similar to the raw option, on
1661 export the results will be interpreted as org-formatted
1662 text, however by wrapping the results in an org code
1663 block they can be replaced upon re-execution of the
1664 code block.
1666 html ---- results are added inside of a #+BEGIN_HTML block. This
1667 is a good option if you code block will output html
1668 formatted text.
1670 latex --- results are added inside of a #+BEGIN_LATEX block.
1671 This is a good option if you code block will output
1672 latex formatted text.
1674 code ---- the results are extracted in the syntax of the source
1675 code of the language being evaluated and are added
1676 inside of a #+BEGIN_SRC block with the source-code
1677 language set appropriately. Note this relies on the
1678 optional LANG argument."
1679 (if (stringp result)
1680 (progn
1681 (setq result (org-babel-clean-text-properties result))
1682 (when (member "file" result-params)
1683 (setq result (org-babel-result-to-file result))))
1684 (unless (listp result) (setq result (format "%S" result))))
1685 (if (and result-params (member "silent" result-params))
1686 (progn
1687 (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
1688 result)
1689 (save-excursion
1690 (let* ((inlinep
1691 (save-excursion
1692 (when (or (org-babel-get-inline-src-block-matches)
1693 (org-babel-get-lob-one-liner-matches))
1694 (goto-char (match-end 0))
1695 (insert (if (listp result) "\n" " "))
1696 (point))))
1697 (existing-result (unless inlinep
1698 (org-babel-where-is-src-block-result
1699 t info hash indent)))
1700 (results-switches
1701 (cdr (assoc :results_switches (nth 2 info))))
1702 beg end)
1703 (when (and (stringp result) ; ensure results end in a newline
1704 (not inlinep)
1705 (> (length result) 0)
1706 (not (or (string-equal (substring result -1) "\n")
1707 (string-equal (substring result -1) "\r"))))
1708 (setq result (concat result "\n")))
1709 (if (not existing-result)
1710 (setq beg (or inlinep (point)))
1711 (goto-char existing-result)
1712 (save-excursion
1713 (re-search-forward "#" nil t)
1714 (setq indent (- (current-column) 1)))
1715 (forward-line 1)
1716 (setq beg (point))
1717 (cond
1718 ((member "replace" result-params)
1719 (delete-region (point) (org-babel-result-end)))
1720 ((member "append" result-params)
1721 (goto-char (org-babel-result-end)) (setq beg (point-marker)))
1722 ((member "prepend" result-params)))) ; already there
1723 (setq results-switches
1724 (if results-switches (concat " " results-switches) ""))
1725 ;; insert results based on type
1726 (cond
1727 ;; do nothing for an empty result
1728 ((= (length result) 0))
1729 ;; insert a list if preferred
1730 ((member "list" result-params)
1731 (insert
1732 (org-babel-trim
1733 (org-list-to-generic
1734 (cons 'unordered
1735 (mapcar
1736 (lambda (el) (list nil (if (stringp el) el (format "%S" el))))
1737 (if (listp result) result (list result))))
1738 '(:splicep nil :istart "- " :iend "\n")))
1739 "\n"))
1740 ;; assume the result is a table if it's not a string
1741 ((not (stringp result))
1742 (goto-char beg)
1743 (insert (concat (orgtbl-to-orgtbl
1744 (if (or (eq 'hline (car result))
1745 (and (listp (car result))
1746 (listp (cdr (car result)))))
1747 result (list result))
1748 '(:fmt (lambda (cell) (format "%s" cell)))) "\n"))
1749 (goto-char beg) (when (org-at-table-p) (org-table-align)))
1750 ((member "file" result-params)
1751 (when inlinep (goto-char inlinep))
1752 (insert result))
1753 (t (goto-char beg) (insert result)))
1754 (when (listp result) (goto-char (org-table-end)))
1755 (setq end (point-marker))
1756 ;; possibly wrap result
1757 (flet ((wrap (start finish)
1758 (goto-char beg) (insert (concat start "\n"))
1759 (goto-char end) (insert (concat finish "\n"))
1760 (setq end (point-marker))))
1761 (cond
1762 ((member "html" result-params)
1763 (wrap "#+BEGIN_HTML" "#+END_HTML"))
1764 ((member "latex" result-params)
1765 (wrap "#+BEGIN_LaTeX" "#+END_LaTeX"))
1766 ((member "code" result-params)
1767 (wrap (format "#+BEGIN_SRC %s%s" (or lang "none") results-switches)
1768 "#+END_SRC"))
1769 ((member "org" result-params)
1770 (wrap "#+BEGIN_ORG" "#+END_ORG"))
1771 ((member "raw" result-params)
1772 (goto-char beg) (if (org-at-table-p) (org-cycle)))
1773 ((member "wrap" result-params)
1774 (when (and (stringp result) (not (member "file" result-params)))
1775 (org-babel-examplize-region beg end results-switches))
1776 (wrap "#+BEGIN_RESULT" "#+END_RESULT"))
1777 ((and (stringp result) (not (member "file" result-params)))
1778 (org-babel-examplize-region beg end results-switches)
1779 (setq end (point)))))
1780 ;; possibly indent the results to match the #+results line
1781 (when (and (not inlinep) (numberp indent) indent (> indent 0)
1782 ;; in this case `table-align' does the work for us
1783 (not (and (listp result)
1784 (member "append" result-params))))
1785 (indent-rigidly beg end indent))))
1786 (if (= (length result) 0)
1787 (if (member "value" result-params)
1788 (message "Code block returned no value.")
1789 (message "Code block produced no output."))
1790 (message "Code block evaluation complete."))))
1792 (defun org-babel-remove-result (&optional info)
1793 "Remove the result of the current source block."
1794 (interactive)
1795 (let ((location (org-babel-where-is-src-block-result nil info)) start)
1796 (when location
1797 (setq start (- location 1))
1798 (save-excursion
1799 (goto-char location) (forward-line 1)
1800 (delete-region start (org-babel-result-end))))))
1802 (defun org-babel-result-end ()
1803 "Return the point at the end of the current set of results"
1804 (save-excursion
1805 (cond
1806 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
1807 ((org-at-item-p) (let* ((struct (org-list-struct))
1808 (prvs (org-list-prevs-alist struct)))
1809 (org-list-get-list-end (point-at-bol) struct prvs)))
1811 (let ((case-fold-search t)
1812 (blocks-re (regexp-opt
1813 (list "latex" "html" "example" "src" "result" "org"))))
1814 (if (looking-at (concat "[ \t]*#\\+begin_" blocks-re))
1815 (progn (re-search-forward (concat "[ \t]*#\\+end_" blocks-re) nil t)
1816 (forward-char 1))
1817 (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
1818 (forward-line 1))))
1819 (point)))))
1821 (defun org-babel-result-to-file (result)
1822 "Convert RESULT into an `org-mode' link.
1823 If the `default-directory' is different from the containing
1824 file's directory then expand relative links."
1825 (flet ((cond-exp (file)
1826 (if (and default-directory
1827 buffer-file-name
1828 (not (string= (expand-file-name default-directory)
1829 (expand-file-name
1830 (file-name-directory buffer-file-name)))))
1831 (expand-file-name file default-directory)
1832 file)))
1833 (if (stringp result)
1834 (format "[[file:%s]]" (cond-exp result))
1835 (when (and (listp result) (= 2 (length result))
1836 (stringp (car result)) (stringp (cadr result)))
1837 (format "[[file:%s][%s]]" (car result) (cadr result))))))
1839 (defun org-babel-examplize-region (beg end &optional results-switches)
1840 "Comment out region using the inline '==' or ': ' org example quote."
1841 (interactive "*r")
1842 (flet ((chars-between (b e) (string-match "[\\S]" (buffer-substring b e))))
1843 (if (or (chars-between (save-excursion (goto-char beg) (point-at-bol)) beg)
1844 (chars-between end (save-excursion (goto-char end) (point-at-eol))))
1845 (save-excursion
1846 (goto-char beg)
1847 (insert (format "=%s=" (prog1 (buffer-substring beg end)
1848 (delete-region beg end)))))
1849 (let ((size (count-lines beg end)))
1850 (save-excursion
1851 (cond ((= size 0)) ; do nothing for an empty result
1852 ((< size org-babel-min-lines-for-block-output)
1853 (goto-char beg)
1854 (dotimes (n size)
1855 (beginning-of-line 1) (insert ": ") (forward-line 1)))
1857 (goto-char beg)
1858 (insert (if results-switches
1859 (format "#+begin_example%s\n" results-switches)
1860 "#+begin_example\n"))
1861 (if (markerp end) (goto-char end) (forward-char (- end beg)))
1862 (insert "#+end_example\n"))))))))
1864 (defun org-babel-update-block-body (new-body)
1865 "Update the body of the current code block to NEW-BODY."
1866 (if (not (org-babel-where-is-src-block-head))
1867 (error "not in source block")
1868 (save-match-data
1869 (replace-match (concat (org-babel-trim new-body) "\n") nil t nil 5))
1870 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
1872 (defun org-babel-merge-params (&rest plists)
1873 "Combine all parameter association lists in PLISTS.
1874 Later elements of PLISTS override the values of previous elements.
1875 This takes into account some special considerations for certain
1876 parameters when merging lists."
1877 (let ((results-exclusive-groups
1878 (mapcar (lambda (group) (mapcar #'symbol-name group))
1879 (cdr (assoc 'results org-babel-common-header-args-w-values))))
1880 (exports-exclusive-groups
1881 (mapcar (lambda (group) (mapcar #'symbol-name group))
1882 (cdr (assoc 'exports org-babel-common-header-args-w-values))))
1883 (variable-index 0)
1884 params results exports tangle noweb cache vars shebang comments padline)
1885 (flet ((e-merge (exclusive-groups &rest result-params)
1886 ;; maintain exclusivity of mutually exclusive parameters
1887 (let (output)
1888 (mapc (lambda (new-params)
1889 (mapc (lambda (new-param)
1890 (mapc (lambda (exclusive-group)
1891 (when (member new-param exclusive-group)
1892 (mapcar (lambda (excluded-param)
1893 (setq output
1894 (delete
1895 excluded-param
1896 output)))
1897 exclusive-group)))
1898 exclusive-groups)
1899 (setq output (org-uniquify
1900 (cons new-param output))))
1901 new-params))
1902 result-params)
1903 output)))
1904 (mapc
1905 (lambda (plist)
1906 (mapc
1907 (lambda (pair)
1908 (case (car pair)
1909 (:var
1910 (let ((name (if (listp (cdr pair))
1911 (cadr pair)
1912 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
1913 (cdr pair))
1914 (intern (match-string 1 (cdr pair)))))))
1915 (if name
1916 (setq vars
1917 (append
1918 (if (member name (mapcar #'car vars))
1919 (delq nil
1920 (mapcar
1921 (lambda (p)
1922 (unless (equal (car p) name) p))
1923 vars))
1924 vars)
1925 (list (cons name pair))))
1926 ;; if no name is given and we already have named variables
1927 ;; then assign to named variables in order
1928 (if (and vars (nth variable-index vars))
1929 (prog1 (setf (cddr (nth variable-index vars))
1930 (concat (symbol-name
1931 (car (nth variable-index vars)))
1932 "=" (cdr pair)))
1933 (incf variable-index))
1934 (error "variable \"%s\" must be assigned a default value"
1935 (cdr pair))))))
1936 (:results
1937 (setq results (e-merge results-exclusive-groups
1938 results
1939 (split-string
1940 (let ((r (cdr pair)))
1941 (if (stringp r) r (eval r)))))))
1942 (:file
1943 (when (cdr pair)
1944 (setq results (e-merge results-exclusive-groups
1945 results '("file")))
1946 (unless (or (member "both" exports)
1947 (member "none" exports)
1948 (member "code" exports))
1949 (setq exports (e-merge exports-exclusive-groups
1950 exports '("results"))))
1951 (setq params (cons pair (assq-delete-all (car pair) params)))))
1952 (:exports
1953 (setq exports (e-merge exports-exclusive-groups
1954 exports (split-string (cdr pair)))))
1955 (:tangle ;; take the latest -- always overwrite
1956 (setq tangle (or (list (cdr pair)) tangle)))
1957 (:noweb
1958 (setq noweb (e-merge '(("yes" "no" "tangle")) noweb
1959 (split-string (or (cdr pair) "")))))
1960 (:cache
1961 (setq cache (e-merge '(("yes" "no")) cache
1962 (split-string (or (cdr pair) "")))))
1963 (:padline
1964 (setq padline (e-merge '(("yes" "no")) padline
1965 (split-string (or (cdr pair) "")))))
1966 (:shebang ;; take the latest -- always overwrite
1967 (setq shebang (or (list (cdr pair)) shebang)))
1968 (:comments
1969 (setq comments (e-merge '(("yes" "no")) comments
1970 (split-string (or (cdr pair) "")))))
1971 (t ;; replace: this covers e.g. :session
1972 (setq params (cons pair (assq-delete-all (car pair) params))))))
1973 plist))
1974 plists))
1975 (setq vars (reverse vars))
1976 (while vars (setq params (cons (cons :var (cddr (pop vars))) params)))
1977 (mapc
1978 (lambda (hd)
1979 (let ((key (intern (concat ":" (symbol-name hd))))
1980 (val (eval hd)))
1981 (setf params (cons (cons key (mapconcat 'identity val " ")) params))))
1982 '(results exports tangle noweb padline cache shebang comments))
1983 params))
1985 (defun org-babel-expand-noweb-references (&optional info parent-buffer)
1986 "Expand Noweb references in the body of the current source code block.
1988 For example the following reference would be replaced with the
1989 body of the source-code block named 'example-block'.
1991 <<example-block>>
1993 Note that any text preceding the <<foo>> construct on a line will
1994 be interposed between the lines of the replacement text. So for
1995 example if <<foo>> is placed behind a comment, then the entire
1996 replacement text will also be commented.
1998 This function must be called from inside of the buffer containing
1999 the source-code block which holds BODY.
2001 In addition the following syntax can be used to insert the
2002 results of evaluating the source-code block named 'example-block'.
2004 <<example-block()>>
2006 Any optional arguments can be passed to example-block by placing
2007 the arguments inside the parenthesis following the convention
2008 defined by `org-babel-lob'. For example
2010 <<example-block(a=9)>>
2012 would set the value of argument \"a\" equal to \"9\". Note that
2013 these arguments are not evaluated in the current source-code
2014 block but are passed literally to the \"example-block\"."
2015 (let* ((parent-buffer (or parent-buffer (current-buffer)))
2016 (info (or info (org-babel-get-src-block-info)))
2017 (lang (nth 0 info))
2018 (body (nth 1 info))
2019 (comment (string= "noweb" (cdr (assoc :comments (nth 2 info)))))
2020 (new-body "") index source-name evaluate prefix blocks-in-buffer)
2021 (flet ((nb-add (text) (setq new-body (concat new-body text)))
2022 (c-wrap (text)
2023 (with-temp-buffer
2024 (funcall (intern (concat lang "-mode")))
2025 (comment-region (point) (progn (insert text) (point)))
2026 (org-babel-trim (buffer-string))))
2027 (blocks () ;; return the info lists of all blocks in this buffer
2028 (let (infos)
2029 (save-restriction
2030 (widen)
2031 (org-babel-map-src-blocks nil
2032 (setq infos (cons (org-babel-get-src-block-info 'light)
2033 infos))))
2034 (reverse infos))))
2035 (with-temp-buffer
2036 (insert body) (goto-char (point-min))
2037 (setq index (point))
2038 (while (and (re-search-forward "<<\\(.+?\\)>>" nil t))
2039 (save-match-data (setf source-name (match-string 1)))
2040 (save-match-data (setq evaluate (string-match "\(.*\)" source-name)))
2041 (save-match-data
2042 (setq prefix
2043 (buffer-substring (match-beginning 0)
2044 (save-excursion
2045 (beginning-of-line 1) (point)))))
2046 ;; add interval to new-body (removing noweb reference)
2047 (goto-char (match-beginning 0))
2048 (nb-add (buffer-substring index (point)))
2049 (goto-char (match-end 0))
2050 (setq index (point))
2051 (nb-add
2052 (with-current-buffer parent-buffer
2053 (mapconcat ;; interpose PREFIX between every line
2054 #'identity
2055 (split-string
2056 (if evaluate
2057 (let ((raw (org-babel-ref-resolve source-name)))
2058 (if (stringp raw) raw (format "%S" raw)))
2060 ;; retrieve from the library of babel
2061 (nth 2 (assoc (intern source-name)
2062 org-babel-library-of-babel))
2063 ;; return the contents of headlines literally
2064 (save-excursion
2065 (when (org-babel-ref-goto-headline-id source-name)
2066 (org-babel-ref-headline-body)))
2067 ;; find the expansion of reference in this buffer
2068 (mapconcat
2069 (lambda (i)
2070 (when (string= source-name
2071 (or (cdr (assoc :noweb-ref (nth 2 i)))
2072 (nth 4 i)))
2073 (let ((body (org-babel-expand-noweb-references i)))
2074 (if comment
2075 ((lambda (cs)
2076 (concat (c-wrap (car cs)) "\n"
2077 body "\n" (c-wrap (cadr cs))))
2078 (org-babel-tangle-comment-links i))
2079 body))))
2080 (or blocks-in-buffer
2081 (setq blocks-in-buffer (blocks)))
2083 ;; possibly raise an error if named block doesn't exist
2084 (if (member lang org-babel-noweb-error-langs)
2085 (error "%s" (concat
2086 "<<" source-name ">> "
2087 "could not be resolved (see "
2088 "`org-babel-noweb-error-langs')"))
2089 "")))
2090 "[\n\r]") (concat "\n" prefix)))))
2091 (nb-add (buffer-substring index (point-max)))))
2092 new-body))
2094 (defun org-babel-clean-text-properties (text)
2095 "Strip all properties from text return."
2096 (when text
2097 (set-text-properties 0 (length text) nil text) text))
2099 (defun org-babel-strip-protective-commas (body)
2100 "Strip protective commas from bodies of source blocks."
2101 (when body
2102 (replace-regexp-in-string "^,#" "#" body)))
2104 (defun org-babel-script-escape (str &optional force)
2105 "Safely convert tables into elisp lists."
2106 (let (in-single in-double out)
2107 ((lambda (escaped) (condition-case nil (org-babel-read escaped) (error escaped)))
2108 (if (or force
2109 (and (stringp str)
2110 (> (length str) 2)
2111 (or (and (string-equal "[" (substring str 0 1))
2112 (string-equal "]" (substring str -1)))
2113 (and (string-equal "{" (substring str 0 1))
2114 (string-equal "}" (substring str -1)))
2115 (and (string-equal "(" (substring str 0 1))
2116 (string-equal ")" (substring str -1))))))
2117 (org-babel-read
2118 (concat
2120 (progn
2121 (mapc
2122 (lambda (ch)
2123 (setq
2125 (case ch
2126 (91 (if (or in-double in-single) ; [
2127 (cons 91 out)
2128 (cons 40 out)))
2129 (93 (if (or in-double in-single) ; ]
2130 (cons 93 out)
2131 (cons 41 out)))
2132 (123 (if (or in-double in-single) ; {
2133 (cons 123 out)
2134 (cons 40 out)))
2135 (125 (if (or in-double in-single) ; }
2136 (cons 125 out)
2137 (cons 41 out)))
2138 (44 (if (or in-double in-single) ; ,
2139 (cons 44 out) (cons 32 out)))
2140 (39 (if in-double ; '
2141 (cons 39 out)
2142 (setq in-single (not in-single)) (cons 34 out)))
2143 (34 (if in-single ; "
2144 (append (list 34 32) out)
2145 (setq in-double (not in-double)) (cons 34 out)))
2146 (t (cons ch out)))))
2147 (string-to-list str))
2148 (apply #'string (reverse out)))))
2149 str))))
2151 (defun org-babel-read (cell &optional inhibit-lisp-eval)
2152 "Convert the string value of CELL to a number if appropriate.
2153 Otherwise if cell looks like lisp (meaning it starts with a
2154 \"(\", \"'\", \"`\" or a \"[\") then read it as lisp, otherwise
2155 return it unmodified as a string. Optional argument NO-LISP-EVAL
2156 inhibits lisp evaluation for situations in which is it not
2157 appropriate."
2158 (if (and (stringp cell) (not (equal cell "")))
2159 (or (org-babel-number-p cell)
2160 (if (and (not inhibit-lisp-eval)
2161 (member (substring cell 0 1) '("(" "'" "`" "[")))
2162 (eval (read cell))
2163 (if (string= (substring cell 0 1) "\"")
2164 (read cell)
2165 (progn (set-text-properties 0 (length cell) nil cell) cell))))
2166 cell))
2168 (defun org-babel-number-p (string)
2169 "If STRING represents a number return it's value."
2170 (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string)
2171 (= (length (substring string (match-beginning 0)
2172 (match-end 0)))
2173 (length string)))
2174 (string-to-number string)))
2176 (defun org-babel-import-elisp-from-file (file-name &optional separator)
2177 "Read the results located at FILE-NAME into an elisp table.
2178 If the table is trivial, then return it as a scalar."
2179 (let (result)
2180 (save-window-excursion
2181 (with-temp-buffer
2182 (condition-case nil
2183 (progn
2184 (org-table-import file-name separator)
2185 (delete-file file-name)
2186 (setq result (mapcar (lambda (row)
2187 (mapcar #'org-babel-string-read row))
2188 (org-table-to-lisp))))
2189 (error nil)))
2190 (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
2191 (if (consp (car result))
2192 (if (null (cdr (car result)))
2193 (caar result)
2194 result)
2195 (car result))
2196 result))))
2198 (defun org-babel-string-read (cell)
2199 "Strip nested \"s from around strings."
2200 (org-babel-read (or (and (stringp cell)
2201 (string-match "\\\"\\(.+\\)\\\"" cell)
2202 (match-string 1 cell))
2203 cell)))
2205 (defun org-babel-reverse-string (string)
2206 "Return the reverse of STRING."
2207 (apply 'string (reverse (string-to-list string))))
2209 (defun org-babel-chomp (string &optional regexp)
2210 "Strip trailing spaces and carriage returns from STRING.
2211 Default regexp used is \"[ \f\t\n\r\v]\" but can be
2212 overwritten by specifying a regexp as a second argument."
2213 (let ((regexp (or regexp "[ \f\t\n\r\v]")))
2214 (while (and (> (length string) 0)
2215 (string-match regexp (substring string -1)))
2216 (setq string (substring string 0 -1)))
2217 string))
2219 (defun org-babel-trim (string &optional regexp)
2220 "Strip leading and trailing spaces and carriage returns from STRING.
2221 Like `org-babel-chomp' only it runs on both the front and back
2222 of the string."
2223 (org-babel-chomp (org-babel-reverse-string
2224 (org-babel-chomp (org-babel-reverse-string string) regexp))
2225 regexp))
2227 (defvar org-babel-org-babel-call-process-region-original nil)
2228 (defun org-babel-tramp-handle-call-process-region
2229 (start end program &optional delete buffer display &rest args)
2230 "Use tramp to handle call-process-region.
2231 Fixes a bug in `tramp-handle-call-process-region'."
2232 (if (and (featurep 'tramp) (file-remote-p default-directory))
2233 (let ((tmpfile (tramp-compat-make-temp-file "")))
2234 (write-region start end tmpfile)
2235 (when delete (delete-region start end))
2236 (unwind-protect
2237 ;; (apply 'call-process program tmpfile buffer display args)
2238 ;; bug in tramp
2239 (apply 'process-file program tmpfile buffer display args)
2240 (delete-file tmpfile)))
2241 ;; org-babel-call-process-region-original is the original emacs
2242 ;; definition. It is in scope from the let binding in
2243 ;; org-babel-execute-src-block
2244 (apply org-babel-call-process-region-original
2245 start end program delete buffer display args)))
2247 (defun org-babel-local-file-name (file)
2248 "Return the local name component of FILE."
2249 (if (file-remote-p file)
2250 (let (localname)
2251 (with-parsed-tramp-file-name file nil
2252 localname))
2253 file))
2255 (defun org-babel-process-file-name (name &optional no-quote-p)
2256 "Prepare NAME to be used in an external process.
2257 If NAME specifies a remote location, the remote portion of the
2258 name is removed, since in that case the process will be executing
2259 remotely. The file name is then processed by
2260 `expand-file-name'. Unless second argument NO-QUOTE-P is non-nil,
2261 the file name is additionally processed by
2262 `shell-quote-argument'"
2263 ((lambda (f) (if no-quote-p f (shell-quote-argument f)))
2264 (expand-file-name (org-babel-local-file-name name))))
2266 (defvar org-babel-temporary-directory)
2267 (unless (or noninteractive (boundp 'org-babel-temporary-directory))
2268 (defvar org-babel-temporary-directory
2269 (or (and (boundp 'org-babel-temporary-directory)
2270 (file-exists-p org-babel-temporary-directory)
2271 org-babel-temporary-directory)
2272 (make-temp-file "babel-" t))
2273 "Directory to hold temporary files created to execute code blocks.
2274 Used by `org-babel-temp-file'. This directory will be removed on
2275 Emacs shutdown."))
2277 (defun org-babel-temp-file (prefix &optional suffix)
2278 "Create a temporary file in the `org-babel-temporary-directory'.
2279 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2280 value of `temporary-file-directory' temporarily set to the value
2281 of `org-babel-temporary-directory'."
2282 (if (file-remote-p default-directory)
2283 (make-temp-file
2284 (concat (file-remote-p default-directory)
2285 (expand-file-name
2286 prefix temporary-file-directory)
2287 nil suffix))
2288 (let ((temporary-file-directory
2289 (or (and (boundp 'org-babel-temporary-directory)
2290 (file-exists-p org-babel-temporary-directory)
2291 org-babel-temporary-directory)
2292 temporary-file-directory)))
2293 (make-temp-file prefix nil suffix))))
2295 (defun org-babel-remove-temporary-directory ()
2296 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2297 (when (and (boundp 'org-babel-temporary-directory)
2298 (file-exists-p org-babel-temporary-directory))
2299 ;; taken from `delete-directory' in files.el
2300 (condition-case nil
2301 (progn
2302 (mapc (lambda (file)
2303 ;; This test is equivalent to
2304 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2305 ;; but more efficient
2306 (if (eq t (car (file-attributes file)))
2307 (delete-directory file)
2308 (delete-file file)))
2309 ;; We do not want to delete "." and "..".
2310 (directory-files org-babel-temporary-directory 'full
2311 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2312 (delete-directory org-babel-temporary-directory))
2313 (error
2314 (message "Failed to remove temporary Org-babel directory %s"
2315 (if (boundp 'org-babel-temporary-directory)
2316 org-babel-temporary-directory
2317 "[directory not defined]"))))))
2319 (add-hook 'kill-emacs-hook 'org-babel-remove-temporary-directory)
2321 (provide 'ob)
2325 ;;; ob.el ends here