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