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