Merge branch 'maint'
[org-mode.git] / lisp / ob.el
blobb5f6c452c96bf0bf24f638e26b8bf8c2e59c9c63
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))
93 (declare-function org-add-protective-commas "org-src" (beg end))
95 (defgroup org-babel nil
96 "Code block evaluation and management in `org-mode' documents."
97 :tag "Babel"
98 :group 'org)
100 (defcustom org-confirm-babel-evaluate t
101 "Confirm before evaluation.
102 Require confirmation before interactively evaluating code
103 blocks in Org-mode buffers. The default value of this variable
104 is t, meaning confirmation is required for any code block
105 evaluation. This variable can be set to nil to inhibit any
106 future confirmation requests. This variable can also be set to a
107 function which takes two arguments the language of the code block
108 and the body of the code block. Such a function should then
109 return a non-nil value if the user should be prompted for
110 execution or nil if no prompt is required.
112 Warning: Disabling confirmation may result in accidental
113 evaluation of potentially harmful code. It may be advisable
114 remove code block execution from C-c C-c as further protection
115 against accidental code block evaluation. The
116 `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
117 remove code block execution from the C-c C-c keybinding."
118 :group 'org-babel
119 :version "24.1"
120 :type '(choice boolean function))
121 ;; don't allow this variable to be changed through file settings
122 (put 'org-confirm-babel-evaluate 'safe-local-variable (lambda (x) (eq x t)))
124 (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
125 "Remove code block evaluation from the C-c C-c key binding."
126 :group 'org-babel
127 :version "24.1"
128 :type 'boolean)
130 (defcustom org-babel-results-keyword "RESULTS"
131 "Keyword used to name results generated by code blocks.
132 Should be either RESULTS or NAME however any capitalization may
133 be used."
134 :group 'org-babel
135 :type 'string)
137 (defcustom org-babel-noweb-wrap-start "<<"
138 "String used to begin a noweb reference in a code block.
139 See also `org-babel-noweb-wrap-end'."
140 :group 'org-babel
141 :type 'string)
143 (defcustom org-babel-noweb-wrap-end ">>"
144 "String used to end a noweb reference in a code block.
145 See also `org-babel-noweb-wrap-start'."
146 :group 'org-babel
147 :type 'string)
149 (defun org-babel-noweb-wrap (&optional regexp)
150 (concat org-babel-noweb-wrap-start
151 (or regexp "\\([^ \t\n].+?[^ \t]\\|[^ \t\n]\\)")
152 org-babel-noweb-wrap-end))
154 (defvar org-babel-src-name-regexp
155 "^[ \t]*#\\+name:[ \t]*"
156 "Regular expression used to match a source name line.")
158 (defvar org-babel-multi-line-header-regexp
159 "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
160 "Regular expression used to match multi-line header arguments.")
162 (defvar org-babel-src-name-w-name-regexp
163 (concat org-babel-src-name-regexp
164 "\\("
165 org-babel-multi-line-header-regexp
166 "\\)*"
167 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)")
168 "Regular expression matching source name lines with a name.")
170 (defvar org-babel-src-block-regexp
171 (concat
172 ;; (1) indentation (2) lang
173 "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
174 ;; (3) switches
175 "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
176 ;; (4) header arguments
177 "\\([^\n]*\\)\n"
178 ;; (5) body
179 "\\([^\000]*?\n\\)?[ \t]*#\\+end_src")
180 "Regexp used to identify code blocks.")
182 (defvar org-babel-inline-src-block-regexp
183 (concat
184 ;; (1) replacement target (2) lang
185 "\\(?:^\\|[^-[:alnum:]]\\)\\(src_\\([^ \f\t\n\r\v]+\\)"
186 ;; (3,4) (unused, headers)
187 "\\(\\|\\[\\(.*?\\)\\]\\)"
188 ;; (5) body
189 "{\\([^\f\n\r\v]+?\\)}\\)")
190 "Regexp used to identify inline src-blocks.")
192 (defun org-babel-get-header (params key &optional others)
193 "Select only header argument of type KEY from a list.
194 Optional argument OTHERS indicates that only the header that do
195 not match KEY should be returned."
196 (delq nil
197 (mapcar
198 (lambda (p) (when (funcall (if others #'not #'identity) (eq (car p) key)) p))
199 params)))
201 (defun org-babel-get-inline-src-block-matches()
202 "Set match data if within body of an inline source block.
203 Returns non-nil if match-data set"
204 (let ((src-at-0-p (save-excursion
205 (beginning-of-line 1)
206 (string= "src" (thing-at-point 'word))))
207 (first-line-p (= 1 (line-number-at-pos)))
208 (orig (point)))
209 (let ((search-for (cond ((and src-at-0-p first-line-p "src_"))
210 (first-line-p "[[:punct:] \t]src_")
211 (t "[[:punct:] \f\t\n\r\v]src_")))
212 (lower-limit (if first-line-p
214 (- (point-at-bol) 1))))
215 (save-excursion
216 (when (or (and src-at-0-p (bobp))
217 (and (re-search-forward "}" (point-at-eol) t)
218 (re-search-backward search-for lower-limit t)
219 (> orig (point))))
220 (when (looking-at org-babel-inline-src-block-regexp)
221 t ))))))
223 (defvar org-babel-inline-lob-one-liner-regexp)
224 (defun org-babel-get-lob-one-liner-matches()
225 "Set match data if on line of an lob one liner.
226 Returns non-nil if match-data set"
227 (save-excursion
228 (unless (= (point) (point-at-bol)) ;; move before inline block
229 (re-search-backward "[ \f\t\n\r\v]" nil t))
230 (if (looking-at org-babel-inline-lob-one-liner-regexp)
232 nil)))
234 (defun org-babel-get-src-block-info (&optional light)
235 "Get information on the current source block.
237 Optional argument LIGHT does not resolve remote variable
238 references; a process which could likely result in the execution
239 of other code blocks.
241 Returns a list
242 (language body header-arguments-alist switches name indent)."
243 (let ((case-fold-search t) head info name indent)
244 ;; full code block
245 (if (setq head (org-babel-where-is-src-block-head))
246 (save-excursion
247 (goto-char head)
248 (setq info (org-babel-parse-src-block-match))
249 (setq indent (car (last info)))
250 (setq info (butlast info))
251 (while (and (forward-line -1)
252 (looking-at org-babel-multi-line-header-regexp))
253 (setf (nth 2 info)
254 (org-babel-merge-params
255 (nth 2 info)
256 (org-babel-parse-header-arguments (match-string 1)))))
257 (when (looking-at org-babel-src-name-w-name-regexp)
258 (setq name (org-no-properties (match-string 3)))
259 (when (and (match-string 5) (> (length (match-string 5)) 0))
260 (setf (nth 2 info) ;; merge functional-syntax vars and header-args
261 (org-babel-merge-params
262 (mapcar
263 (lambda (ref) (cons :var ref))
264 (mapcar
265 (lambda (var) ;; check that each variable is initialized
266 (if (string-match ".+=.+" var)
268 (error
269 "variable \"%s\"%s must be assigned a default value"
270 var (if name (format " in block \"%s\"" name) ""))))
271 (org-babel-ref-split-args (match-string 5))))
272 (nth 2 info))))))
273 ;; inline source block
274 (when (org-babel-get-inline-src-block-matches)
275 (setq info (org-babel-parse-inline-src-block-match))))
276 ;; resolve variable references and add summary parameters
277 (when (and info (not light))
278 (setf (nth 2 info) (org-babel-process-params (nth 2 info))))
279 (when info (append info (list name indent)))))
281 (defvar org-current-export-file) ; dynamically bound
282 (defun org-babel-confirm-evaluate (info)
283 "Confirm evaluation of the code block INFO.
284 This behavior can be suppressed by setting the value of
285 `org-confirm-babel-evaluate' to nil, in which case all future
286 interactive code block evaluations will proceed without any
287 confirmation from the user.
289 Note disabling confirmation may result in accidental evaluation
290 of potentially harmful code."
291 (let* ((eval (or (cdr (assoc :eval (nth 2 info)))
292 (when (assoc :noeval (nth 2 info)) "no")))
293 (query (cond ((equal eval "query") t)
294 ((and (boundp 'org-current-export-file)
295 org-current-export-file
296 (equal eval "query-export")) t)
297 ((functionp org-confirm-babel-evaluate)
298 (funcall org-confirm-babel-evaluate
299 (nth 0 info) (nth 1 info)))
300 (t org-confirm-babel-evaluate))))
301 (if (or (equal eval "never") (equal eval "no")
302 (and (boundp 'org-current-export-file)
303 org-current-export-file
304 (or (equal eval "no-export")
305 (equal eval "never-export")))
306 (and query
307 (not (yes-or-no-p
308 (format "Evaluate this%scode block%son your system? "
309 (if info (format " %s " (nth 0 info)) " ")
310 (if (nth 4 info)
311 (format " (%s) " (nth 4 info)) " "))))))
312 (prog1 nil (message "Evaluation %s"
313 (if (or (equal eval "never") (equal eval "no")
314 (equal eval "no-export")
315 (equal eval "never-export"))
316 "Disabled" "Aborted")))
317 t)))
319 ;;;###autoload
320 (defun org-babel-execute-safely-maybe ()
321 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
322 (org-babel-execute-maybe)))
324 (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-execute-safely-maybe)
326 ;;;###autoload
327 (defun org-babel-execute-maybe ()
328 (interactive)
329 (or (org-babel-execute-src-block-maybe)
330 (org-babel-lob-execute-maybe)))
332 (defun org-babel-execute-src-block-maybe ()
333 "Conditionally execute a source block.
334 Detect if this is context for a Babel src-block and if so
335 then run `org-babel-execute-src-block'."
336 (interactive)
337 (let ((info (org-babel-get-src-block-info)))
338 (if info
339 (progn (org-babel-eval-wipe-error-buffer)
340 (org-babel-execute-src-block current-prefix-arg info) t) nil)))
342 ;;;###autoload
343 (defun org-babel-view-src-block-info ()
344 "Display information on the current source block.
345 This includes header arguments, language and name, and is largely
346 a window into the `org-babel-get-src-block-info' function."
347 (interactive)
348 (let ((info (org-babel-get-src-block-info 'light))
349 (full (lambda (it) (> (length it) 0)))
350 (printf (lambda (fmt &rest args) (princ (apply #'format fmt args)))))
351 (when info
352 (with-help-window (help-buffer)
353 (let ((name (nth 4 info))
354 (lang (nth 0 info))
355 (switches (nth 3 info))
356 (header-args (nth 2 info)))
357 (when name (funcall printf "Name: %s\n" name))
358 (when lang (funcall printf "Lang: %s\n" lang))
359 (when (funcall full switches) (funcall printf "Switches: %s\n" switches))
360 (funcall printf "Header Arguments:\n")
361 (dolist (pair (sort header-args
362 (lambda (a b) (string< (symbol-name (car a))
363 (symbol-name (car b))))))
364 (when (funcall full (cdr pair))
365 (funcall printf "\t%S%s\t%s\n"
366 (car pair)
367 (if (> (length (format "%S" (car pair))) 7) "" "\t")
368 (cdr pair)))))))))
370 ;;;###autoload
371 (defun org-babel-expand-src-block-maybe ()
372 "Conditionally expand a source block.
373 Detect if this is context for a org-babel src-block and if so
374 then run `org-babel-expand-src-block'."
375 (interactive)
376 (let ((info (org-babel-get-src-block-info)))
377 (if info
378 (progn (org-babel-expand-src-block current-prefix-arg info) t)
379 nil)))
381 ;;;###autoload
382 (defun org-babel-load-in-session-maybe ()
383 "Conditionally load a source block in a session.
384 Detect if this is context for a org-babel src-block and if so
385 then run `org-babel-load-in-session'."
386 (interactive)
387 (let ((info (org-babel-get-src-block-info)))
388 (if info
389 (progn (org-babel-load-in-session current-prefix-arg info) t)
390 nil)))
392 (add-hook 'org-metaup-hook 'org-babel-load-in-session-maybe)
394 ;;;###autoload
395 (defun org-babel-pop-to-session-maybe ()
396 "Conditionally pop to a session.
397 Detect if this is context for a org-babel src-block and if so
398 then run `org-babel-pop-to-session'."
399 (interactive)
400 (let ((info (org-babel-get-src-block-info)))
401 (if info (progn (org-babel-pop-to-session current-prefix-arg info) t) nil)))
403 (add-hook 'org-metadown-hook 'org-babel-pop-to-session-maybe)
405 (defconst org-babel-common-header-args-w-values
406 '((cache . ((no yes)))
407 (cmdline . :any)
408 (colnames . ((nil no yes)))
409 (comments . ((no link yes org both noweb)))
410 (dir . :any)
411 (eval . ((never query)))
412 (exports . ((code results both none)))
413 (file . :any)
414 (file-desc . :any)
415 (hlines . ((no yes)))
416 (mkdirp . ((yes no)))
417 (no-expand)
418 (noeval)
419 (noweb . ((yes no tangle no-export strip-export)))
420 (noweb-ref . :any)
421 (noweb-sep . :any)
422 (padline . ((yes no)))
423 (results . ((file list vector table scalar verbatim)
424 (raw html latex org code pp drawer)
425 (replace silent append prepend)
426 (output value)))
427 (rownames . ((no yes)))
428 (sep . :any)
429 (session . :any)
430 (shebang . :any)
431 (tangle . ((tangle yes no :any)))
432 (var . :any)
433 (wrap . :any)))
435 (defconst org-babel-header-arg-names
436 (mapcar #'car org-babel-common-header-args-w-values)
437 "Common header arguments used by org-babel.
438 Note that individual languages may define their own language
439 specific header arguments as well.")
441 (defvar org-babel-default-header-args
442 '((:session . "none") (:results . "replace") (:exports . "code")
443 (:cache . "no") (:noweb . "no") (:hlines . "no") (:tangle . "no")
444 (:padnewline . "yes"))
445 "Default arguments to use when evaluating a source block.")
447 (defvar org-babel-default-inline-header-args
448 '((:session . "none") (:results . "replace") (:exports . "results"))
449 "Default arguments to use when evaluating an inline source block.")
451 (defvar org-babel-data-names '("tblname" "results" "name"))
453 (defvar org-babel-result-regexp
454 (concat "^[ \t]*#\\+"
455 (regexp-opt org-babel-data-names t)
456 "\\(\\[\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*")
457 "Regular expression used to match result lines.
458 If the results are associated with a hash key then the hash will
459 be saved in the second match data.")
461 (defvar org-babel-result-w-name-regexp
462 (concat org-babel-result-regexp
463 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
465 (defvar org-babel-min-lines-for-block-output 10
466 "The minimum number of lines for block output.
467 If number of lines of output is equal to or exceeds this
468 value, the output is placed in a #+begin_example...#+end_example
469 block. Otherwise the output is marked as literal by inserting
470 colons at the starts of the lines. This variable only takes
471 effect if the :results output option is in effect.")
473 (defvar org-babel-noweb-error-langs nil
474 "Languages for which Babel will raise literate programming errors.
475 List of languages for which errors should be raised when the
476 source code block satisfying a noweb reference in this language
477 can not be resolved.")
479 (defvar org-babel-hash-show 4
480 "Number of initial characters to show of a hidden results hash.")
482 (defvar org-babel-after-execute-hook nil
483 "Hook for functions to be called after `org-babel-execute-src-block'")
485 (defun org-babel-named-src-block-regexp-for-name (name)
486 "This generates a regexp used to match a src block named NAME."
487 (concat org-babel-src-name-regexp (regexp-quote name)
488 "[ \t(]*[\r\n]\\(?:^#.*[\r\n]\\)*"
489 (substring org-babel-src-block-regexp 1)))
491 (defun org-babel-named-data-regexp-for-name (name)
492 "This generates a regexp used to match data named NAME."
493 (concat org-babel-result-regexp (regexp-quote name) "\\([ \t]\\|$\\)"))
495 ;;; functions
496 (defvar call-process-region)
497 ;;;###autoload
499 (defun org-babel-execute-src-block (&optional arg info params)
500 "Execute the current source code block.
501 Insert the results of execution into the buffer. Source code
502 execution and the collection and formatting of results can be
503 controlled through a variety of header arguments.
505 With prefix argument ARG, force re-execution even if an existing
506 result cached in the buffer would otherwise have been returned.
508 Optionally supply a value for INFO in the form returned by
509 `org-babel-get-src-block-info'.
511 Optionally supply a value for PARAMS which will be merged with
512 the header arguments specified at the front of the source code
513 block."
514 (interactive)
515 (let ((info (or info (org-babel-get-src-block-info))))
516 (when (org-babel-confirm-evaluate
517 (let ((i info))
518 (setf (nth 2 i) (org-babel-merge-params (nth 2 info) params))
520 (let* ((lang (nth 0 info))
521 (params (if params
522 (org-babel-process-params
523 (org-babel-merge-params (nth 2 info) params))
524 (nth 2 info)))
525 (cache? (and (not arg) (cdr (assoc :cache params))
526 (string= "yes" (cdr (assoc :cache params)))))
527 (result-params (cdr (assoc :result-params params)))
528 (new-hash (when cache? (org-babel-sha1-hash info)))
529 (old-hash (when cache? (org-babel-current-result-hash)))
530 (body (setf (nth 1 info)
531 (if (org-babel-noweb-p params :eval)
532 (org-babel-expand-noweb-references info)
533 (nth 1 info))))
534 (dir (cdr (assoc :dir params)))
535 (default-directory
536 (or (and dir (file-name-as-directory (expand-file-name dir)))
537 default-directory))
538 (org-babel-call-process-region-original
539 (if (boundp 'org-babel-call-process-region-original)
540 org-babel-call-process-region-original
541 (symbol-function 'call-process-region)))
542 (indent (car (last info)))
543 result cmd)
544 (unwind-protect
545 (let ((call-process-region
546 (lambda (&rest args)
547 (apply 'org-babel-tramp-handle-call-process-region args))))
548 (let ((lang-check (lambda (f)
549 (let ((f (intern (concat "org-babel-execute:" f))))
550 (when (fboundp f) f)))))
551 (setq cmd
552 (or (funcall lang-check lang)
553 (funcall lang-check (symbol-name
554 (cdr (assoc lang org-src-lang-modes))))
555 (error "No org-babel-execute function for %s!" lang))))
556 (if (and (not arg) new-hash (equal new-hash old-hash))
557 (save-excursion ;; return cached result
558 (goto-char (org-babel-where-is-src-block-result nil info))
559 (end-of-line 1) (forward-char 1)
560 (setq result (org-babel-read-result))
561 (message (replace-regexp-in-string
562 "%" "%%" (format "%S" result))) result)
563 (message "executing %s code block%s..."
564 (capitalize lang)
565 (if (nth 4 info) (format " (%s)" (nth 4 info)) ""))
566 (setq result
567 ((lambda (result)
568 (if (and (eq (cdr (assoc :result-type params)) 'value)
569 (or (member "vector" result-params)
570 (member "table" result-params))
571 (not (listp result)))
572 (list (list result)) result))
573 (funcall cmd body params)))
574 ;; if non-empty result and :file then write to :file
575 (when (cdr (assoc :file params))
576 (when result
577 (with-temp-file (cdr (assoc :file params))
578 (insert
579 (org-babel-format-result
580 result (cdr (assoc :sep (nth 2 info)))))))
581 (setq result (cdr (assoc :file params))))
582 (org-babel-insert-result
583 result result-params info new-hash indent lang)
584 (run-hooks 'org-babel-after-execute-hook)
585 result))
586 (setq call-process-region 'org-babel-call-process-region-original))))))
588 (defun org-babel-expand-body:generic (body params &optional var-lines)
589 "Expand BODY with PARAMS.
590 Expand a block of code with org-babel according to its header
591 arguments. This generic implementation of body expansion is
592 called for languages which have not defined their own specific
593 org-babel-expand-body:lang function."
594 (mapconcat #'identity (append var-lines (list body)) "\n"))
596 ;;;###autoload
597 (defun org-babel-expand-src-block (&optional arg info params)
598 "Expand the current source code block.
599 Expand according to the source code block's header
600 arguments and pop open the results in a preview buffer."
601 (interactive)
602 (let* ((info (or info (org-babel-get-src-block-info)))
603 (lang (nth 0 info))
604 (params (setf (nth 2 info)
605 (sort (org-babel-merge-params (nth 2 info) params)
606 (lambda (el1 el2) (string< (symbol-name (car el1))
607 (symbol-name (car el2)))))))
608 (body (setf (nth 1 info)
609 (if (org-babel-noweb-p params :eval)
610 (org-babel-expand-noweb-references info) (nth 1 info))))
611 (expand-cmd (intern (concat "org-babel-expand-body:" lang)))
612 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
613 lang)))
614 (expanded
615 (if (fboundp expand-cmd) (funcall expand-cmd body params)
616 (org-babel-expand-body:generic
617 body params (and (fboundp assignments-cmd)
618 (funcall assignments-cmd params))))))
619 (org-edit-src-code
620 nil expanded (concat "*Org-Babel Preview " (buffer-name) "[ " lang " ]*"))))
622 (defun org-babel-edit-distance (s1 s2)
623 "Return the edit (levenshtein) distance between strings S1 S2."
624 (let* ((l1 (length s1))
625 (l2 (length s2))
626 (dist (vconcat (mapcar (lambda (_) (make-vector (1+ l2) nil))
627 (number-sequence 1 (1+ l1)))))
628 (in (lambda (i j) (aref (aref dist i) j)))
629 (mmin (lambda (&rest lst) (apply #'min (remove nil lst)))))
630 (setf (aref (aref dist 0) 0) 0)
631 (dolist (i (number-sequence 1 l1))
632 (dolist (j (number-sequence 1 l2))
633 (setf (aref (aref dist i) j)
634 (+ (if (equal (aref s1 (1- i)) (aref s2 (1- j))) 0 1)
635 (funcall mmin (funcall in (1- i) j)
636 (funcall in i (1- j))
637 (funcall in (1- i) (1- j)))))))
638 (funcall in l1 l2)))
640 (defun org-babel-combine-header-arg-lists (original &rest others)
641 "Combine a number of lists of header argument names and arguments."
642 (let ((results (copy-sequence original)))
643 (dolist (new-list others)
644 (dolist (arg-pair new-list)
645 (let ((header (car arg-pair))
646 (args (cdr arg-pair)))
647 (setq results
648 (cons arg-pair (org-remove-if
649 (lambda (pair) (equal header (car pair)))
650 results))))))
651 results))
653 ;;;###autoload
654 (defun org-babel-check-src-block ()
655 "Check for misspelled header arguments in the current code block."
656 (interactive)
657 ;; TODO: report malformed code block
658 ;; TODO: report incompatible combinations of header arguments
659 ;; TODO: report uninitialized variables
660 (let ((too-close 2) ;; <- control closeness to report potential match
661 (names (mapcar #'symbol-name org-babel-header-arg-names)))
662 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg)) 1))
663 (and (org-babel-where-is-src-block-head)
664 (org-babel-parse-header-arguments
665 (org-no-properties
666 (match-string 4))))))
667 (dolist (name names)
668 (when (and (not (string= header name))
669 (<= (org-babel-edit-distance header name) too-close)
670 (not (member header names)))
671 (error "Supplied header \"%S\" is suspiciously close to \"%S\""
672 header name))))
673 (message "No suspicious header arguments found.")))
675 ;;;###autoload
676 (defun org-babel-insert-header-arg ()
677 "Insert a header argument selecting from lists of common args and values."
678 (interactive)
679 (let* ((lang (car (org-babel-get-src-block-info 'light)))
680 (lang-headers (intern (concat "org-babel-header-args:" lang)))
681 (headers (org-babel-combine-header-arg-lists
682 org-babel-common-header-args-w-values
683 (if (boundp lang-headers) (eval lang-headers) nil)))
684 (arg (org-icompleting-read
685 "Header Arg: "
686 (mapcar
687 (lambda (header-spec) (symbol-name (car header-spec)))
688 headers))))
689 (insert ":" arg)
690 (let ((vals (cdr (assoc (intern arg) headers))))
691 (when vals
692 (insert
694 (cond
695 ((eq vals :any)
696 (read-from-minibuffer "value: "))
697 ((listp vals)
698 (mapconcat
699 (lambda (group)
700 (let ((arg (org-icompleting-read
701 "value: "
702 (cons "default" (mapcar #'symbol-name group)))))
703 (if (and arg (not (string= "default" arg)))
704 (concat arg " ")
705 "")))
706 vals ""))))))))
708 ;; Add support for completing-read insertion of header arguments after ":"
709 (defun org-babel-header-arg-expand ()
710 "Call `org-babel-enter-header-arg-w-completion' in appropriate contexts."
711 (when (and (equal (char-before) ?\:) (org-babel-where-is-src-block-head))
712 (org-babel-enter-header-arg-w-completion (match-string 2))))
714 (defun org-babel-enter-header-arg-w-completion (&optional lang)
715 "Insert header argument appropriate for LANG with completion."
716 (let* ((lang-headers-var (intern (concat "org-babel-header-args:" lang)))
717 (lang-headers (when (boundp lang-headers-var) (eval lang-headers-var)))
718 (headers-w-values (org-babel-combine-header-arg-lists
719 org-babel-common-header-args-w-values lang-headers))
720 (headers (mapcar #'symbol-name (mapcar #'car headers-w-values)))
721 (header (org-completing-read "Header Arg: " headers))
722 (args (cdr (assoc (intern header) headers-w-values)))
723 (arg (when (and args (listp args))
724 (org-completing-read
725 (format "%s: " header)
726 (mapcar #'symbol-name (apply #'append args))))))
727 (insert (concat header " " (or arg "")))
728 (cons header arg)))
730 (add-hook 'org-tab-first-hook 'org-babel-header-arg-expand)
732 ;;;###autoload
733 (defun org-babel-load-in-session (&optional arg info)
734 "Load the body of the current source-code block.
735 Evaluate the header arguments for the source block before
736 entering the session. After loading the body this pops open the
737 session."
738 (interactive)
739 (let* ((info (or info (org-babel-get-src-block-info)))
740 (lang (nth 0 info))
741 (params (nth 2 info))
742 (body (setf (nth 1 info)
743 (if (org-babel-noweb-p params :eval)
744 (org-babel-expand-noweb-references info)
745 (nth 1 info))))
746 (session (cdr (assoc :session params)))
747 (dir (cdr (assoc :dir params)))
748 (default-directory
749 (or (and dir (file-name-as-directory dir)) default-directory))
750 (cmd (intern (concat "org-babel-load-session:" lang))))
751 (unless (fboundp cmd)
752 (error "No org-babel-load-session function for %s!" lang))
753 (pop-to-buffer (funcall cmd session body params))
754 (end-of-line 1)))
756 ;;;###autoload
757 (defun org-babel-initiate-session (&optional arg info)
758 "Initiate session for current code block.
759 If called with a prefix argument then resolve any variable
760 references in the header arguments and assign these variables in
761 the session. Copy the body of the code block to the kill ring."
762 (interactive "P")
763 (let* ((info (or info (org-babel-get-src-block-info (not arg))))
764 (lang (nth 0 info))
765 (body (nth 1 info))
766 (params (nth 2 info))
767 (session (cdr (assoc :session params)))
768 (dir (cdr (assoc :dir params)))
769 (default-directory
770 (or (and dir (file-name-as-directory dir)) default-directory))
771 (init-cmd (intern (format "org-babel-%s-initiate-session" lang)))
772 (prep-cmd (intern (concat "org-babel-prep-session:" lang))))
773 (if (and (stringp session) (string= session "none"))
774 (error "This block is not using a session!"))
775 (unless (fboundp init-cmd)
776 (error "No org-babel-initiate-session function for %s!" lang))
777 (with-temp-buffer (insert (org-babel-trim body))
778 (copy-region-as-kill (point-min) (point-max)))
779 (when arg
780 (unless (fboundp prep-cmd)
781 (error "No org-babel-prep-session function for %s!" lang))
782 (funcall prep-cmd session params))
783 (funcall init-cmd session params)))
785 ;;;###autoload
786 (defun org-babel-switch-to-session (&optional arg info)
787 "Switch to the session of the current code block.
788 Uses `org-babel-initiate-session' to start the session. If called
789 with a prefix argument then this is passed on to
790 `org-babel-initiate-session'."
791 (interactive "P")
792 (pop-to-buffer (org-babel-initiate-session arg info))
793 (end-of-line 1))
795 (defalias 'org-babel-pop-to-session 'org-babel-switch-to-session)
797 ;;;###autoload
798 (defun org-babel-switch-to-session-with-code (&optional arg info)
799 "Switch to code buffer and display session."
800 (interactive "P")
801 (let ((swap-windows
802 (lambda ()
803 (let ((other-window-buffer (window-buffer (next-window))))
804 (set-window-buffer (next-window) (current-buffer))
805 (set-window-buffer (selected-window) other-window-buffer))
806 (other-window 1)))
807 (info (org-babel-get-src-block-info))
808 (org-src-window-setup 'reorganize-frame))
809 (save-excursion
810 (org-babel-switch-to-session arg info))
811 (org-edit-src-code)
812 (funcall swap-windows)))
814 (defmacro org-babel-do-in-edit-buffer (&rest body)
815 "Evaluate BODY in edit buffer if there is a code block at point.
816 Return t if a code block was found at point, nil otherwise."
817 `(let ((org-src-window-setup 'switch-invisibly))
818 (when (and (org-babel-where-is-src-block-head)
819 (org-edit-src-code nil nil nil))
820 (unwind-protect (progn ,@body)
821 (if (org-bound-and-true-p org-edit-src-from-org-mode)
822 (org-edit-src-exit)))
823 t)))
824 (def-edebug-spec org-babel-do-in-edit-buffer (body))
826 (defun org-babel-do-key-sequence-in-edit-buffer (key)
827 "Read key sequence and execute the command in edit buffer.
828 Enter a key sequence to be executed in the language major-mode
829 edit buffer. For example, TAB will alter the contents of the
830 Org-mode code block according to the effect of TAB in the
831 language major-mode buffer. For languages that support
832 interactive sessions, this can be used to send code from the Org
833 buffer to the session for evaluation using the native major-mode
834 evaluation mechanisms."
835 (interactive "kEnter key-sequence to execute in edit buffer: ")
836 (org-babel-do-in-edit-buffer
837 (call-interactively
838 (key-binding (or key (read-key-sequence nil))))))
840 (defvar org-bracket-link-regexp)
841 ;;;###autoload
842 (defun org-babel-open-src-block-result (&optional re-run)
843 "If `point' is on a src block then open the results of the
844 source code block, otherwise return nil. With optional prefix
845 argument RE-RUN the source-code block is evaluated even if
846 results already exist."
847 (interactive "P")
848 (let ((info (org-babel-get-src-block-info)))
849 (when info
850 (save-excursion
851 ;; go to the results, if there aren't any then run the block
852 (goto-char (or (and (not re-run) (org-babel-where-is-src-block-result))
853 (progn (org-babel-execute-src-block)
854 (org-babel-where-is-src-block-result))))
855 (end-of-line 1)
856 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
857 ;; open the results
858 (if (looking-at org-bracket-link-regexp)
859 ;; file results
860 (org-open-at-point)
861 (let ((r (org-babel-format-result
862 (org-babel-read-result) (cdr (assoc :sep (nth 2 info))))))
863 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
864 (delete-region (point-min) (point-max))
865 (insert r)))
866 t))))
868 ;;;###autoload
869 (defmacro org-babel-map-src-blocks (file &rest body)
870 "Evaluate BODY forms on each source-block in FILE.
871 If FILE is nil evaluate BODY forms on source blocks in current
872 buffer. During evaluation of BODY the following local variables
873 are set relative to the currently matched code block.
875 full-block ------- string holding the entirety of the code block
876 beg-block -------- point at the beginning of the code block
877 end-block -------- point at the end of the matched code block
878 lang ------------- string holding the language of the code block
879 beg-lang --------- point at the beginning of the lang
880 end-lang --------- point at the end of the lang
881 switches --------- string holding the switches
882 beg-switches ----- point at the beginning of the switches
883 end-switches ----- point at the end of the switches
884 header-args ------ string holding the header-args
885 beg-header-args -- point at the beginning of the header-args
886 end-header-args -- point at the end of the header-args
887 body ------------- string holding the body of the code block
888 beg-body --------- point at the beginning of the body
889 end-body --------- point at the end of the body"
890 (declare (indent 1))
891 (let ((tempvar (make-symbol "file")))
892 `(let* ((,tempvar ,file)
893 (visited-p (or (null ,tempvar)
894 (get-file-buffer (expand-file-name ,tempvar))))
895 (point (point)) to-be-removed)
896 (save-window-excursion
897 (when ,tempvar (find-file ,tempvar))
898 (setq to-be-removed (current-buffer))
899 (goto-char (point-min))
900 (while (re-search-forward org-babel-src-block-regexp nil t)
901 (goto-char (match-beginning 0))
902 (let ((full-block (match-string 0))
903 (beg-block (match-beginning 0))
904 (end-block (match-end 0))
905 (lang (match-string 2))
906 (beg-lang (match-beginning 2))
907 (end-lang (match-end 2))
908 (switches (match-string 3))
909 (beg-switches (match-beginning 3))
910 (end-switches (match-end 3))
911 (header-args (match-string 4))
912 (beg-header-args (match-beginning 4))
913 (end-header-args (match-end 4))
914 (body (match-string 5))
915 (beg-body (match-beginning 5))
916 (end-body (match-end 5)))
917 ,@body
918 (goto-char end-block))))
919 (unless visited-p (kill-buffer to-be-removed))
920 (goto-char point))))
921 (def-edebug-spec org-babel-map-src-blocks (form body))
923 ;;;###autoload
924 (defmacro org-babel-map-inline-src-blocks (file &rest body)
925 "Evaluate BODY forms on each inline source-block in FILE.
926 If FILE is nil evaluate BODY forms on source blocks in current
927 buffer."
928 (declare (indent 1))
929 (let ((tempvar (make-symbol "file")))
930 `(let* ((,tempvar ,file)
931 (visited-p (or (null ,tempvar)
932 (get-file-buffer (expand-file-name ,tempvar))))
933 (point (point)) to-be-removed)
934 (save-window-excursion
935 (when ,tempvar (find-file ,tempvar))
936 (setq to-be-removed (current-buffer))
937 (goto-char (point-min))
938 (while (re-search-forward org-babel-inline-src-block-regexp nil t)
939 (goto-char (match-beginning 1))
940 (save-match-data ,@body)
941 (goto-char (match-end 0))))
942 (unless visited-p (kill-buffer to-be-removed))
943 (goto-char point))))
944 (def-edebug-spec org-babel-map-inline-src-blocks (form body))
946 (defvar org-babel-lob-one-liner-regexp)
947 ;;;###autoload
948 (defmacro org-babel-map-call-lines (file &rest body)
949 "Evaluate BODY forms on each call line in FILE.
950 If FILE is nil evaluate BODY forms on source blocks in current
951 buffer."
952 (declare (indent 1))
953 (let ((tempvar (make-symbol "file")))
954 `(let* ((,tempvar ,file)
955 (visited-p (or (null ,tempvar)
956 (get-file-buffer (expand-file-name ,tempvar))))
957 (point (point)) to-be-removed)
958 (save-window-excursion
959 (when ,tempvar (find-file ,tempvar))
960 (setq to-be-removed (current-buffer))
961 (goto-char (point-min))
962 (while (re-search-forward org-babel-lob-one-liner-regexp nil t)
963 (goto-char (match-beginning 1))
964 (save-match-data ,@body)
965 (goto-char (match-end 0))))
966 (unless visited-p (kill-buffer to-be-removed))
967 (goto-char point))))
968 (def-edebug-spec org-babel-map-call-lines (form body))
970 ;;;###autoload
971 (defmacro org-babel-map-executables (file &rest body)
972 (declare (indent 1))
973 (let ((tempvar (make-symbol "file"))
974 (rx (make-symbol "rx")))
975 `(let* ((,tempvar ,file)
976 (,rx (concat "\\(" org-babel-src-block-regexp
977 "\\|" org-babel-inline-src-block-regexp
978 "\\|" org-babel-lob-one-liner-regexp "\\)"))
979 (visited-p (or (null ,tempvar)
980 (get-file-buffer (expand-file-name ,tempvar))))
981 (point (point)) to-be-removed)
982 (save-window-excursion
983 (when ,tempvar (find-file ,tempvar))
984 (setq to-be-removed (current-buffer))
985 (goto-char (point-min))
986 (while (re-search-forward ,rx nil t)
987 (goto-char (match-beginning 1))
988 (when (looking-at org-babel-inline-src-block-regexp)(forward-char 1))
989 (save-match-data ,@body)
990 (goto-char (match-end 0))))
991 (unless visited-p (kill-buffer to-be-removed))
992 (goto-char point))))
993 (def-edebug-spec org-babel-map-executables (form body))
995 ;;;###autoload
996 (defun org-babel-execute-buffer (&optional arg)
997 "Execute source code blocks in a buffer.
998 Call `org-babel-execute-src-block' on every source block in
999 the current buffer."
1000 (interactive "P")
1001 (org-babel-eval-wipe-error-buffer)
1002 (org-save-outline-visibility t
1003 (org-babel-map-executables nil
1004 (if (looking-at org-babel-lob-one-liner-regexp)
1005 (org-babel-lob-execute-maybe)
1006 (org-babel-execute-src-block arg)))))
1008 ;;;###autoload
1009 (defun org-babel-execute-subtree (&optional arg)
1010 "Execute source code blocks in a subtree.
1011 Call `org-babel-execute-src-block' on every source block in
1012 the current subtree."
1013 (interactive "P")
1014 (save-restriction
1015 (save-excursion
1016 (org-narrow-to-subtree)
1017 (org-babel-execute-buffer arg)
1018 (widen))))
1020 ;;;###autoload
1021 (defun org-babel-sha1-hash (&optional info)
1022 "Generate an sha1 hash based on the value of info."
1023 (interactive)
1024 (let ((print-level nil)
1025 (info (or info (org-babel-get-src-block-info))))
1026 (setf (nth 2 info)
1027 (sort (copy-sequence (nth 2 info))
1028 (lambda (a b) (string< (car a) (car b)))))
1029 (let* ((rm (lambda (lst)
1030 (dolist (p '("replace" "silent" "append" "prepend"))
1031 (setq lst (remove p lst)))
1032 lst))
1033 (norm (lambda (arg)
1034 (let ((v (if (and (listp (cdr arg)) (null (cddr arg)))
1035 (copy-sequence (cdr arg))
1036 (cdr arg))))
1037 (when (and v (not (and (sequencep v)
1038 (not (consp v))
1039 (= (length v) 0))))
1040 (cond
1041 ((and (listp v) ; lists are sorted
1042 (member (car arg) '(:result-params)))
1043 (sort (funcall rm v) #'string<))
1044 ((and (stringp v) ; strings are sorted
1045 (member (car arg) '(:results :exports)))
1046 (mapconcat #'identity (sort (funcall rm (split-string v))
1047 #'string<) " "))
1048 (t v)))))))
1049 ((lambda (hash)
1050 (when (org-called-interactively-p 'interactive) (message hash)) hash)
1051 (let ((it (format "%s-%s"
1052 (mapconcat
1053 #'identity
1054 (delq nil (mapcar (lambda (arg)
1055 (let ((normalized (funcall norm arg)))
1056 (when normalized
1057 (format "%S" normalized))))
1058 (nth 2 info))) ":")
1059 (nth 1 info))))
1060 (sha1 it))))))
1062 (defun org-babel-current-result-hash ()
1063 "Return the current in-buffer hash."
1064 (org-babel-where-is-src-block-result)
1065 (org-no-properties (match-string 3)))
1067 (defun org-babel-set-current-result-hash (hash)
1068 "Set the current in-buffer hash to HASH."
1069 (org-babel-where-is-src-block-result)
1070 (save-excursion (goto-char (match-beginning 3))
1071 ;; (mapc #'delete-overlay (overlays-at (point)))
1072 (replace-match hash nil nil nil 3)
1073 (org-babel-hide-hash)))
1075 (defun org-babel-hide-hash ()
1076 "Hide the hash in the current results line.
1077 Only the initial `org-babel-hash-show' characters of the hash
1078 will remain visible."
1079 (add-to-invisibility-spec '(org-babel-hide-hash . t))
1080 (save-excursion
1081 (when (and (re-search-forward org-babel-result-regexp nil t)
1082 (match-string 3))
1083 (let* ((start (match-beginning 3))
1084 (hide-start (+ org-babel-hash-show start))
1085 (end (match-end 3))
1086 (hash (match-string 3))
1087 ov1 ov2)
1088 (setq ov1 (make-overlay start hide-start))
1089 (setq ov2 (make-overlay hide-start end))
1090 (overlay-put ov2 'invisible 'org-babel-hide-hash)
1091 (overlay-put ov1 'babel-hash hash)))))
1093 (defun org-babel-hide-all-hashes ()
1094 "Hide the hash in the current buffer.
1095 Only the initial `org-babel-hash-show' characters of each hash
1096 will remain visible. This function should be called as part of
1097 the `org-mode-hook'."
1098 (save-excursion
1099 (while (re-search-forward org-babel-result-regexp nil t)
1100 (goto-char (match-beginning 0))
1101 (org-babel-hide-hash)
1102 (goto-char (match-end 0)))))
1103 (add-hook 'org-mode-hook 'org-babel-hide-all-hashes)
1105 (defun org-babel-hash-at-point (&optional point)
1106 "Return the value of the hash at POINT.
1107 The hash is also added as the last element of the kill ring.
1108 This can be called with C-c C-c."
1109 (interactive)
1110 (let ((hash (car (delq nil (mapcar
1111 (lambda (ol) (overlay-get ol 'babel-hash))
1112 (overlays-at (or point (point))))))))
1113 (when hash (kill-new hash) (message hash))))
1114 (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-hash-at-point)
1116 (defun org-babel-result-hide-spec ()
1117 "Hide portions of results lines.
1118 Add `org-babel-hide-result' as an invisibility spec for hiding
1119 portions of results lines."
1120 (add-to-invisibility-spec '(org-babel-hide-result . t)))
1121 (add-hook 'org-mode-hook 'org-babel-result-hide-spec)
1123 (defvar org-babel-hide-result-overlays nil
1124 "Overlays hiding results.")
1126 (defun org-babel-result-hide-all ()
1127 "Fold all results in the current buffer."
1128 (interactive)
1129 (org-babel-show-result-all)
1130 (save-excursion
1131 (while (re-search-forward org-babel-result-regexp nil t)
1132 (save-excursion (goto-char (match-beginning 0))
1133 (org-babel-hide-result-toggle-maybe)))))
1135 (defun org-babel-show-result-all ()
1136 "Unfold all results in the current buffer."
1137 (mapc 'delete-overlay org-babel-hide-result-overlays)
1138 (setq org-babel-hide-result-overlays nil))
1140 ;;;###autoload
1141 (defun org-babel-hide-result-toggle-maybe ()
1142 "Toggle visibility of result at point."
1143 (interactive)
1144 (let ((case-fold-search t))
1145 (if (save-excursion
1146 (beginning-of-line 1)
1147 (looking-at org-babel-result-regexp))
1148 (progn (org-babel-hide-result-toggle)
1149 t) ;; to signal that we took action
1150 nil))) ;; to signal that we did not
1152 (defun org-babel-hide-result-toggle (&optional force)
1153 "Toggle the visibility of the current result."
1154 (interactive)
1155 (save-excursion
1156 (beginning-of-line)
1157 (if (re-search-forward org-babel-result-regexp nil t)
1158 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
1159 (end (progn
1160 (while (looking-at org-babel-multi-line-header-regexp)
1161 (forward-line 1))
1162 (goto-char (- (org-babel-result-end) 1)) (point)))
1164 (if (memq t (mapcar (lambda (overlay)
1165 (eq (overlay-get overlay 'invisible)
1166 'org-babel-hide-result))
1167 (overlays-at start)))
1168 (if (or (not force) (eq force 'off))
1169 (mapc (lambda (ov)
1170 (when (member ov org-babel-hide-result-overlays)
1171 (setq org-babel-hide-result-overlays
1172 (delq ov org-babel-hide-result-overlays)))
1173 (when (eq (overlay-get ov 'invisible)
1174 'org-babel-hide-result)
1175 (delete-overlay ov)))
1176 (overlays-at start)))
1177 (setq ov (make-overlay start end))
1178 (overlay-put ov 'invisible 'org-babel-hide-result)
1179 ;; make the block accessible to isearch
1180 (overlay-put
1181 ov 'isearch-open-invisible
1182 (lambda (ov)
1183 (when (member ov org-babel-hide-result-overlays)
1184 (setq org-babel-hide-result-overlays
1185 (delq ov org-babel-hide-result-overlays)))
1186 (when (eq (overlay-get ov 'invisible)
1187 'org-babel-hide-result)
1188 (delete-overlay ov))))
1189 (push ov org-babel-hide-result-overlays)))
1190 (error "Not looking at a result line"))))
1192 ;; org-tab-after-check-for-cycling-hook
1193 (add-hook 'org-tab-first-hook 'org-babel-hide-result-toggle-maybe)
1194 ;; Remove overlays when changing major mode
1195 (add-hook 'org-mode-hook
1196 (lambda () (org-add-hook 'change-major-mode-hook
1197 'org-babel-show-result-all 'append 'local)))
1199 (defvar org-file-properties)
1200 (defun org-babel-params-from-properties (&optional lang)
1201 "Retrieve parameters specified as properties.
1202 Return an association list of any source block params which
1203 may be specified in the properties of the current outline entry."
1204 (save-match-data
1205 (let (val sym)
1206 (org-babel-parse-multiple-vars
1207 (delq nil
1208 (mapcar
1209 (lambda (header-arg)
1210 (and (setq val (org-entry-get (point) header-arg t))
1211 (cons (intern (concat ":" header-arg))
1212 (org-babel-read val))))
1213 (mapcar
1214 #'symbol-name
1215 (mapcar
1216 #'car
1217 (org-babel-combine-header-arg-lists
1218 org-babel-common-header-args-w-values
1219 (progn
1220 (setq sym (intern (concat "org-babel-header-args:" lang)))
1221 (and (boundp sym) (eval sym))))))))))))
1223 (defvar org-src-preserve-indentation)
1224 (defun org-babel-parse-src-block-match ()
1225 "Parse the results from a match of the `org-babel-src-block-regexp'."
1226 (let* ((block-indentation (length (match-string 1)))
1227 (lang (org-no-properties (match-string 2)))
1228 (lang-headers (intern (concat "org-babel-default-header-args:" lang)))
1229 (switches (match-string 3))
1230 (body (org-no-properties
1231 (let* ((body (match-string 5))
1232 (sub-length (- (length body) 1)))
1233 (if (and (> sub-length 0)
1234 (string= "\n" (substring body sub-length)))
1235 (substring body 0 sub-length)
1236 (or body "")))))
1237 (preserve-indentation (or org-src-preserve-indentation
1238 (save-match-data
1239 (string-match "-i\\>" switches)))))
1240 (list lang
1241 ;; get block body less properties, protective commas, and indentation
1242 (with-temp-buffer
1243 (save-match-data
1244 (insert (org-babel-strip-protective-commas body lang))
1245 (unless preserve-indentation (org-do-remove-indentation))
1246 (buffer-string)))
1247 (org-babel-merge-params
1248 org-babel-default-header-args
1249 (org-babel-params-from-properties lang)
1250 (if (boundp lang-headers) (eval lang-headers) nil)
1251 (org-babel-parse-header-arguments
1252 (org-no-properties (or (match-string 4) ""))))
1253 switches
1254 block-indentation)))
1256 (defun org-babel-parse-inline-src-block-match ()
1257 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
1258 (let* ((lang (org-no-properties (match-string 2)))
1259 (lang-headers (intern (concat "org-babel-default-header-args:" lang))))
1260 (list lang
1261 (org-babel-strip-protective-commas
1262 (org-no-properties (match-string 5)) lang)
1263 (org-babel-merge-params
1264 org-babel-default-inline-header-args
1265 (org-babel-params-from-properties lang)
1266 (if (boundp lang-headers) (eval lang-headers) nil)
1267 (org-babel-parse-header-arguments
1268 (org-no-properties (or (match-string 4) "")))))))
1270 (defun org-babel-balanced-split (string alts)
1271 "Split STRING on instances of ALTS.
1272 ALTS is a cons of two character options where each option may be
1273 either the numeric code of a single character or a list of
1274 character alternatives. For example to split on balanced
1275 instances of \"[ \t]:\" set ALTS to '((32 9) . 58)."
1276 (let* ((matches (lambda (ch spec) (if (listp spec) (member ch spec) (equal spec ch))))
1277 (matched (lambda (ch last)
1278 (if (consp alts)
1279 (and (funcall matches ch (cdr alts))
1280 (funcall matches last (car alts)))
1281 (funcall matches ch alts))))
1282 (balance 0) (last 0)
1283 quote partial lst)
1284 (mapc (lambda (ch) ; split on [], (), "" balanced instances of [ \t]:
1285 (setq balance (+ balance
1286 (cond ((or (equal 91 ch) (equal 40 ch)) 1)
1287 ((or (equal 93 ch) (equal 41 ch)) -1)
1288 (t 0))))
1289 (when (and (equal 34 ch) (not (equal 92 last)))
1290 (setq quote (not quote)))
1291 (setq partial (cons ch partial))
1292 (when (and (= balance 0) (not quote) (funcall matched ch last))
1293 (setq lst (cons (apply #'string (nreverse
1294 (if (consp alts)
1295 (cddr partial)
1296 (cdr partial))))
1297 lst))
1298 (setq partial nil))
1299 (setq last ch))
1300 (string-to-list string))
1301 (nreverse (cons (apply #'string (nreverse partial)) lst))))
1303 (defun org-babel-join-splits-near-ch (ch list)
1304 "Join splits where \"=\" is on either end of the split."
1305 (let ((last= (lambda (str) (= ch (aref str (1- (length str))))))
1306 (first= (lambda (str) (= ch (aref str 0)))))
1307 (reverse
1308 (org-reduce (lambda (acc el)
1309 (let ((head (car acc)))
1310 (if (and head (or (funcall last= head) (funcall first= el)))
1311 (cons (concat head el) (cdr acc))
1312 (cons el acc))))
1313 list :initial-value nil))))
1315 (defun org-babel-parse-header-arguments (arg-string)
1316 "Parse a string of header arguments returning an alist."
1317 (when (> (length arg-string) 0)
1318 (org-babel-parse-multiple-vars
1319 (delq nil
1320 (mapcar
1321 (lambda (arg)
1322 (if (string-match
1323 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1324 arg)
1325 (cons (intern (match-string 1 arg))
1326 (org-babel-read (org-babel-chomp (match-string 2 arg))))
1327 (cons (intern (org-babel-chomp arg)) nil)))
1328 ((lambda (raw)
1329 (cons (car raw) (mapcar (lambda (r) (concat ":" r)) (cdr raw))))
1330 (org-babel-balanced-split arg-string '((32 9) . 58))))))))
1332 (defun org-babel-parse-multiple-vars (header-arguments)
1333 "Expand multiple variable assignments behind a single :var keyword.
1335 This allows expression of multiple variables with one :var as
1336 shown below.
1338 #+PROPERTY: var foo=1, bar=2"
1339 (let (results)
1340 (mapc (lambda (pair)
1341 (if (eq (car pair) :var)
1342 (mapcar (lambda (v) (push (cons :var (org-babel-trim v)) results))
1343 (org-babel-join-splits-near-ch
1344 61 (org-babel-balanced-split (cdr pair) 32)))
1345 (push pair results)))
1346 header-arguments)
1347 (nreverse results)))
1349 (defun org-babel-process-params (params)
1350 "Expand variables in PARAMS and add summary parameters."
1351 (let* ((processed-vars (mapcar (lambda (el)
1352 (if (consp (cdr el))
1353 (cdr el)
1354 (org-babel-ref-parse (cdr el))))
1355 (org-babel-get-header params :var)))
1356 (vars-and-names (if (and (assoc :colname-names params)
1357 (assoc :rowname-names params))
1358 (list processed-vars)
1359 (org-babel-disassemble-tables
1360 processed-vars
1361 (cdr (assoc :hlines params))
1362 (cdr (assoc :colnames params))
1363 (cdr (assoc :rownames params)))))
1364 (raw-result (or (cdr (assoc :results params)) ""))
1365 (result-params (append
1366 (split-string (if (stringp raw-result)
1367 raw-result
1368 (eval raw-result)))
1369 (cdr (assoc :result-params params)))))
1370 (append
1371 (mapcar (lambda (var) (cons :var var)) (car vars-and-names))
1372 (list
1373 (cons :colname-names (or (cdr (assoc :colname-names params))
1374 (cadr vars-and-names)))
1375 (cons :rowname-names (or (cdr (assoc :rowname-names params))
1376 (caddr vars-and-names)))
1377 (cons :result-params result-params)
1378 (cons :result-type (cond ((member "output" result-params) 'output)
1379 ((member "value" result-params) 'value)
1380 (t 'value))))
1381 (org-babel-get-header params :var 'other))))
1383 ;; row and column names
1384 (defun org-babel-del-hlines (table)
1385 "Remove all 'hlines from TABLE."
1386 (remove 'hline table))
1388 (defun org-babel-get-colnames (table)
1389 "Return the column names of TABLE.
1390 Return a cons cell, the `car' of which contains the TABLE less
1391 colnames, and the `cdr' of which contains a list of the column
1392 names."
1393 (if (equal 'hline (nth 1 table))
1394 (cons (cddr table) (car table))
1395 (cons (cdr table) (car table))))
1397 (defun org-babel-get-rownames (table)
1398 "Return the row names of TABLE.
1399 Return a cons cell, the `car' of which contains the TABLE less
1400 colnames, and the `cdr' of which contains a list of the column
1401 names. Note: this function removes any hlines in TABLE."
1402 (let* ((trans (lambda (table) (apply #'mapcar* #'list table)))
1403 (width (apply 'max
1404 (mapcar (lambda (el) (if (listp el) (length el) 0)) table)))
1405 (table (funcall trans (mapcar (lambda (row)
1406 (if (not (equal row 'hline))
1408 (setq row '())
1409 (dotimes (n width)
1410 (setq row (cons 'hline row)))
1411 row))
1412 table))))
1413 (cons (mapcar (lambda (row) (if (equal (car row) 'hline) 'hline row))
1414 (funcall trans (cdr table)))
1415 (remove 'hline (car table)))))
1417 (defun org-babel-put-colnames (table colnames)
1418 "Add COLNAMES to TABLE if they exist."
1419 (if colnames (apply 'list colnames 'hline table) table))
1421 (defun org-babel-put-rownames (table rownames)
1422 "Add ROWNAMES to TABLE if they exist."
1423 (if rownames
1424 (mapcar (lambda (row)
1425 (if (listp row)
1426 (cons (or (pop rownames) "") row)
1427 row)) table)
1428 table))
1430 (defun org-babel-pick-name (names selector)
1431 "Select one out of an alist of row or column names.
1432 SELECTOR can be either a list of names in which case those names
1433 will be returned directly, or an index into the list NAMES in
1434 which case the indexed names will be return."
1435 (if (listp selector)
1436 selector
1437 (when names
1438 (if (and selector (symbolp selector) (not (equal t selector)))
1439 (cdr (assoc selector names))
1440 (if (integerp selector)
1441 (nth (- selector 1) names)
1442 (cdr (car (last names))))))))
1444 (defun org-babel-disassemble-tables (vars hlines colnames rownames)
1445 "Parse tables for further processing.
1446 Process the variables in VARS according to the HLINES,
1447 ROWNAMES and COLNAMES header arguments. Return a list consisting
1448 of the vars, cnames and rnames."
1449 (let (cnames rnames)
1450 (list
1451 (mapcar
1452 (lambda (var)
1453 (when (listp (cdr var))
1454 (when (and (not (equal colnames "no"))
1455 (or colnames (and (equal (nth 1 (cdr var)) 'hline)
1456 (not (member 'hline (cddr (cdr var)))))))
1457 (let ((both (org-babel-get-colnames (cdr var))))
1458 (setq cnames (cons (cons (car var) (cdr both))
1459 cnames))
1460 (setq var (cons (car var) (car both)))))
1461 (when (and rownames (not (equal rownames "no")))
1462 (let ((both (org-babel-get-rownames (cdr var))))
1463 (setq rnames (cons (cons (car var) (cdr both))
1464 rnames))
1465 (setq var (cons (car var) (car both)))))
1466 (when (and hlines (not (equal hlines "yes")))
1467 (setq var (cons (car var) (org-babel-del-hlines (cdr var))))))
1468 var)
1469 vars)
1470 (reverse cnames) (reverse rnames))))
1472 (defun org-babel-reassemble-table (table colnames rownames)
1473 "Add column and row names to a table.
1474 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1475 to the table for reinsertion to org-mode."
1476 (if (listp table)
1477 ((lambda (table)
1478 (if (and colnames (listp (car table)) (= (length (car table))
1479 (length colnames)))
1480 (org-babel-put-colnames table colnames) table))
1481 (if (and rownames (= (length table) (length rownames)))
1482 (org-babel-put-rownames table rownames) table))
1483 table))
1485 (defun org-babel-where-is-src-block-head ()
1486 "Find where the current source block begins.
1487 Return the point at the beginning of the current source
1488 block. Specifically at the beginning of the #+BEGIN_SRC line.
1489 If the point is not on a source block then return nil."
1490 (let ((initial (point)) (case-fold-search t) top bottom)
1492 (save-excursion ;; on a source name line or a #+header line
1493 (beginning-of-line 1)
1494 (and (or (looking-at org-babel-src-name-regexp)
1495 (looking-at org-babel-multi-line-header-regexp))
1496 (progn
1497 (while (and (forward-line 1)
1498 (or (looking-at org-babel-src-name-regexp)
1499 (looking-at org-babel-multi-line-header-regexp))))
1500 (looking-at org-babel-src-block-regexp))
1501 (point)))
1502 (save-excursion ;; on a #+begin_src line
1503 (beginning-of-line 1)
1504 (and (looking-at org-babel-src-block-regexp)
1505 (point)))
1506 (save-excursion ;; inside a src block
1507 (and
1508 (re-search-backward "^[ \t]*#\\+begin_src" nil t) (setq top (point))
1509 (re-search-forward "^[ \t]*#\\+end_src" nil t) (setq bottom (point))
1510 (< top initial) (< initial bottom)
1511 (progn (goto-char top) (beginning-of-line 1)
1512 (looking-at org-babel-src-block-regexp))
1513 (point))))))
1515 ;;;###autoload
1516 (defun org-babel-goto-src-block-head ()
1517 "Go to the beginning of the current code block."
1518 (interactive)
1519 ((lambda (head)
1520 (if head (goto-char head) (error "Not currently in a code block")))
1521 (org-babel-where-is-src-block-head)))
1523 ;;;###autoload
1524 (defun org-babel-goto-named-src-block (name)
1525 "Go to a named source-code block."
1526 (interactive
1527 (let ((completion-ignore-case t)
1528 (case-fold-search t)
1529 (under-point (thing-at-point 'line)))
1530 (list (org-icompleting-read
1531 "source-block name: " (org-babel-src-block-names) nil t
1532 (cond
1533 ;; noweb
1534 ((string-match (org-babel-noweb-wrap) under-point)
1535 (let ((block-name (match-string 1 under-point)))
1536 (string-match "[^(]*" block-name)
1537 (match-string 0 block-name)))
1538 ;; #+call:
1539 ((string-match org-babel-lob-one-liner-regexp under-point)
1540 (let ((source-info (car (org-babel-lob-get-info))))
1541 (if (string-match "^\\([^\\[]+?\\)\\(\\[.*\\]\\)?(" source-info)
1542 (let ((source-name (match-string 1 source-info)))
1543 source-name))))
1544 ;; #+results:
1545 ((string-match (concat "#\\+" org-babel-results-keyword
1546 "\\:\s+\\([^\\(]*\\)") under-point)
1547 (match-string 1 under-point))
1548 ;; symbol-at-point
1549 ((and (thing-at-point 'symbol))
1550 (org-babel-find-named-block (thing-at-point 'symbol))
1551 (thing-at-point 'symbol))
1552 (""))))))
1553 (let ((point (org-babel-find-named-block name)))
1554 (if point
1555 ;; taken from `org-open-at-point'
1556 (progn (org-mark-ring-push) (goto-char point) (org-show-context))
1557 (message "source-code block '%s' not found in this buffer" name))))
1559 (defun org-babel-find-named-block (name)
1560 "Find a named source-code block.
1561 Return the location of the source block identified by source
1562 NAME, or nil if no such block exists. Set match data according to
1563 org-babel-named-src-block-regexp."
1564 (save-excursion
1565 (let ((case-fold-search t)
1566 (regexp (org-babel-named-src-block-regexp-for-name name)) msg)
1567 (goto-char (point-min))
1568 (when (or (re-search-forward regexp nil t)
1569 (re-search-backward regexp nil t))
1570 (match-beginning 0)))))
1572 (defun org-babel-src-block-names (&optional file)
1573 "Returns the names of source blocks in FILE or the current buffer."
1574 (save-excursion
1575 (when file (find-file file)) (goto-char (point-min))
1576 (let ((case-fold-search t) names)
1577 (while (re-search-forward org-babel-src-name-w-name-regexp nil t)
1578 (setq names (cons (match-string 3) names)))
1579 names)))
1581 ;;;###autoload
1582 (defun org-babel-goto-named-result (name)
1583 "Go to a named result."
1584 (interactive
1585 (let ((completion-ignore-case t))
1586 (list (org-icompleting-read "source-block name: "
1587 (org-babel-result-names) nil t))))
1588 (let ((point (org-babel-find-named-result name)))
1589 (if point
1590 ;; taken from `org-open-at-point'
1591 (progn (goto-char point) (org-show-context))
1592 (message "result '%s' not found in this buffer" name))))
1594 (defun org-babel-find-named-result (name &optional point)
1595 "Find a named result.
1596 Return the location of the result named NAME in the current
1597 buffer or nil if no such result exists."
1598 (save-excursion
1599 (let ((case-fold-search t))
1600 (goto-char (or point (point-min)))
1601 (catch 'is-a-code-block
1602 (when (re-search-forward
1603 (concat org-babel-result-regexp
1604 "[ \t]" (regexp-quote name) "[ \t]*[\n\f\v\r]") nil t)
1605 (when (and (string= "name" (downcase (match-string 1)))
1606 (or (beginning-of-line 1)
1607 (looking-at org-babel-src-block-regexp)
1608 (looking-at org-babel-multi-line-header-regexp)))
1609 (throw 'is-a-code-block (org-babel-find-named-result name (point))))
1610 (beginning-of-line 0) (point))))))
1612 (defun org-babel-result-names (&optional file)
1613 "Returns the names of results in FILE or the current buffer."
1614 (save-excursion
1615 (when file (find-file file)) (goto-char (point-min))
1616 (let ((case-fold-search t) names)
1617 (while (re-search-forward org-babel-result-w-name-regexp nil t)
1618 (setq names (cons (match-string 4) names)))
1619 names)))
1621 ;;;###autoload
1622 (defun org-babel-next-src-block (&optional arg)
1623 "Jump to the next source block.
1624 With optional prefix argument ARG, jump forward ARG many source blocks."
1625 (interactive "P")
1626 (when (looking-at org-babel-src-block-regexp) (forward-char 1))
1627 (condition-case nil
1628 (re-search-forward org-babel-src-block-regexp nil nil (or arg 1))
1629 (error (error "No further code blocks")))
1630 (goto-char (match-beginning 0)) (org-show-context))
1632 ;;;###autoload
1633 (defun org-babel-previous-src-block (&optional arg)
1634 "Jump to the previous source block.
1635 With optional prefix argument ARG, jump backward ARG many source blocks."
1636 (interactive "P")
1637 (condition-case nil
1638 (re-search-backward org-babel-src-block-regexp nil nil (or arg 1))
1639 (error (error "No previous code blocks")))
1640 (goto-char (match-beginning 0)) (org-show-context))
1642 (defvar org-babel-load-languages)
1644 ;;;###autoload
1645 (defun org-babel-mark-block ()
1646 "Mark current src block."
1647 (interactive)
1648 ((lambda (head)
1649 (when head
1650 (save-excursion
1651 (goto-char head)
1652 (looking-at org-babel-src-block-regexp))
1653 (push-mark (match-end 5) nil t)
1654 (goto-char (match-beginning 5))))
1655 (org-babel-where-is-src-block-head)))
1657 (defun org-babel-demarcate-block (&optional arg)
1658 "Wrap or split the code in the region or on the point.
1659 When called from inside of a code block the current block is
1660 split. When called from outside of a code block a new code block
1661 is created. In both cases if the region is demarcated and if the
1662 region is not active then the point is demarcated."
1663 (interactive "P")
1664 (let ((info (org-babel-get-src-block-info 'light))
1665 (headers (progn (org-babel-where-is-src-block-head)
1666 (match-string 4)))
1667 (stars (concat (make-string (or (org-current-level) 1) ?*) " ")))
1668 (if info
1669 (mapc
1670 (lambda (place)
1671 (save-excursion
1672 (goto-char place)
1673 (let ((lang (nth 0 info))
1674 (indent (make-string (nth 5 info) ? )))
1675 (when (string-match "^[[:space:]]*$"
1676 (buffer-substring (point-at-bol)
1677 (point-at-eol)))
1678 (delete-region (point-at-bol) (point-at-eol)))
1679 (insert (concat
1680 (if (looking-at "^") "" "\n")
1681 indent "#+end_src\n"
1682 (if arg stars indent) "\n"
1683 indent "#+begin_src " lang
1684 (if (> (length headers) 1)
1685 (concat " " headers) headers)
1686 (if (looking-at "[\n\r]")
1688 (concat "\n" (make-string (current-column) ? )))))))
1689 (move-end-of-line 2))
1690 (sort (if (org-region-active-p) (list (mark) (point)) (list (point))) #'>))
1691 (let ((start (point))
1692 (lang (org-icompleting-read "Lang: "
1693 (mapcar (lambda (el) (symbol-name (car el)))
1694 org-babel-load-languages)))
1695 (body (delete-and-extract-region
1696 (if (org-region-active-p) (mark) (point)) (point))))
1697 (insert (concat (if (looking-at "^") "" "\n")
1698 (if arg (concat stars "\n") "")
1699 "#+begin_src " lang "\n"
1700 body
1701 (if (or (= (length body) 0)
1702 (string-match "[\r\n]$" body)) "" "\n")
1703 "#+end_src\n"))
1704 (goto-char start) (move-end-of-line 1)))))
1706 (defvar org-babel-lob-one-liner-regexp)
1707 (defun org-babel-where-is-src-block-result (&optional insert info hash indent)
1708 "Find where the current source block results begin.
1709 Return the point at the beginning of the result of the current
1710 source block. Specifically at the beginning of the results line.
1711 If no result exists for this block then create a results line
1712 following the source block."
1713 (save-excursion
1714 (let* ((case-fold-search t)
1715 (on-lob-line (save-excursion
1716 (beginning-of-line 1)
1717 (looking-at org-babel-lob-one-liner-regexp)))
1718 (inlinep (when (org-babel-get-inline-src-block-matches)
1719 (match-end 0)))
1720 (name (if on-lob-line
1721 (mapconcat #'identity (butlast (org-babel-lob-get-info)) "")
1722 (nth 4 (or info (org-babel-get-src-block-info 'light)))))
1723 (head (unless on-lob-line (org-babel-where-is-src-block-head)))
1724 found beg end)
1725 (when head (goto-char head))
1726 (setq
1727 found ;; was there a result (before we potentially insert one)
1729 inlinep
1730 (and
1731 ;; named results:
1732 ;; - return t if it is found, else return nil
1733 ;; - if it does not need to be rebuilt, then don't set end
1734 ;; - if it does need to be rebuilt then do set end
1735 name (setq beg (org-babel-find-named-result name))
1736 (prog1 beg
1737 (when (and hash (not (string= hash (match-string 3))))
1738 (goto-char beg) (setq end beg) ;; beginning of result
1739 (forward-line 1)
1740 (delete-region end (org-babel-result-end)) nil)))
1741 (and
1742 ;; unnamed results:
1743 ;; - return t if it is found, else return nil
1744 ;; - if it is found, and the hash doesn't match, delete and set end
1745 (or on-lob-line (re-search-forward "^[ \t]*#\\+end_src" nil t))
1746 (progn (end-of-line 1)
1747 (if (eobp) (insert "\n") (forward-char 1))
1748 (setq end (point))
1749 (or (and (not name)
1750 (progn ;; unnamed results line already exists
1751 (re-search-forward "[^ \f\t\n\r\v]" nil t)
1752 (beginning-of-line 1)
1753 (looking-at
1754 (concat org-babel-result-regexp "\n")))
1755 (prog1 (point)
1756 ;; must remove and rebuild if hash!=old-hash
1757 (if (and hash (not (string= hash (match-string 3))))
1758 (prog1 nil
1759 (forward-line 1)
1760 (delete-region
1761 end (org-babel-result-end)))
1762 (setq end nil)))))))))
1763 (if (and insert end)
1764 (progn
1765 (goto-char end)
1766 (unless beg
1767 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1768 (insert (concat
1769 (if indent
1770 (mapconcat
1771 (lambda (el) " ")
1772 (org-number-sequence 1 indent) "")
1774 "#+" org-babel-results-keyword
1775 (when hash (concat "["hash"]"))
1777 (when name (concat " " name)) "\n"))
1778 (unless beg (insert "\n") (backward-char))
1779 (beginning-of-line 0)
1780 (if hash (org-babel-hide-hash))
1781 (point))
1782 found))))
1784 (defvar org-block-regexp)
1785 (defun org-babel-read-result ()
1786 "Read the result at `point' into emacs-lisp."
1787 (let ((case-fold-search t) result-string)
1788 (cond
1789 ((org-at-table-p) (org-babel-read-table))
1790 ((org-at-item-p) (org-babel-read-list))
1791 ((looking-at org-bracket-link-regexp) (org-babel-read-link))
1792 ((looking-at org-block-regexp) (org-babel-trim (match-string 4)))
1793 ((looking-at "^[ \t]*: ")
1794 (setq result-string
1795 (org-babel-trim
1796 (mapconcat (lambda (line)
1797 (if (and (> (length line) 1)
1798 (string-match "^[ \t]*: \\(.+\\)" line))
1799 (match-string 1 line)
1800 line))
1801 (split-string
1802 (buffer-substring
1803 (point) (org-babel-result-end)) "[\r\n]+")
1804 "\n")))
1805 (or (org-babel-number-p result-string) result-string))
1806 ((looking-at org-babel-result-regexp)
1807 (save-excursion (forward-line 1) (org-babel-read-result))))))
1809 (defun org-babel-read-table ()
1810 "Read the table at `point' into emacs-lisp."
1811 (mapcar (lambda (row)
1812 (if (and (symbolp row) (equal row 'hline)) row
1813 (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval)) row)))
1814 (org-table-to-lisp)))
1816 (defun org-babel-read-list ()
1817 "Read the list at `point' into emacs-lisp."
1818 (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval))
1819 (mapcar #'cadr (cdr (org-list-parse-list)))))
1821 (defvar org-link-types-re)
1822 (defun org-babel-read-link ()
1823 "Read the link at `point' into emacs-lisp.
1824 If the path of the link is a file path it is expanded using
1825 `expand-file-name'."
1826 (let* ((case-fold-search t)
1827 (raw (and (looking-at org-bracket-link-regexp)
1828 (org-no-properties (match-string 1))))
1829 (type (and (string-match org-link-types-re raw)
1830 (match-string 1 raw))))
1831 (cond
1832 ((not type) (expand-file-name raw))
1833 ((string= type "file")
1834 (and (string-match "file\\(.*\\):\\(.+\\)" raw)
1835 (expand-file-name (match-string 2 raw))))
1836 (t raw))))
1838 (defun org-babel-format-result (result &optional sep)
1839 "Format RESULT for writing to file."
1840 (let ((echo-res (lambda (r) (if (stringp r) r (format "%S" r)))))
1841 (if (listp result)
1842 ;; table result
1843 (orgtbl-to-generic
1844 result (list :sep (or sep "\t") :fmt echo-res))
1845 ;; scalar result
1846 (funcall echo-res result))))
1848 (defun org-babel-insert-result
1849 (result &optional result-params info hash indent lang)
1850 "Insert RESULT into the current buffer.
1851 By default RESULT is inserted after the end of the
1852 current source block. With optional argument RESULT-PARAMS
1853 controls insertion of results in the org-mode file.
1854 RESULT-PARAMS can take the following values:
1856 replace - (default option) insert results after the source block
1857 replacing any previously inserted results
1859 silent -- no results are inserted
1861 file ---- the results are interpreted as a file path, and are
1862 inserted into the buffer using the Org-mode file syntax
1864 list ---- the results are interpreted as an Org-mode list.
1866 raw ----- results are added directly to the Org-mode file. This
1867 is a good option if you code block will output org-mode
1868 formatted text.
1870 drawer -- results are added directly to the Org-mode file as with
1871 \"raw\", but are wrapped in a RESULTS drawer, allowing
1872 them to later be replaced or removed automatically.
1874 org ----- results are added inside of a \"#+BEGIN_SRC org\" block.
1875 They are not comma-escaped when inserted, but Org syntax
1876 here will be discarded when exporting the file.
1878 html ---- results are added inside of a #+BEGIN_HTML block. This
1879 is a good option if you code block will output html
1880 formatted text.
1882 latex --- results are added inside of a #+BEGIN_LATEX block.
1883 This is a good option if you code block will output
1884 latex formatted text.
1886 code ---- the results are extracted in the syntax of the source
1887 code of the language being evaluated and are added
1888 inside of a #+BEGIN_SRC block with the source-code
1889 language set appropriately. Note this relies on the
1890 optional LANG argument."
1891 (save-restriction (widen)
1892 (if (stringp result)
1893 (progn
1894 (setq result (org-no-properties result))
1895 (when (member "file" result-params)
1896 (setq result (org-babel-result-to-file
1897 result (when (assoc :file-desc (nth 2 info))
1898 (or (cdr (assoc :file-desc (nth 2 info)))
1899 result))))))
1900 (unless (listp result) (setq result (format "%S" result))))
1901 (if (and result-params (member "silent" result-params))
1902 (progn
1903 (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
1904 result)
1905 (save-excursion
1906 (let* ((inlinep
1907 (save-excursion
1908 (when (or (org-babel-get-inline-src-block-matches)
1909 (org-babel-get-lob-one-liner-matches))
1910 (goto-char (match-end 0))
1911 (insert (if (listp result) "\n" " "))
1912 (point))))
1913 (existing-result (unless inlinep
1914 (org-babel-where-is-src-block-result
1915 t info hash indent)))
1916 (results-switches
1917 (cdr (assoc :results_switches (nth 2 info))))
1918 beg end)
1919 (when (and (stringp result) ; ensure results end in a newline
1920 (not inlinep)
1921 (> (length result) 0)
1922 (not (or (string-equal (substring result -1) "\n")
1923 (string-equal (substring result -1) "\r"))))
1924 (setq result (concat result "\n")))
1925 (if (not existing-result)
1926 (setq beg (or inlinep (point)))
1927 (goto-char existing-result)
1928 (save-excursion
1929 (re-search-forward "#" nil t)
1930 (setq indent (- (current-column) 1)))
1931 (forward-line 1)
1932 (setq beg (point))
1933 (cond
1934 ((member "replace" result-params)
1935 (delete-region (point) (org-babel-result-end)))
1936 ((member "append" result-params)
1937 (goto-char (org-babel-result-end)) (setq beg (point-marker)))
1938 ((member "prepend" result-params)))) ; already there
1939 (setq results-switches
1940 (if results-switches (concat " " results-switches) ""))
1941 (let ((wrap (lambda (start finish &optional escape)
1942 (goto-char end) (insert (concat finish "\n"))
1943 (goto-char beg) (insert (concat start "\n"))
1944 (if escape (org-add-protective-commas (point) end))
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 "org" result-params)
1991 (funcall wrap "#+BEGIN_SRC org" "#+END_SRC" 'escape))
1992 ((member "code" result-params)
1993 (funcall wrap (format "#+BEGIN_SRC %s%s" (or lang "none") results-switches)
1994 "#+END_SRC"))
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