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