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