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