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