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