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