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