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