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