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