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