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