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