ox-html: Fix stack overflow in regexp matching
[org-mode.git] / lisp / ob-core.el
blob3278bf91a37512931d1c6de801be429e72439ca9
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 (if (called-interactively-p 'any)
634 (org-edit-src-code
635 nil expanded
636 (concat "*Org-Babel Preview " (buffer-name) "[ " lang " ]*"))
637 expanded)))
639 (defun org-babel-edit-distance (s1 s2)
640 "Return the edit (levenshtein) distance between strings S1 S2."
641 (let* ((l1 (length s1))
642 (l2 (length s2))
643 (dist (vconcat (mapcar (lambda (_) (make-vector (1+ l2) nil))
644 (number-sequence 1 (1+ l1)))))
645 (in (lambda (i j) (aref (aref dist i) j))))
646 (setf (aref (aref dist 0) 0) 0)
647 (dolist (j (number-sequence 1 l2))
648 (setf (aref (aref dist 0) j) j))
649 (dolist (i (number-sequence 1 l1))
650 (setf (aref (aref dist i) 0) i)
651 (dolist (j (number-sequence 1 l2))
652 (setf (aref (aref dist i) j)
653 (min
654 (1+ (funcall in (1- i) j))
655 (1+ (funcall in i (1- j)))
656 (+ (if (equal (aref s1 (1- i)) (aref s2 (1- j))) 0 1)
657 (funcall in (1- i) (1- j)))))))
658 (funcall in l1 l2)))
660 (defun org-babel-combine-header-arg-lists (original &rest others)
661 "Combine a number of lists of header argument names and arguments."
662 (let ((results (copy-sequence original)))
663 (dolist (new-list others)
664 (dolist (arg-pair new-list)
665 (let ((header (car arg-pair))
666 (args (cdr arg-pair)))
667 (setq results
668 (cons arg-pair (org-remove-if
669 (lambda (pair) (equal header (car pair)))
670 results))))))
671 results))
673 ;;;###autoload
674 (defun org-babel-check-src-block ()
675 "Check for misspelled header arguments in the current code block."
676 (interactive)
677 ;; TODO: report malformed code block
678 ;; TODO: report incompatible combinations of header arguments
679 ;; TODO: report uninitialized variables
680 (let ((too-close 2) ;; <- control closeness to report potential match
681 (names (mapcar #'symbol-name org-babel-header-arg-names)))
682 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg)) 1))
683 (and (org-babel-where-is-src-block-head)
684 (org-babel-parse-header-arguments
685 (org-no-properties
686 (match-string 4))))))
687 (dolist (name names)
688 (when (and (not (string= header name))
689 (<= (org-babel-edit-distance header name) too-close)
690 (not (member header names)))
691 (error "Supplied header \"%S\" is suspiciously close to \"%S\""
692 header name))))
693 (message "No suspicious header arguments found.")))
695 ;;;###autoload
696 (defun org-babel-insert-header-arg ()
697 "Insert a header argument selecting from lists of common args and values."
698 (interactive)
699 (let* ((lang (car (org-babel-get-src-block-info 'light)))
700 (lang-headers (intern (concat "org-babel-header-args:" lang)))
701 (headers (org-babel-combine-header-arg-lists
702 org-babel-common-header-args-w-values
703 (if (boundp lang-headers) (eval lang-headers) nil)))
704 (arg (org-icompleting-read
705 "Header Arg: "
706 (mapcar
707 (lambda (header-spec) (symbol-name (car header-spec)))
708 headers))))
709 (insert ":" arg)
710 (let ((vals (cdr (assoc (intern arg) headers))))
711 (when vals
712 (insert
714 (cond
715 ((eq vals :any)
716 (read-from-minibuffer "value: "))
717 ((listp vals)
718 (mapconcat
719 (lambda (group)
720 (let ((arg (org-icompleting-read
721 "value: "
722 (cons "default" (mapcar #'symbol-name group)))))
723 (if (and arg (not (string= "default" arg)))
724 (concat arg " ")
725 "")))
726 vals ""))))))))
728 ;; Add support for completing-read insertion of header arguments after ":"
729 (defun org-babel-header-arg-expand ()
730 "Call `org-babel-enter-header-arg-w-completion' in appropriate contexts."
731 (when (and (equal (char-before) ?\:) (org-babel-where-is-src-block-head))
732 (org-babel-enter-header-arg-w-completion (match-string 2))))
734 (defun org-babel-enter-header-arg-w-completion (&optional lang)
735 "Insert header argument appropriate for LANG with completion."
736 (let* ((lang-headers-var (intern (concat "org-babel-header-args:" lang)))
737 (lang-headers (when (boundp lang-headers-var) (eval lang-headers-var)))
738 (headers-w-values (org-babel-combine-header-arg-lists
739 org-babel-common-header-args-w-values lang-headers))
740 (headers (mapcar #'symbol-name (mapcar #'car headers-w-values)))
741 (header (org-completing-read "Header Arg: " headers))
742 (args (cdr (assoc (intern header) headers-w-values)))
743 (arg (when (and args (listp args))
744 (org-completing-read
745 (format "%s: " header)
746 (mapcar #'symbol-name (apply #'append args))))))
747 (insert (concat header " " (or arg "")))
748 (cons header arg)))
750 (add-hook 'org-tab-first-hook 'org-babel-header-arg-expand)
752 ;;;###autoload
753 (defun org-babel-load-in-session (&optional arg info)
754 "Load the body of the current source-code block.
755 Evaluate the header arguments for the source block before
756 entering the session. After loading the body this pops open the
757 session."
758 (interactive)
759 (let* ((info (or info (org-babel-get-src-block-info)))
760 (lang (nth 0 info))
761 (params (nth 2 info))
762 (body (setf (nth 1 info)
763 (if (org-babel-noweb-p params :eval)
764 (org-babel-expand-noweb-references info)
765 (nth 1 info))))
766 (session (cdr (assoc :session params)))
767 (dir (cdr (assoc :dir params)))
768 (default-directory
769 (or (and dir (file-name-as-directory dir)) default-directory))
770 (cmd (intern (concat "org-babel-load-session:" lang))))
771 (unless (fboundp cmd)
772 (error "No org-babel-load-session function for %s!" lang))
773 (pop-to-buffer (funcall cmd session body params))
774 (end-of-line 1)))
776 ;;;###autoload
777 (defun org-babel-initiate-session (&optional arg info)
778 "Initiate session for current code block.
779 If called with a prefix argument then resolve any variable
780 references in the header arguments and assign these variables in
781 the session. Copy the body of the code block to the kill ring."
782 (interactive "P")
783 (let* ((info (or info (org-babel-get-src-block-info (not arg))))
784 (lang (nth 0 info))
785 (body (nth 1 info))
786 (params (nth 2 info))
787 (session (cdr (assoc :session params)))
788 (dir (cdr (assoc :dir params)))
789 (default-directory
790 (or (and dir (file-name-as-directory dir)) default-directory))
791 (init-cmd (intern (format "org-babel-%s-initiate-session" lang)))
792 (prep-cmd (intern (concat "org-babel-prep-session:" lang))))
793 (if (and (stringp session) (string= session "none"))
794 (error "This block is not using a session!"))
795 (unless (fboundp init-cmd)
796 (error "No org-babel-initiate-session function for %s!" lang))
797 (with-temp-buffer (insert (org-babel-trim body))
798 (copy-region-as-kill (point-min) (point-max)))
799 (when arg
800 (unless (fboundp prep-cmd)
801 (error "No org-babel-prep-session function for %s!" lang))
802 (funcall prep-cmd session params))
803 (funcall init-cmd session params)))
805 ;;;###autoload
806 (defun org-babel-switch-to-session (&optional arg info)
807 "Switch to the session of the current code block.
808 Uses `org-babel-initiate-session' to start the session. If called
809 with a prefix argument then this is passed on to
810 `org-babel-initiate-session'."
811 (interactive "P")
812 (pop-to-buffer (org-babel-initiate-session arg info))
813 (end-of-line 1))
815 (defalias 'org-babel-pop-to-session 'org-babel-switch-to-session)
817 ;;;###autoload
818 (defun org-babel-switch-to-session-with-code (&optional arg info)
819 "Switch to code buffer and display session."
820 (interactive "P")
821 (let ((swap-windows
822 (lambda ()
823 (let ((other-window-buffer (window-buffer (next-window))))
824 (set-window-buffer (next-window) (current-buffer))
825 (set-window-buffer (selected-window) other-window-buffer))
826 (other-window 1)))
827 (info (org-babel-get-src-block-info))
828 (org-src-window-setup 'reorganize-frame))
829 (save-excursion
830 (org-babel-switch-to-session arg info))
831 (org-edit-src-code)
832 (funcall swap-windows)))
834 (defmacro org-babel-do-in-edit-buffer (&rest body)
835 "Evaluate BODY in edit buffer if there is a code block at point.
836 Return t if a code block was found at point, nil otherwise."
837 `(let ((org-src-window-setup 'switch-invisibly))
838 (when (and (org-babel-where-is-src-block-head)
839 (org-edit-src-code nil nil nil))
840 (unwind-protect (progn ,@body)
841 (if (org-bound-and-true-p org-edit-src-from-org-mode)
842 (org-edit-src-exit)))
843 t)))
844 (def-edebug-spec org-babel-do-in-edit-buffer (body))
846 (defun org-babel-do-key-sequence-in-edit-buffer (key)
847 "Read key sequence and execute the command in edit buffer.
848 Enter a key sequence to be executed in the language major-mode
849 edit buffer. For example, TAB will alter the contents of the
850 Org-mode code block according to the effect of TAB in the
851 language major-mode buffer. For languages that support
852 interactive sessions, this can be used to send code from the Org
853 buffer to the session for evaluation using the native major-mode
854 evaluation mechanisms."
855 (interactive "kEnter key-sequence to execute in edit buffer: ")
856 (org-babel-do-in-edit-buffer
857 (call-interactively
858 (key-binding (or key (read-key-sequence nil))))))
860 (defvar org-bracket-link-regexp)
862 ;;;###autoload
863 (defun org-babel-open-src-block-result (&optional re-run)
864 "If `point' is on a src block then open the results of the
865 source code block, otherwise return nil. With optional prefix
866 argument RE-RUN the source-code block is evaluated even if
867 results already exist."
868 (interactive "P")
869 (let ((info (org-babel-get-src-block-info)))
870 (when info
871 (save-excursion
872 ;; go to the results, if there aren't any then run the block
873 (goto-char (or (and (not re-run) (org-babel-where-is-src-block-result))
874 (progn (org-babel-execute-src-block)
875 (org-babel-where-is-src-block-result))))
876 (end-of-line 1)
877 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
878 ;; open the results
879 (if (looking-at org-bracket-link-regexp)
880 ;; file results
881 (org-open-at-point)
882 (let ((r (org-babel-format-result
883 (org-babel-read-result) (cdr (assoc :sep (nth 2 info))))))
884 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
885 (delete-region (point-min) (point-max))
886 (insert r)))
887 t))))
889 ;;;###autoload
890 (defmacro org-babel-map-src-blocks (file &rest body)
891 "Evaluate BODY forms on each source-block in FILE.
892 If FILE is nil evaluate BODY forms on source blocks in current
893 buffer. During evaluation of BODY the following local variables
894 are set relative to the currently matched code block.
896 full-block ------- string holding the entirety of the code block
897 beg-block -------- point at the beginning of the code block
898 end-block -------- point at the end of the matched code block
899 lang ------------- string holding the language of the code block
900 beg-lang --------- point at the beginning of the lang
901 end-lang --------- point at the end of the lang
902 switches --------- string holding the switches
903 beg-switches ----- point at the beginning of the switches
904 end-switches ----- point at the end of the switches
905 header-args ------ string holding the header-args
906 beg-header-args -- point at the beginning of the header-args
907 end-header-args -- point at the end of the header-args
908 body ------------- string holding the body of the code block
909 beg-body --------- point at the beginning of the body
910 end-body --------- point at the end of the body"
911 (declare (indent 1))
912 (let ((tempvar (make-symbol "file")))
913 `(let* ((,tempvar ,file)
914 (visited-p (or (null ,tempvar)
915 (get-file-buffer (expand-file-name ,tempvar))))
916 (point (point)) to-be-removed)
917 (save-window-excursion
918 (when ,tempvar (find-file ,tempvar))
919 (setq to-be-removed (current-buffer))
920 (goto-char (point-min))
921 (while (re-search-forward org-babel-src-block-regexp nil t)
922 (goto-char (match-beginning 0))
923 (let ((full-block (match-string 0))
924 (beg-block (match-beginning 0))
925 (end-block (match-end 0))
926 (lang (match-string 2))
927 (beg-lang (match-beginning 2))
928 (end-lang (match-end 2))
929 (switches (match-string 3))
930 (beg-switches (match-beginning 3))
931 (end-switches (match-end 3))
932 (header-args (match-string 4))
933 (beg-header-args (match-beginning 4))
934 (end-header-args (match-end 4))
935 (body (match-string 5))
936 (beg-body (match-beginning 5))
937 (end-body (match-end 5)))
938 ,@body
939 (goto-char end-block))))
940 (unless visited-p (kill-buffer to-be-removed))
941 (goto-char point))))
942 (def-edebug-spec org-babel-map-src-blocks (form body))
944 ;;;###autoload
945 (defmacro org-babel-map-inline-src-blocks (file &rest body)
946 "Evaluate BODY forms on each inline source-block in FILE.
947 If FILE is nil evaluate BODY forms on source blocks in current
948 buffer."
949 (declare (indent 1))
950 (let ((tempvar (make-symbol "file")))
951 `(let* ((,tempvar ,file)
952 (visited-p (or (null ,tempvar)
953 (get-file-buffer (expand-file-name ,tempvar))))
954 (point (point)) to-be-removed)
955 (save-window-excursion
956 (when ,tempvar (find-file ,tempvar))
957 (setq to-be-removed (current-buffer))
958 (goto-char (point-min))
959 (while (re-search-forward org-babel-inline-src-block-regexp nil t)
960 (goto-char (match-beginning 1))
961 (save-match-data ,@body)
962 (goto-char (match-end 0))))
963 (unless visited-p (kill-buffer to-be-removed))
964 (goto-char point))))
965 (def-edebug-spec org-babel-map-inline-src-blocks (form body))
967 (defvar org-babel-lob-one-liner-regexp)
969 ;;;###autoload
970 (defmacro org-babel-map-call-lines (file &rest body)
971 "Evaluate BODY forms on each call line in FILE.
972 If FILE is nil evaluate BODY forms on source blocks in current
973 buffer."
974 (declare (indent 1))
975 (let ((tempvar (make-symbol "file")))
976 `(let* ((,tempvar ,file)
977 (visited-p (or (null ,tempvar)
978 (get-file-buffer (expand-file-name ,tempvar))))
979 (point (point)) to-be-removed)
980 (save-window-excursion
981 (when ,tempvar (find-file ,tempvar))
982 (setq to-be-removed (current-buffer))
983 (goto-char (point-min))
984 (while (re-search-forward org-babel-lob-one-liner-regexp nil t)
985 (goto-char (match-beginning 1))
986 (save-match-data ,@body)
987 (goto-char (match-end 0))))
988 (unless visited-p (kill-buffer to-be-removed))
989 (goto-char point))))
990 (def-edebug-spec org-babel-map-call-lines (form body))
992 ;;;###autoload
993 (defmacro org-babel-map-executables (file &rest body)
994 (declare (indent 1))
995 (let ((tempvar (make-symbol "file"))
996 (rx (make-symbol "rx")))
997 `(let* ((,tempvar ,file)
998 (,rx (concat "\\(" org-babel-src-block-regexp
999 "\\|" org-babel-inline-src-block-regexp
1000 "\\|" org-babel-lob-one-liner-regexp "\\)"))
1001 (visited-p (or (null ,tempvar)
1002 (get-file-buffer (expand-file-name ,tempvar))))
1003 (point (point)) to-be-removed)
1004 (save-window-excursion
1005 (when ,tempvar (find-file ,tempvar))
1006 (setq to-be-removed (current-buffer))
1007 (goto-char (point-min))
1008 (while (re-search-forward ,rx nil t)
1009 (goto-char (match-beginning 1))
1010 (when (looking-at org-babel-inline-src-block-regexp)(forward-char 1))
1011 (save-match-data ,@body)
1012 (goto-char (match-end 0))))
1013 (unless visited-p (kill-buffer to-be-removed))
1014 (goto-char point))))
1015 (def-edebug-spec org-babel-map-executables (form body))
1017 ;;;###autoload
1018 (defun org-babel-execute-buffer (&optional arg)
1019 "Execute source code blocks in a buffer.
1020 Call `org-babel-execute-src-block' on every source block in
1021 the current buffer."
1022 (interactive "P")
1023 (org-babel-eval-wipe-error-buffer)
1024 (org-save-outline-visibility t
1025 (org-babel-map-executables nil
1026 (if (looking-at org-babel-lob-one-liner-regexp)
1027 (org-babel-lob-execute-maybe)
1028 (org-babel-execute-src-block arg)))))
1030 ;;;###autoload
1031 (defun org-babel-execute-subtree (&optional arg)
1032 "Execute source code blocks in a subtree.
1033 Call `org-babel-execute-src-block' on every source block in
1034 the current subtree."
1035 (interactive "P")
1036 (save-restriction
1037 (save-excursion
1038 (org-narrow-to-subtree)
1039 (org-babel-execute-buffer arg)
1040 (widen))))
1042 ;;;###autoload
1043 (defun org-babel-sha1-hash (&optional info)
1044 "Generate an sha1 hash based on the value of info."
1045 (interactive)
1046 (let ((print-level nil)
1047 (info (or info (org-babel-get-src-block-info))))
1048 (setf (nth 2 info)
1049 (sort (copy-sequence (nth 2 info))
1050 (lambda (a b) (string< (car a) (car b)))))
1051 (let* ((rm (lambda (lst)
1052 (dolist (p '("replace" "silent" "none"
1053 "append" "prepend"))
1054 (setq lst (remove p lst)))
1055 lst))
1056 (norm (lambda (arg)
1057 (let ((v (if (and (listp (cdr arg)) (null (cddr arg)))
1058 (copy-sequence (cdr arg))
1059 (cdr arg))))
1060 (when (and v (not (and (sequencep v)
1061 (not (consp v))
1062 (= (length v) 0))))
1063 (cond
1064 ((and (listp v) ; lists are sorted
1065 (member (car arg) '(:result-params)))
1066 (sort (funcall rm v) #'string<))
1067 ((and (stringp v) ; strings are sorted
1068 (member (car arg) '(:results :exports)))
1069 (mapconcat #'identity (sort (funcall rm (split-string v))
1070 #'string<) " "))
1071 (t v)))))))
1072 ((lambda (hash)
1073 (when (org-called-interactively-p 'interactive) (message hash)) hash)
1074 (let ((it (format "%s-%s"
1075 (mapconcat
1076 #'identity
1077 (delq nil (mapcar (lambda (arg)
1078 (let ((normalized (funcall norm arg)))
1079 (when normalized
1080 (format "%S" normalized))))
1081 (nth 2 info))) ":")
1082 (nth 1 info))))
1083 (sha1 it))))))
1085 (defun org-babel-current-result-hash ()
1086 "Return the current in-buffer hash."
1087 (org-babel-where-is-src-block-result)
1088 (org-no-properties (match-string 5)))
1090 (defun org-babel-set-current-result-hash (hash)
1091 "Set the current in-buffer hash to HASH."
1092 (org-babel-where-is-src-block-result)
1093 (save-excursion (goto-char (match-beginning 3))
1094 ;; (mapc #'delete-overlay (overlays-at (point)))
1095 (replace-match hash nil nil nil 3)
1096 (org-babel-hide-hash)))
1098 (defun org-babel-hide-hash ()
1099 "Hide the hash in the current results line.
1100 Only the initial `org-babel-hash-show' characters of the hash
1101 will remain visible."
1102 (add-to-invisibility-spec '(org-babel-hide-hash . t))
1103 (save-excursion
1104 (when (and (re-search-forward org-babel-result-regexp nil t)
1105 (match-string 5))
1106 (let* ((start (match-beginning 5))
1107 (hide-start (+ org-babel-hash-show start))
1108 (end (match-end 5))
1109 (hash (match-string 5))
1110 ov1 ov2)
1111 (setq ov1 (make-overlay start hide-start))
1112 (setq ov2 (make-overlay hide-start end))
1113 (overlay-put ov2 'invisible 'org-babel-hide-hash)
1114 (overlay-put ov1 'babel-hash hash)))))
1116 (defun org-babel-hide-all-hashes ()
1117 "Hide the hash in the current buffer.
1118 Only the initial `org-babel-hash-show' characters of each hash
1119 will remain visible. This function should be called as part of
1120 the `org-mode-hook'."
1121 (save-excursion
1122 (while (and (not org-babel-hash-show-time)
1123 (re-search-forward org-babel-result-regexp nil t))
1124 (goto-char (match-beginning 0))
1125 (org-babel-hide-hash)
1126 (goto-char (match-end 0)))))
1127 (add-hook 'org-mode-hook 'org-babel-hide-all-hashes)
1129 (defun org-babel-hash-at-point (&optional point)
1130 "Return the value of the hash at POINT.
1131 The hash is also added as the last element of the kill ring.
1132 This can be called with C-c C-c."
1133 (interactive)
1134 (let ((hash (car (delq nil (mapcar
1135 (lambda (ol) (overlay-get ol 'babel-hash))
1136 (overlays-at (or point (point))))))))
1137 (when hash (kill-new hash) (message hash))))
1138 (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-hash-at-point)
1140 (defun org-babel-result-hide-spec ()
1141 "Hide portions of results lines.
1142 Add `org-babel-hide-result' as an invisibility spec for hiding
1143 portions of results lines."
1144 (add-to-invisibility-spec '(org-babel-hide-result . t)))
1145 (add-hook 'org-mode-hook 'org-babel-result-hide-spec)
1147 (defvar org-babel-hide-result-overlays nil
1148 "Overlays hiding results.")
1150 (defun org-babel-result-hide-all ()
1151 "Fold all results in the current buffer."
1152 (interactive)
1153 (org-babel-show-result-all)
1154 (save-excursion
1155 (while (re-search-forward org-babel-result-regexp nil t)
1156 (save-excursion (goto-char (match-beginning 0))
1157 (org-babel-hide-result-toggle-maybe)))))
1159 (defun org-babel-show-result-all ()
1160 "Unfold all results in the current buffer."
1161 (mapc 'delete-overlay org-babel-hide-result-overlays)
1162 (setq org-babel-hide-result-overlays nil))
1164 ;;;###autoload
1165 (defun org-babel-hide-result-toggle-maybe ()
1166 "Toggle visibility of result at point."
1167 (interactive)
1168 (let ((case-fold-search t))
1169 (if (save-excursion
1170 (beginning-of-line 1)
1171 (looking-at org-babel-result-regexp))
1172 (progn (org-babel-hide-result-toggle)
1173 t) ;; to signal that we took action
1174 nil))) ;; to signal that we did not
1176 (defun org-babel-hide-result-toggle (&optional force)
1177 "Toggle the visibility of the current result."
1178 (interactive)
1179 (save-excursion
1180 (beginning-of-line)
1181 (if (re-search-forward org-babel-result-regexp nil t)
1182 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
1183 (end (progn
1184 (while (looking-at org-babel-multi-line-header-regexp)
1185 (forward-line 1))
1186 (goto-char (- (org-babel-result-end) 1)) (point)))
1188 (if (memq t (mapcar (lambda (overlay)
1189 (eq (overlay-get overlay 'invisible)
1190 'org-babel-hide-result))
1191 (overlays-at start)))
1192 (if (or (not force) (eq force 'off))
1193 (mapc (lambda (ov)
1194 (when (member ov org-babel-hide-result-overlays)
1195 (setq org-babel-hide-result-overlays
1196 (delq ov org-babel-hide-result-overlays)))
1197 (when (eq (overlay-get ov 'invisible)
1198 'org-babel-hide-result)
1199 (delete-overlay ov)))
1200 (overlays-at start)))
1201 (setq ov (make-overlay start end))
1202 (overlay-put ov 'invisible 'org-babel-hide-result)
1203 ;; make the block accessible to isearch
1204 (overlay-put
1205 ov 'isearch-open-invisible
1206 (lambda (ov)
1207 (when (member ov org-babel-hide-result-overlays)
1208 (setq org-babel-hide-result-overlays
1209 (delq ov org-babel-hide-result-overlays)))
1210 (when (eq (overlay-get ov 'invisible)
1211 'org-babel-hide-result)
1212 (delete-overlay ov))))
1213 (push ov org-babel-hide-result-overlays)))
1214 (error "Not looking at a result line"))))
1216 ;; org-tab-after-check-for-cycling-hook
1217 (add-hook 'org-tab-first-hook 'org-babel-hide-result-toggle-maybe)
1218 ;; Remove overlays when changing major mode
1219 (add-hook 'org-mode-hook
1220 (lambda () (org-add-hook 'change-major-mode-hook
1221 'org-babel-show-result-all 'append 'local)))
1223 (defvar org-file-properties)
1224 (defun org-babel-params-from-properties (&optional lang)
1225 "Retrieve parameters specified as properties.
1226 Return an association list of any source block params which
1227 may be specified in the properties of the current outline entry."
1228 (save-match-data
1229 (let (val sym)
1230 (org-babel-parse-multiple-vars
1231 (delq nil
1232 (mapcar
1233 (lambda (header-arg)
1234 (and (setq val (org-entry-get (point) header-arg t))
1235 (cons (intern (concat ":" header-arg))
1236 (org-babel-read val))))
1237 (mapcar
1238 #'symbol-name
1239 (mapcar
1240 #'car
1241 (org-babel-combine-header-arg-lists
1242 org-babel-common-header-args-w-values
1243 (progn
1244 (setq sym (intern (concat "org-babel-header-args:" lang)))
1245 (and (boundp sym) (eval sym))))))))))))
1247 (defvar org-src-preserve-indentation)
1248 (defun org-babel-parse-src-block-match ()
1249 "Parse the results from a match of the `org-babel-src-block-regexp'."
1250 (let* ((block-indentation (length (match-string 1)))
1251 (lang (org-no-properties (match-string 2)))
1252 (lang-headers (intern (concat "org-babel-default-header-args:" lang)))
1253 (switches (match-string 3))
1254 (body (org-no-properties
1255 (let* ((body (match-string 5))
1256 (sub-length (- (length body) 1)))
1257 (if (and (> sub-length 0)
1258 (string= "\n" (substring body sub-length)))
1259 (substring body 0 sub-length)
1260 (or body "")))))
1261 (preserve-indentation (or org-src-preserve-indentation
1262 (save-match-data
1263 (string-match "-i\\>" switches)))))
1264 (list lang
1265 ;; get block body less properties, protective commas, and indentation
1266 (with-temp-buffer
1267 (save-match-data
1268 (insert (org-unescape-code-in-string body))
1269 (unless preserve-indentation (org-do-remove-indentation))
1270 (buffer-string)))
1271 (org-babel-merge-params
1272 org-babel-default-header-args
1273 (org-babel-params-from-properties lang)
1274 (if (boundp lang-headers) (eval lang-headers) nil)
1275 (org-babel-parse-header-arguments
1276 (org-no-properties (or (match-string 4) ""))))
1277 switches
1278 block-indentation)))
1280 (defun org-babel-parse-inline-src-block-match ()
1281 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
1282 (let* ((lang (org-no-properties (match-string 2)))
1283 (lang-headers (intern (concat "org-babel-default-header-args:" lang))))
1284 (list lang
1285 (org-unescape-code-in-string (org-no-properties (match-string 5)))
1286 (org-babel-merge-params
1287 org-babel-default-inline-header-args
1288 (org-babel-params-from-properties lang)
1289 (if (boundp lang-headers) (eval lang-headers) nil)
1290 (org-babel-parse-header-arguments
1291 (org-no-properties (or (match-string 4) "")))))))
1293 (defun org-babel-balanced-split (string alts)
1294 "Split STRING on instances of ALTS.
1295 ALTS is a cons of two character options where each option may be
1296 either the numeric code of a single character or a list of
1297 character alternatives. For example to split on balanced
1298 instances of \"[ \t]:\" set ALTS to '((32 9) . 58)."
1299 (let* ((matches (lambda (ch spec) (if (listp spec) (member ch spec) (equal spec ch))))
1300 (matched (lambda (ch last)
1301 (if (consp alts)
1302 (and (funcall matches ch (cdr alts))
1303 (funcall matches last (car alts)))
1304 (funcall matches ch alts))))
1305 (balance 0) (last 0)
1306 quote partial lst)
1307 (mapc (lambda (ch) ; split on [], (), "" balanced instances of [ \t]:
1308 (setq balance (+ balance
1309 (cond ((or (equal 91 ch) (equal 40 ch)) 1)
1310 ((or (equal 93 ch) (equal 41 ch)) -1)
1311 (t 0))))
1312 (when (and (equal 34 ch) (not (equal 92 last)))
1313 (setq quote (not quote)))
1314 (setq partial (cons ch partial))
1315 (when (and (= balance 0) (not quote) (funcall matched ch last))
1316 (setq lst (cons (apply #'string (nreverse
1317 (if (consp alts)
1318 (cddr partial)
1319 (cdr partial))))
1320 lst))
1321 (setq partial nil))
1322 (setq last ch))
1323 (string-to-list string))
1324 (nreverse (cons (apply #'string (nreverse partial)) lst))))
1326 (defun org-babel-join-splits-near-ch (ch list)
1327 "Join splits where \"=\" is on either end of the split."
1328 (let ((last= (lambda (str) (= ch (aref str (1- (length str))))))
1329 (first= (lambda (str) (= ch (aref str 0)))))
1330 (reverse
1331 (org-reduce (lambda (acc el)
1332 (let ((head (car acc)))
1333 (if (and head (or (funcall last= head) (funcall first= el)))
1334 (cons (concat head el) (cdr acc))
1335 (cons el acc))))
1336 list :initial-value nil))))
1338 (defun org-babel-parse-header-arguments (arg-string)
1339 "Parse a string of header arguments returning an alist."
1340 (when (> (length arg-string) 0)
1341 (org-babel-parse-multiple-vars
1342 (delq nil
1343 (mapcar
1344 (lambda (arg)
1345 (if (string-match
1346 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1347 arg)
1348 (cons (intern (match-string 1 arg))
1349 (org-babel-read (org-babel-chomp (match-string 2 arg))))
1350 (cons (intern (org-babel-chomp arg)) nil)))
1351 ((lambda (raw)
1352 (cons (car raw) (mapcar (lambda (r) (concat ":" r)) (cdr raw))))
1353 (org-babel-balanced-split arg-string '((32 9) . 58))))))))
1355 (defun org-babel-parse-multiple-vars (header-arguments)
1356 "Expand multiple variable assignments behind a single :var keyword.
1358 This allows expression of multiple variables with one :var as
1359 shown below.
1361 #+PROPERTY: var foo=1, bar=2"
1362 (let (results)
1363 (mapc (lambda (pair)
1364 (if (eq (car pair) :var)
1365 (mapcar (lambda (v) (push (cons :var (org-babel-trim v)) results))
1366 (org-babel-join-splits-near-ch
1367 61 (org-babel-balanced-split (cdr pair) 32)))
1368 (push pair results)))
1369 header-arguments)
1370 (nreverse results)))
1372 (defun org-babel-process-params (params)
1373 "Expand variables in PARAMS and add summary parameters."
1374 (let* ((processed-vars (mapcar (lambda (el)
1375 (if (consp (cdr el))
1376 (cdr el)
1377 (org-babel-ref-parse (cdr el))))
1378 (org-babel-get-header params :var)))
1379 (vars-and-names (if (and (assoc :colname-names params)
1380 (assoc :rowname-names params))
1381 (list processed-vars)
1382 (org-babel-disassemble-tables
1383 processed-vars
1384 (cdr (assoc :hlines params))
1385 (cdr (assoc :colnames params))
1386 (cdr (assoc :rownames params)))))
1387 (raw-result (or (cdr (assoc :results params)) ""))
1388 (result-params (append
1389 (split-string (if (stringp raw-result)
1390 raw-result
1391 (eval raw-result)))
1392 (cdr (assoc :result-params params)))))
1393 (append
1394 (mapcar (lambda (var) (cons :var var)) (car vars-and-names))
1395 (list
1396 (cons :colname-names (or (cdr (assoc :colname-names params))
1397 (cadr vars-and-names)))
1398 (cons :rowname-names (or (cdr (assoc :rowname-names params))
1399 (caddr vars-and-names)))
1400 (cons :result-params result-params)
1401 (cons :result-type (cond ((member "output" result-params) 'output)
1402 ((member "value" result-params) 'value)
1403 (t 'value))))
1404 (org-babel-get-header params :var 'other))))
1406 ;; row and column names
1407 (defun org-babel-del-hlines (table)
1408 "Remove all 'hlines from TABLE."
1409 (remove 'hline table))
1411 (defun org-babel-get-colnames (table)
1412 "Return the column names of TABLE.
1413 Return a cons cell, the `car' of which contains the TABLE less
1414 colnames, and the `cdr' of which contains a list of the column
1415 names."
1416 (if (equal 'hline (nth 1 table))
1417 (cons (cddr table) (car table))
1418 (cons (cdr table) (car table))))
1420 (defun org-babel-get-rownames (table)
1421 "Return the row names of TABLE.
1422 Return a cons cell, the `car' of which contains the TABLE less
1423 colnames, and the `cdr' of which contains a list of the column
1424 names. Note: this function removes any hlines in TABLE."
1425 (let* ((trans (lambda (table) (apply #'mapcar* #'list table)))
1426 (width (apply 'max
1427 (mapcar (lambda (el) (if (listp el) (length el) 0)) table)))
1428 (table (funcall trans (mapcar (lambda (row)
1429 (if (not (equal row 'hline))
1431 (setq row '())
1432 (dotimes (n width)
1433 (setq row (cons 'hline row)))
1434 row))
1435 table))))
1436 (cons (mapcar (lambda (row) (if (equal (car row) 'hline) 'hline row))
1437 (funcall trans (cdr table)))
1438 (remove 'hline (car table)))))
1440 (defun org-babel-put-colnames (table colnames)
1441 "Add COLNAMES to TABLE if they exist."
1442 (if colnames (apply 'list colnames 'hline table) table))
1444 (defun org-babel-put-rownames (table rownames)
1445 "Add ROWNAMES to TABLE if they exist."
1446 (if rownames
1447 (mapcar (lambda (row)
1448 (if (listp row)
1449 (cons (or (pop rownames) "") row)
1450 row)) table)
1451 table))
1453 (defun org-babel-pick-name (names selector)
1454 "Select one out of an alist of row or column names.
1455 SELECTOR can be either a list of names in which case those names
1456 will be returned directly, or an index into the list NAMES in
1457 which case the indexed names will be return."
1458 (if (listp selector)
1459 selector
1460 (when names
1461 (if (and selector (symbolp selector) (not (equal t selector)))
1462 (cdr (assoc selector names))
1463 (if (integerp selector)
1464 (nth (- selector 1) names)
1465 (cdr (car (last names))))))))
1467 (defun org-babel-disassemble-tables (vars hlines colnames rownames)
1468 "Parse tables for further processing.
1469 Process the variables in VARS according to the HLINES,
1470 ROWNAMES and COLNAMES header arguments. Return a list consisting
1471 of the vars, cnames and rnames."
1472 (let (cnames rnames)
1473 (list
1474 (mapcar
1475 (lambda (var)
1476 (when (listp (cdr var))
1477 (when (and (not (equal colnames "no"))
1478 (or colnames (and (equal (nth 1 (cdr var)) 'hline)
1479 (not (member 'hline (cddr (cdr var)))))))
1480 (let ((both (org-babel-get-colnames (cdr var))))
1481 (setq cnames (cons (cons (car var) (cdr both))
1482 cnames))
1483 (setq var (cons (car var) (car both)))))
1484 (when (and rownames (not (equal rownames "no")))
1485 (let ((both (org-babel-get-rownames (cdr var))))
1486 (setq rnames (cons (cons (car var) (cdr both))
1487 rnames))
1488 (setq var (cons (car var) (car both)))))
1489 (when (and hlines (not (equal hlines "yes")))
1490 (setq var (cons (car var) (org-babel-del-hlines (cdr var))))))
1491 var)
1492 vars)
1493 (reverse cnames) (reverse rnames))))
1495 (defun org-babel-reassemble-table (table colnames rownames)
1496 "Add column and row names to a table.
1497 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1498 to the table for reinsertion to org-mode."
1499 (if (listp table)
1500 ((lambda (table)
1501 (if (and colnames (listp (car table)) (= (length (car table))
1502 (length colnames)))
1503 (org-babel-put-colnames table colnames) table))
1504 (if (and rownames (= (length table) (length rownames)))
1505 (org-babel-put-rownames table rownames) table))
1506 table))
1508 (defun org-babel-where-is-src-block-head ()
1509 "Find where the current source block begins.
1510 Return the point at the beginning of the current source
1511 block. Specifically at the beginning of the #+BEGIN_SRC line.
1512 If the point is not on a source block then return nil."
1513 (let ((initial (point)) (case-fold-search t) top bottom)
1515 (save-excursion ;; on a source name line or a #+header line
1516 (beginning-of-line 1)
1517 (and (or (looking-at org-babel-src-name-regexp)
1518 (looking-at org-babel-multi-line-header-regexp))
1519 (progn
1520 (while (and (forward-line 1)
1521 (or (looking-at org-babel-src-name-regexp)
1522 (looking-at org-babel-multi-line-header-regexp))))
1523 (looking-at org-babel-src-block-regexp))
1524 (point)))
1525 (save-excursion ;; on a #+begin_src line
1526 (beginning-of-line 1)
1527 (and (looking-at org-babel-src-block-regexp)
1528 (point)))
1529 (save-excursion ;; inside a src block
1530 (and
1531 (re-search-backward "^[ \t]*#\\+begin_src" nil t) (setq top (point))
1532 (re-search-forward "^[ \t]*#\\+end_src" nil t) (setq bottom (point))
1533 (< top initial) (< initial bottom)
1534 (progn (goto-char top) (beginning-of-line 1)
1535 (looking-at org-babel-src-block-regexp))
1536 (point))))))
1538 ;;;###autoload
1539 (defun org-babel-goto-src-block-head ()
1540 "Go to the beginning of the current code block."
1541 (interactive)
1542 ((lambda (head)
1543 (if head (goto-char head) (error "Not currently in a code block")))
1544 (org-babel-where-is-src-block-head)))
1546 ;;;###autoload
1547 (defun org-babel-goto-named-src-block (name)
1548 "Go to a named source-code block."
1549 (interactive
1550 (let ((completion-ignore-case t)
1551 (case-fold-search t)
1552 (under-point (thing-at-point 'line)))
1553 (list (org-icompleting-read
1554 "source-block name: " (org-babel-src-block-names) nil t
1555 (cond
1556 ;; noweb
1557 ((string-match (org-babel-noweb-wrap) under-point)
1558 (let ((block-name (match-string 1 under-point)))
1559 (string-match "[^(]*" block-name)
1560 (match-string 0 block-name)))
1561 ;; #+call:
1562 ((string-match org-babel-lob-one-liner-regexp under-point)
1563 (let ((source-info (car (org-babel-lob-get-info))))
1564 (if (string-match "^\\([^\\[]+?\\)\\(\\[.*\\]\\)?(" source-info)
1565 (let ((source-name (match-string 1 source-info)))
1566 source-name))))
1567 ;; #+results:
1568 ((string-match (concat "#\\+" org-babel-results-keyword
1569 "\\:\s+\\([^\\(]*\\)") under-point)
1570 (match-string 1 under-point))
1571 ;; symbol-at-point
1572 ((and (thing-at-point 'symbol))
1573 (org-babel-find-named-block (thing-at-point 'symbol))
1574 (thing-at-point 'symbol))
1575 (""))))))
1576 (let ((point (org-babel-find-named-block name)))
1577 (if point
1578 ;; taken from `org-open-at-point'
1579 (progn (org-mark-ring-push) (goto-char point) (org-show-context))
1580 (message "source-code block '%s' not found in this buffer" name))))
1582 (defun org-babel-find-named-block (name)
1583 "Find a named source-code block.
1584 Return the location of the source block identified by source
1585 NAME, or nil if no such block exists. Set match data according to
1586 org-babel-named-src-block-regexp."
1587 (save-excursion
1588 (let ((case-fold-search t)
1589 (regexp (org-babel-named-src-block-regexp-for-name name)) msg)
1590 (goto-char (point-min))
1591 (when (or (re-search-forward regexp nil t)
1592 (re-search-backward regexp nil t))
1593 (match-beginning 0)))))
1595 (defun org-babel-src-block-names (&optional file)
1596 "Returns the names of source blocks in FILE or the current buffer."
1597 (save-excursion
1598 (when file (find-file file)) (goto-char (point-min))
1599 (let ((case-fold-search t) names)
1600 (while (re-search-forward org-babel-src-name-w-name-regexp nil t)
1601 (setq names (cons (match-string 3) names)))
1602 names)))
1604 ;;;###autoload
1605 (defun org-babel-goto-named-result (name)
1606 "Go to a named result."
1607 (interactive
1608 (let ((completion-ignore-case t))
1609 (list (org-icompleting-read "source-block name: "
1610 (org-babel-result-names) nil t))))
1611 (let ((point (org-babel-find-named-result name)))
1612 (if point
1613 ;; taken from `org-open-at-point'
1614 (progn (goto-char point) (org-show-context))
1615 (message "result '%s' not found in this buffer" name))))
1617 (defun org-babel-find-named-result (name &optional point)
1618 "Find a named result.
1619 Return the location of the result named NAME in the current
1620 buffer or nil if no such result exists."
1621 (save-excursion
1622 (let ((case-fold-search t))
1623 (goto-char (or point (point-min)))
1624 (catch 'is-a-code-block
1625 (when (re-search-forward
1626 (concat org-babel-result-regexp
1627 "[ \t]" (regexp-quote name) "[ \t]*[\n\f\v\r]") nil t)
1628 (when (and (string= "name" (downcase (match-string 1)))
1629 (or (beginning-of-line 1)
1630 (looking-at org-babel-src-block-regexp)
1631 (looking-at org-babel-multi-line-header-regexp)))
1632 (throw 'is-a-code-block (org-babel-find-named-result name (point))))
1633 (beginning-of-line 0) (point))))))
1635 (defun org-babel-result-names (&optional file)
1636 "Returns the names of results in FILE or the current buffer."
1637 (save-excursion
1638 (when file (find-file file)) (goto-char (point-min))
1639 (let ((case-fold-search t) names)
1640 (while (re-search-forward org-babel-result-w-name-regexp nil t)
1641 (setq names (cons (match-string 4) names)))
1642 names)))
1644 ;;;###autoload
1645 (defun org-babel-next-src-block (&optional arg)
1646 "Jump to the next source block.
1647 With optional prefix argument ARG, jump forward ARG many source blocks."
1648 (interactive "p")
1649 (org-next-block arg nil org-babel-src-block-regexp))
1651 ;;;###autoload
1652 (defun org-babel-previous-src-block (&optional arg)
1653 "Jump to the previous source block.
1654 With optional prefix argument ARG, jump backward ARG many source blocks."
1655 (interactive "p")
1656 (org-previous-block arg org-babel-src-block-regexp))
1658 (defvar org-babel-load-languages)
1660 ;;;###autoload
1661 (defun org-babel-mark-block ()
1662 "Mark current src block."
1663 (interactive)
1664 ((lambda (head)
1665 (when head
1666 (save-excursion
1667 (goto-char head)
1668 (looking-at org-babel-src-block-regexp))
1669 (push-mark (match-end 5) nil t)
1670 (goto-char (match-beginning 5))))
1671 (org-babel-where-is-src-block-head)))
1673 (defun org-babel-demarcate-block (&optional arg)
1674 "Wrap or split the code in the region or on the point.
1675 When called from inside of a code block the current block is
1676 split. When called from outside of a code block a new code block
1677 is created. In both cases if the region is demarcated and if the
1678 region is not active then the point is demarcated."
1679 (interactive "P")
1680 (let ((info (org-babel-get-src-block-info 'light))
1681 (headers (progn (org-babel-where-is-src-block-head)
1682 (match-string 4)))
1683 (stars (concat (make-string (or (org-current-level) 1) ?*) " ")))
1684 (if info
1685 (mapc
1686 (lambda (place)
1687 (save-excursion
1688 (goto-char place)
1689 (let ((lang (nth 0 info))
1690 (indent (make-string (nth 5 info) ? )))
1691 (when (string-match "^[[:space:]]*$"
1692 (buffer-substring (point-at-bol)
1693 (point-at-eol)))
1694 (delete-region (point-at-bol) (point-at-eol)))
1695 (insert (concat
1696 (if (looking-at "^") "" "\n")
1697 indent "#+end_src\n"
1698 (if arg stars indent) "\n"
1699 indent "#+begin_src " lang
1700 (if (> (length headers) 1)
1701 (concat " " headers) headers)
1702 (if (looking-at "[\n\r]")
1704 (concat "\n" (make-string (current-column) ? )))))))
1705 (move-end-of-line 2))
1706 (sort (if (org-region-active-p) (list (mark) (point)) (list (point))) #'>))
1707 (let ((start (point))
1708 (lang (org-icompleting-read "Lang: "
1709 (mapcar (lambda (el) (symbol-name (car el)))
1710 org-babel-load-languages)))
1711 (body (delete-and-extract-region
1712 (if (org-region-active-p) (mark) (point)) (point))))
1713 (insert (concat (if (looking-at "^") "" "\n")
1714 (if arg (concat stars "\n") "")
1715 "#+begin_src " lang "\n"
1716 body
1717 (if (or (= (length body) 0)
1718 (string-match "[\r\n]$" body)) "" "\n")
1719 "#+end_src\n"))
1720 (goto-char start) (move-end-of-line 1)))))
1722 (defvar org-babel-lob-one-liner-regexp)
1723 (defun org-babel-where-is-src-block-result (&optional insert info hash indent)
1724 "Find where the current source block results begin.
1725 Return the point at the beginning of the result of the current
1726 source block. Specifically at the beginning of the results line.
1727 If no result exists for this block then create a results line
1728 following the source block."
1729 (save-excursion
1730 (let* ((case-fold-search t)
1731 (on-lob-line (save-excursion
1732 (beginning-of-line 1)
1733 (looking-at org-babel-lob-one-liner-regexp)))
1734 (inlinep (when (org-babel-get-inline-src-block-matches)
1735 (match-end 0)))
1736 (name (if on-lob-line
1737 (mapconcat #'identity (butlast (org-babel-lob-get-info)) "")
1738 (nth 4 (or info (org-babel-get-src-block-info 'light)))))
1739 (head (unless on-lob-line (org-babel-where-is-src-block-head)))
1740 found beg end)
1741 (when head (goto-char head))
1742 (org-with-wide-buffer
1743 (setq
1744 found ;; was there a result (before we potentially insert one)
1746 inlinep
1747 (and
1748 ;; named results:
1749 ;; - return t if it is found, else return nil
1750 ;; - if it does not need to be rebuilt, then don't set end
1751 ;; - if it does need to be rebuilt then do set end
1752 name (setq beg (org-babel-find-named-result name))
1753 (prog1 beg
1754 (when (and hash (not (string= hash (match-string 5))))
1755 (goto-char beg) (setq end beg) ;; beginning of result
1756 (forward-line 1)
1757 (delete-region end (org-babel-result-end)) nil)))
1758 (and
1759 ;; unnamed results:
1760 ;; - return t if it is found, else return nil
1761 ;; - if it is found, and the hash doesn't match, delete and set end
1762 (or on-lob-line (re-search-forward "^[ \t]*#\\+end_src" nil t))
1763 (progn (end-of-line 1)
1764 (if (eobp) (insert "\n") (forward-char 1))
1765 (setq end (point))
1766 (or (and (not name)
1767 (progn ;; unnamed results line already exists
1768 (re-search-forward "[^ \f\t\n\r\v]" nil t)
1769 (beginning-of-line 1)
1770 (looking-at
1771 (concat org-babel-result-regexp "\n")))
1772 (let ((this-hash (match-string 5)))
1773 (prog1 (point)
1774 ;; must remove and rebuild if hash!=old-hash
1775 (if (and hash (not (string= hash this-hash)))
1776 (prog1 nil
1777 (forward-line 1)
1778 (delete-region
1779 end (org-babel-result-end)))
1780 (setq end nil)))))))))))
1781 (if (not (and insert end)) found
1782 (goto-char end)
1783 (unless beg
1784 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1785 (insert (concat
1786 (when (wholenump indent) (make-string indent ? ))
1787 "#+" org-babel-results-keyword
1788 (when hash
1789 (if org-babel-hash-show-time
1790 (concat
1791 "["(format-time-string "<%Y-%m-%d %H:%M:%S>")" "hash"]")
1792 (concat "["hash"]")))
1794 (when name (concat " " name)) "\n"))
1795 (unless beg (insert "\n") (backward-char))
1796 (beginning-of-line 0)
1797 (if hash (org-babel-hide-hash))
1798 (point)))))
1800 (defvar org-block-regexp)
1801 (defun org-babel-read-result ()
1802 "Read the result at `point' into emacs-lisp."
1803 (let ((case-fold-search t) result-string)
1804 (cond
1805 ((org-at-table-p) (org-babel-read-table))
1806 ((org-at-item-p) (org-babel-read-list))
1807 ((looking-at org-bracket-link-regexp) (org-babel-read-link))
1808 ((looking-at org-block-regexp) (org-babel-trim (match-string 4)))
1809 ((looking-at "^[ \t]*: ")
1810 (setq result-string
1811 (org-babel-trim
1812 (mapconcat (lambda (line)
1813 (if (and (> (length line) 1)
1814 (string-match "^[ \t]*: \\(.+\\)" line))
1815 (match-string 1 line)
1816 line))
1817 (split-string
1818 (buffer-substring
1819 (point) (org-babel-result-end)) "[\r\n]+")
1820 "\n")))
1821 (or (org-babel-number-p result-string) result-string))
1822 ((looking-at org-babel-result-regexp)
1823 (save-excursion (forward-line 1) (org-babel-read-result))))))
1825 (defun org-babel-read-table ()
1826 "Read the table at `point' into emacs-lisp."
1827 (mapcar (lambda (row)
1828 (if (and (symbolp row) (equal row 'hline)) row
1829 (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval)) row)))
1830 (org-table-to-lisp)))
1832 (defun org-babel-read-list ()
1833 "Read the list at `point' into emacs-lisp."
1834 (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval))
1835 (mapcar #'cadr (cdr (org-list-parse-list)))))
1837 (defvar org-link-types-re)
1838 (defun org-babel-read-link ()
1839 "Read the link at `point' into emacs-lisp.
1840 If the path of the link is a file path it is expanded using
1841 `expand-file-name'."
1842 (let* ((case-fold-search t)
1843 (raw (and (looking-at org-bracket-link-regexp)
1844 (org-no-properties (match-string 1))))
1845 (type (and (string-match org-link-types-re raw)
1846 (match-string 1 raw))))
1847 (cond
1848 ((not type) (expand-file-name raw))
1849 ((string= type "file")
1850 (and (string-match "file\\(.*\\):\\(.+\\)" raw)
1851 (expand-file-name (match-string 2 raw))))
1852 (t raw))))
1854 (defun org-babel-format-result (result &optional sep)
1855 "Format RESULT for writing to file."
1856 (let ((echo-res (lambda (r) (if (stringp r) r (format "%S" r)))))
1857 (if (listp result)
1858 ;; table result
1859 (orgtbl-to-generic
1860 result (list :sep (or sep "\t") :fmt echo-res))
1861 ;; scalar result
1862 (funcall echo-res result))))
1864 (defun org-babel-insert-result
1865 (result &optional result-params info hash indent lang)
1866 "Insert RESULT into the current buffer.
1867 By default RESULT is inserted after the end of the
1868 current source block. With optional argument RESULT-PARAMS
1869 controls insertion of results in the org-mode file.
1870 RESULT-PARAMS can take the following values:
1872 replace - (default option) insert results after the source block
1873 replacing any previously inserted results
1875 silent -- no results are inserted into the Org-mode buffer but
1876 the results are echoed to the minibuffer and are
1877 ingested by Emacs (a potentially time consuming
1878 process)
1880 file ---- the results are interpreted as a file path, and are
1881 inserted into the buffer using the Org-mode file syntax
1883 list ---- the results are interpreted as an Org-mode list.
1885 raw ----- results are added directly to the Org-mode file. This
1886 is a good option if you code block will output org-mode
1887 formatted text.
1889 drawer -- results are added directly to the Org-mode file as with
1890 \"raw\", but are wrapped in a RESULTS drawer, allowing
1891 them to later be replaced or removed automatically.
1893 org ----- results are added inside of a \"#+BEGIN_SRC org\" block.
1894 They are not comma-escaped when inserted, but Org syntax
1895 here will be discarded when exporting the file.
1897 html ---- results are added inside of a #+BEGIN_HTML block. This
1898 is a good option if you code block will output html
1899 formatted text.
1901 latex --- results are added inside of a #+BEGIN_LATEX block.
1902 This is a good option if you code block will output
1903 latex formatted text.
1905 code ---- the results are extracted in the syntax of the source
1906 code of the language being evaluated and are added
1907 inside of a #+BEGIN_SRC block with the source-code
1908 language set appropriately. Note this relies on the
1909 optional LANG argument."
1910 (if (stringp result)
1911 (progn
1912 (setq result (org-no-properties result))
1913 (when (member "file" result-params)
1914 (setq result (org-babel-result-to-file
1915 result (when (assoc :file-desc (nth 2 info))
1916 (or (cdr (assoc :file-desc (nth 2 info)))
1917 result))))))
1918 (unless (listp result) (setq result (format "%S" result))))
1919 (if (and result-params (member "silent" result-params))
1920 (progn
1921 (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
1922 result)
1923 (save-excursion
1924 (let* ((inlinep
1925 (save-excursion
1926 (when (or (org-babel-get-inline-src-block-matches)
1927 (org-babel-get-lob-one-liner-matches))
1928 (goto-char (match-end 0))
1929 (insert (if (listp result) "\n" " "))
1930 (point))))
1931 (existing-result (unless inlinep
1932 (org-babel-where-is-src-block-result
1933 t info hash indent)))
1934 (results-switches
1935 (cdr (assoc :results_switches (nth 2 info))))
1936 (visible-beg (copy-marker (point-min)))
1937 (visible-end (copy-marker (point-max)))
1938 ;; When results exist outside of the current visible
1939 ;; region of the buffer, be sure to widen buffer to
1940 ;; update them.
1941 (outside-scope-p (and existing-result
1942 (or (> visible-beg existing-result)
1943 (<= visible-end existing-result))))
1944 beg end)
1945 (when (and (stringp result) ; ensure results end in a newline
1946 (not inlinep)
1947 (> (length result) 0)
1948 (not (or (string-equal (substring result -1) "\n")
1949 (string-equal (substring result -1) "\r"))))
1950 (setq result (concat result "\n")))
1951 (unwind-protect
1952 (progn
1953 (when outside-scope-p (widen))
1954 (if (not existing-result)
1955 (setq beg (or inlinep (point)))
1956 (goto-char existing-result)
1957 (save-excursion
1958 (re-search-forward "#" nil t)
1959 (setq indent (- (current-column) 1)))
1960 (forward-line 1)
1961 (setq beg (point))
1962 (cond
1963 ((member "replace" result-params)
1964 (delete-region (point) (org-babel-result-end)))
1965 ((member "append" result-params)
1966 (goto-char (org-babel-result-end)) (setq beg (point-marker)))
1967 ((member "prepend" result-params)))) ; already there
1968 (setq results-switches
1969 (if results-switches (concat " " results-switches) ""))
1970 (let ((wrap (lambda (start finish &optional no-escape)
1971 (goto-char end) (insert (concat finish "\n"))
1972 (goto-char beg) (insert (concat start "\n"))
1973 (unless no-escape
1974 (org-escape-code-in-region (min (point) end) end))
1975 (goto-char end) (goto-char (point-at-eol))
1976 (setq end (point-marker))))
1977 (proper-list-p (lambda (it) (and (listp it) (null (cdr (last it)))))))
1978 ;; insert results based on type
1979 (cond
1980 ;; do nothing for an empty result
1981 ((null result))
1982 ;; insert a list if preferred
1983 ((member "list" result-params)
1984 (insert
1985 (org-babel-trim
1986 (org-list-to-generic
1987 (cons 'unordered
1988 (mapcar
1989 (lambda (el) (list nil (if (stringp el) el (format "%S" el))))
1990 (if (listp result) result (list result))))
1991 '(:splicep nil :istart "- " :iend "\n")))
1992 "\n"))
1993 ;; assume the result is a table if it's not a string
1994 ((funcall proper-list-p result)
1995 (goto-char beg)
1996 (insert (concat (orgtbl-to-orgtbl
1997 (if (or (eq 'hline (car result))
1998 (and (listp (car result))
1999 (listp (cdr (car result)))))
2000 result (list result))
2001 '(:fmt (lambda (cell) (format "%s" cell)))) "\n"))
2002 (goto-char beg) (when (org-at-table-p) (org-table-align)))
2003 ((and (listp result) (not (funcall proper-list-p result)))
2004 (insert (format "%s\n" result)))
2005 ((member "file" result-params)
2006 (when inlinep (goto-char inlinep))
2007 (insert result))
2008 (t (goto-char beg) (insert result)))
2009 (when (funcall proper-list-p result) (goto-char (org-table-end)))
2010 (setq end (point-marker))
2011 ;; possibly wrap result
2012 (cond
2013 ((assoc :wrap (nth 2 info))
2014 (let ((name (or (cdr (assoc :wrap (nth 2 info))) "RESULTS")))
2015 (funcall wrap (concat "#+BEGIN_" name)
2016 (concat "#+END_" (car (org-split-string name))))))
2017 ((member "html" result-params)
2018 (funcall wrap "#+BEGIN_HTML" "#+END_HTML"))
2019 ((member "latex" result-params)
2020 (funcall wrap "#+BEGIN_LaTeX" "#+END_LaTeX"))
2021 ((member "org" result-params)
2022 (funcall wrap "#+BEGIN_SRC org" "#+END_SRC"))
2023 ((member "code" result-params)
2024 (funcall wrap (format "#+BEGIN_SRC %s%s" (or lang "none") results-switches)
2025 "#+END_SRC"))
2026 ((member "raw" result-params)
2027 (goto-char beg) (if (org-at-table-p) (org-cycle)))
2028 ((or (member "drawer" result-params)
2029 ;; Stay backward compatible with <7.9.2
2030 (member "wrap" result-params))
2031 (funcall wrap ":RESULTS:" ":END:" 'no-escape))
2032 ((and (not (funcall proper-list-p result))
2033 (not (member "file" result-params)))
2034 (org-babel-examplize-region beg end results-switches)
2035 (setq end (point)))))
2036 ;; possibly indent the results to match the #+results line
2037 (when (and (not inlinep) (numberp indent) indent (> indent 0)
2038 ;; in this case `table-align' does the work for us
2039 (not (and (listp result)
2040 (member "append" result-params))))
2041 (indent-rigidly beg end indent))
2042 (if (null result)
2043 (if (member "value" result-params)
2044 (message "Code block returned no value.")
2045 (message "Code block produced no output."))
2046 (message "Code block evaluation complete.")))
2047 (when outside-scope-p (narrow-to-region visible-beg visible-end))
2048 (set-marker visible-beg nil)
2049 (set-marker visible-end nil))))))
2051 (defun org-babel-remove-result (&optional info)
2052 "Remove the result of the current source block."
2053 (interactive)
2054 (let ((location (org-babel-where-is-src-block-result nil info)) start)
2055 (when location
2056 (setq start (- location 1))
2057 (save-excursion
2058 (goto-char location) (forward-line 1)
2059 (delete-region start (org-babel-result-end))))))
2061 (defun org-babel-result-end ()
2062 "Return the point at the end of the current set of results."
2063 (save-excursion
2064 (cond
2065 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
2066 ((org-at-item-p) (let* ((struct (org-list-struct))
2067 (prvs (org-list-prevs-alist struct)))
2068 (org-list-get-list-end (point-at-bol) struct prvs)))
2069 ((let ((case-fold-search t)) (looking-at "^\\([ \t]*\\):results:"))
2070 (progn (re-search-forward (concat "^" (match-string 1) ":END:"))
2071 (forward-char 1) (point)))
2073 (let ((case-fold-search t))
2074 (if (looking-at (concat "[ \t]*#\\+begin_\\([^ \t\n\r]+\\)"))
2075 (progn (re-search-forward (concat "[ \t]*#\\+end_" (match-string 1))
2076 nil t)
2077 (forward-char 1))
2078 (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
2079 (forward-line 1))))
2080 (point)))))
2082 (defun org-babel-result-to-file (result &optional description)
2083 "Convert RESULT into an `org-mode' link with optional DESCRIPTION.
2084 If the `default-directory' is different from the containing
2085 file's directory then expand relative links."
2086 (when (stringp result)
2087 (format "[[file:%s]%s]"
2088 (if (and default-directory
2089 buffer-file-name
2090 (not (string= (expand-file-name default-directory)
2091 (expand-file-name
2092 (file-name-directory buffer-file-name)))))
2093 (expand-file-name result default-directory)
2094 result)
2095 (if description (concat "[" description "]") ""))))
2097 (defvar org-babel-capitalize-examplize-region-markers nil
2098 "Make true to capitalize begin/end example markers inserted by code blocks.")
2100 (defun org-babel-examplize-region (beg end &optional results-switches)
2101 "Comment out region using the inline '==' or ': ' org example quote."
2102 (interactive "*r")
2103 (let ((chars-between (lambda (b e)
2104 (not (string-match "^[\\s]*$" (buffer-substring b e)))))
2105 (maybe-cap (lambda (str) (if org-babel-capitalize-examplize-region-markers
2106 (upcase str) str))))
2107 (if (or (funcall chars-between (save-excursion (goto-char beg) (point-at-bol)) beg)
2108 (funcall chars-between end (save-excursion (goto-char end) (point-at-eol))))
2109 (save-excursion
2110 (goto-char beg)
2111 (insert (format "=%s=" (prog1 (buffer-substring beg end)
2112 (delete-region beg end)))))
2113 (let ((size (count-lines beg end)))
2114 (save-excursion
2115 (cond ((= size 0)) ; do nothing for an empty result
2116 ((< size org-babel-min-lines-for-block-output)
2117 (goto-char beg)
2118 (dotimes (n size)
2119 (beginning-of-line 1) (insert ": ") (forward-line 1)))
2121 (goto-char beg)
2122 (insert (if results-switches
2123 (format "%s%s\n"
2124 (funcall maybe-cap "#+begin_example")
2125 results-switches)
2126 (funcall maybe-cap "#+begin_example\n")))
2127 (if (markerp end) (goto-char end) (forward-char (- end beg)))
2128 (insert (funcall maybe-cap "#+end_example\n")))))))))
2130 (defun org-babel-update-block-body (new-body)
2131 "Update the body of the current code block to NEW-BODY."
2132 (if (not (org-babel-where-is-src-block-head))
2133 (error "Not in a source block")
2134 (save-match-data
2135 (replace-match (concat (org-babel-trim new-body) "\n") nil t nil 5))
2136 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
2138 (defun org-babel-merge-params (&rest plists)
2139 "Combine all parameter association lists in PLISTS.
2140 Later elements of PLISTS override the values of previous elements.
2141 This takes into account some special considerations for certain
2142 parameters when merging lists."
2143 (let* ((results-exclusive-groups
2144 (mapcar (lambda (group) (mapcar #'symbol-name group))
2145 (cdr (assoc 'results org-babel-common-header-args-w-values))))
2146 (exports-exclusive-groups
2147 (mapcar (lambda (group) (mapcar #'symbol-name group))
2148 (cdr (assoc 'exports org-babel-common-header-args-w-values))))
2149 (variable-index 0)
2150 (e-merge (lambda (exclusive-groups &rest result-params)
2151 ;; maintain exclusivity of mutually exclusive parameters
2152 (let (output)
2153 (mapc (lambda (new-params)
2154 (mapc (lambda (new-param)
2155 (mapc (lambda (exclusive-group)
2156 (when (member new-param exclusive-group)
2157 (mapcar (lambda (excluded-param)
2158 (setq output
2159 (delete
2160 excluded-param
2161 output)))
2162 exclusive-group)))
2163 exclusive-groups)
2164 (setq output (org-uniquify
2165 (cons new-param output))))
2166 new-params))
2167 result-params)
2168 output)))
2169 params results exports tangle noweb cache vars shebang comments padline)
2171 (mapc
2172 (lambda (plist)
2173 (mapc
2174 (lambda (pair)
2175 (case (car pair)
2176 (:var
2177 (let ((name (if (listp (cdr pair))
2178 (cadr pair)
2179 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
2180 (cdr pair))
2181 (intern (match-string 1 (cdr pair)))))))
2182 (if name
2183 (setq vars
2184 (append
2185 (if (member name (mapcar #'car vars))
2186 (delq nil
2187 (mapcar
2188 (lambda (p)
2189 (unless (equal (car p) name) p))
2190 vars))
2191 vars)
2192 (list (cons name pair))))
2193 ;; if no name is given and we already have named variables
2194 ;; then assign to named variables in order
2195 (if (and vars (nth variable-index vars))
2196 (prog1 (setf (cddr (nth variable-index vars))
2197 (concat (symbol-name
2198 (car (nth variable-index vars)))
2199 "=" (cdr pair)))
2200 (incf variable-index))
2201 (error "Variable \"%s\" must be assigned a default value"
2202 (cdr pair))))))
2203 (:results
2204 (setq results (funcall e-merge results-exclusive-groups
2205 results
2206 (split-string
2207 (let ((r (cdr pair)))
2208 (if (stringp r) r (eval r)))))))
2209 (:file
2210 (when (cdr pair)
2211 (setq results (funcall e-merge results-exclusive-groups
2212 results '("file")))
2213 (unless (or (member "both" exports)
2214 (member "none" exports)
2215 (member "code" exports))
2216 (setq exports (funcall e-merge exports-exclusive-groups
2217 exports '("results"))))
2218 (setq params (cons pair (assq-delete-all (car pair) params)))))
2219 (:exports
2220 (setq exports (funcall e-merge exports-exclusive-groups
2221 exports (split-string (cdr pair)))))
2222 (:tangle ;; take the latest -- always overwrite
2223 (setq tangle (or (list (cdr pair)) tangle)))
2224 (:noweb
2225 (setq noweb (funcall e-merge
2226 '(("yes" "no" "tangle" "no-export"
2227 "strip-export" "eval"))
2228 noweb
2229 (split-string (or (cdr pair) "")))))
2230 (:cache
2231 (setq cache (funcall e-merge '(("yes" "no")) cache
2232 (split-string (or (cdr pair) "")))))
2233 (:padline
2234 (setq padline (funcall e-merge '(("yes" "no")) padline
2235 (split-string (or (cdr pair) "")))))
2236 (:shebang ;; take the latest -- always overwrite
2237 (setq shebang (or (list (cdr pair)) shebang)))
2238 (:comments
2239 (setq comments (funcall e-merge '(("yes" "no")) comments
2240 (split-string (or (cdr pair) "")))))
2241 (t ;; replace: this covers e.g. :session
2242 (setq params (cons pair (assq-delete-all (car pair) params))))))
2243 plist))
2244 plists)
2245 (setq vars (reverse vars))
2246 (while vars (setq params (cons (cons :var (cddr (pop vars))) params)))
2247 (mapc
2248 (lambda (hd)
2249 (let ((key (intern (concat ":" (symbol-name hd))))
2250 (val (eval hd)))
2251 (setf params (cons (cons key (mapconcat 'identity val " ")) params))))
2252 '(results exports tangle noweb padline cache shebang comments))
2253 params))
2255 (defvar org-babel-use-quick-and-dirty-noweb-expansion nil
2256 "Set to true to use regular expressions to expand noweb references.
2257 This results in much faster noweb reference expansion but does
2258 not properly allow code blocks to inherit the \":noweb-ref\"
2259 header argument from buffer or subtree wide properties.")
2261 (defun org-babel-noweb-p (params context)
2262 "Check if PARAMS require expansion in CONTEXT.
2263 CONTEXT may be one of :tangle, :export or :eval."
2264 (let* (intersect
2265 (intersect (lambda (as bs)
2266 (when as
2267 (if (member (car as) bs)
2268 (car as)
2269 (funcall intersect (cdr as) bs))))))
2270 (funcall intersect (case context
2271 (:tangle '("yes" "tangle" "no-export" "strip-export"))
2272 (:eval '("yes" "no-export" "strip-export" "eval"))
2273 (:export '("yes")))
2274 (split-string (or (cdr (assoc :noweb params)) "")))))
2276 (defun org-babel-expand-noweb-references (&optional info parent-buffer)
2277 "Expand Noweb references in the body of the current source code block.
2279 For example the following reference would be replaced with the
2280 body of the source-code block named 'example-block'.
2282 <<example-block>>
2284 Note that any text preceding the <<foo>> construct on a line will
2285 be interposed between the lines of the replacement text. So for
2286 example if <<foo>> is placed behind a comment, then the entire
2287 replacement text will also be commented.
2289 This function must be called from inside of the buffer containing
2290 the source-code block which holds BODY.
2292 In addition the following syntax can be used to insert the
2293 results of evaluating the source-code block named 'example-block'.
2295 <<example-block()>>
2297 Any optional arguments can be passed to example-block by placing
2298 the arguments inside the parenthesis following the convention
2299 defined by `org-babel-lob'. For example
2301 <<example-block(a=9)>>
2303 would set the value of argument \"a\" equal to \"9\". Note that
2304 these arguments are not evaluated in the current source-code
2305 block but are passed literally to the \"example-block\"."
2306 (let* ((parent-buffer (or parent-buffer (current-buffer)))
2307 (info (or info (org-babel-get-src-block-info)))
2308 (lang (nth 0 info))
2309 (body (nth 1 info))
2310 (ob-nww-start org-babel-noweb-wrap-start)
2311 (ob-nww-end org-babel-noweb-wrap-end)
2312 (comment (string= "noweb" (cdr (assoc :comments (nth 2 info)))))
2313 (rx-prefix (concat "\\(" org-babel-src-name-regexp "\\|"
2314 ":noweb-ref[ \t]+" "\\)"))
2315 (new-body "")
2316 (nb-add (lambda (text) (setq new-body (concat new-body text))))
2317 (c-wrap (lambda (text)
2318 (with-temp-buffer
2319 (funcall (intern (concat lang "-mode")))
2320 (comment-region (point) (progn (insert text) (point)))
2321 (org-babel-trim (buffer-string)))))
2322 index source-name evaluate prefix blocks-in-buffer)
2323 (with-temp-buffer
2324 (org-set-local 'org-babel-noweb-wrap-start ob-nww-start)
2325 (org-set-local 'org-babel-noweb-wrap-end ob-nww-end)
2326 (insert body) (goto-char (point-min))
2327 (setq index (point))
2328 (while (and (re-search-forward (org-babel-noweb-wrap) nil t))
2329 (save-match-data (setf source-name (match-string 1)))
2330 (save-match-data (setq evaluate (string-match "\(.*\)" source-name)))
2331 (save-match-data
2332 (setq prefix
2333 (buffer-substring (match-beginning 0)
2334 (save-excursion
2335 (beginning-of-line 1) (point)))))
2336 ;; add interval to new-body (removing noweb reference)
2337 (goto-char (match-beginning 0))
2338 (funcall nb-add (buffer-substring index (point)))
2339 (goto-char (match-end 0))
2340 (setq index (point))
2341 (funcall nb-add
2342 (with-current-buffer parent-buffer
2343 (save-restriction
2344 (widen)
2345 (mapconcat ;; interpose PREFIX between every line
2346 #'identity
2347 (split-string
2348 (if evaluate
2349 (let ((raw (org-babel-ref-resolve source-name)))
2350 (if (stringp raw) raw (format "%S" raw)))
2352 ;; retrieve from the library of babel
2353 (nth 2 (assoc (intern source-name)
2354 org-babel-library-of-babel))
2355 ;; return the contents of headlines literally
2356 (save-excursion
2357 (when (org-babel-ref-goto-headline-id source-name)
2358 (org-babel-ref-headline-body)))
2359 ;; find the expansion of reference in this buffer
2360 (let ((rx (concat rx-prefix source-name "[ \t\n]"))
2361 expansion)
2362 (save-excursion
2363 (goto-char (point-min))
2364 (if org-babel-use-quick-and-dirty-noweb-expansion
2365 (while (re-search-forward rx nil t)
2366 (let* ((i (org-babel-get-src-block-info 'light))
2367 (body (org-babel-expand-noweb-references i))
2368 (sep (or (cdr (assoc :noweb-sep (nth 2 i)))
2369 "\n"))
2370 (full (if comment
2371 ((lambda (cs)
2372 (concat (funcall c-wrap (car cs)) "\n"
2373 body "\n"
2374 (funcall c-wrap (cadr cs))))
2375 (org-babel-tangle-comment-links i))
2376 body)))
2377 (setq expansion (cons sep (cons full expansion)))))
2378 (org-babel-map-src-blocks nil
2379 (let ((i (org-babel-get-src-block-info 'light)))
2380 (when (equal (or (cdr (assoc :noweb-ref (nth 2 i)))
2381 (nth 4 i))
2382 source-name)
2383 (let* ((body (org-babel-expand-noweb-references i))
2384 (sep (or (cdr (assoc :noweb-sep (nth 2 i)))
2385 "\n"))
2386 (full (if comment
2387 ((lambda (cs)
2388 (concat (funcall c-wrap (car cs)) "\n"
2389 body "\n"
2390 (funcall c-wrap (cadr cs))))
2391 (org-babel-tangle-comment-links i))
2392 body)))
2393 (setq expansion
2394 (cons sep (cons full expansion)))))))))
2395 (and expansion
2396 (mapconcat #'identity (nreverse (cdr expansion)) "")))
2397 ;; possibly raise an error if named block doesn't exist
2398 (if (member lang org-babel-noweb-error-langs)
2399 (error "%s" (concat
2400 (org-babel-noweb-wrap source-name)
2401 "could not be resolved (see "
2402 "`org-babel-noweb-error-langs')"))
2403 "")))
2404 "[\n\r]") (concat "\n" prefix))))))
2405 (funcall nb-add (buffer-substring index (point-max))))
2406 new-body))
2408 (defun org-babel-script-escape (str &optional force)
2409 "Safely convert tables into elisp lists."
2410 (let (in-single in-double out)
2411 ((lambda (escaped) (condition-case nil (org-babel-read escaped) (error escaped)))
2412 (if (or force
2413 (and (stringp str)
2414 (> (length str) 2)
2415 (or (and (string-equal "[" (substring str 0 1))
2416 (string-equal "]" (substring str -1)))
2417 (and (string-equal "{" (substring str 0 1))
2418 (string-equal "}" (substring str -1)))
2419 (and (string-equal "(" (substring str 0 1))
2420 (string-equal ")" (substring str -1))))))
2421 (org-babel-read
2422 (concat
2424 (progn
2425 (mapc
2426 (lambda (ch)
2427 (setq
2429 (case ch
2430 (91 (if (or in-double in-single) ; [
2431 (cons 91 out)
2432 (cons 40 out)))
2433 (93 (if (or in-double in-single) ; ]
2434 (cons 93 out)
2435 (cons 41 out)))
2436 (123 (if (or in-double in-single) ; {
2437 (cons 123 out)
2438 (cons 40 out)))
2439 (125 (if (or in-double in-single) ; }
2440 (cons 125 out)
2441 (cons 41 out)))
2442 (44 (if (or in-double in-single) ; ,
2443 (cons 44 out) (cons 32 out)))
2444 (39 (if in-double ; '
2445 (cons 39 out)
2446 (setq in-single (not in-single)) (cons 34 out)))
2447 (34 (if in-single ; "
2448 (append (list 34 32) out)
2449 (setq in-double (not in-double)) (cons 34 out)))
2450 (t (cons ch out)))))
2451 (string-to-list str))
2452 (apply #'string (reverse out)))))
2453 str))))
2455 (defun org-babel-read (cell &optional inhibit-lisp-eval)
2456 "Convert the string value of CELL to a number if appropriate.
2457 Otherwise if cell looks like lisp (meaning it starts with a
2458 \"(\", \"'\", \"`\" or a \"[\") then read it as lisp, otherwise
2459 return it unmodified as a string. Optional argument NO-LISP-EVAL
2460 inhibits lisp evaluation for situations in which is it not
2461 appropriate."
2462 (if (and (stringp cell) (not (equal cell "")))
2463 (or (org-babel-number-p cell)
2464 (if (and (not inhibit-lisp-eval)
2465 (member (substring cell 0 1) '("(" "'" "`" "[")))
2466 (eval (read cell))
2467 (if (string= (substring cell 0 1) "\"")
2468 (read cell)
2469 (progn (set-text-properties 0 (length cell) nil cell) cell))))
2470 cell))
2472 (defun org-babel-number-p (string)
2473 "If STRING represents a number return its value."
2474 (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string)
2475 (= (length (substring string (match-beginning 0)
2476 (match-end 0)))
2477 (length string)))
2478 (string-to-number string)))
2480 (defun org-babel-import-elisp-from-file (file-name &optional separator)
2481 "Read the results located at FILE-NAME into an elisp table.
2482 If the table is trivial, then return it as a scalar."
2483 (let (result)
2484 (save-window-excursion
2485 (with-temp-buffer
2486 (condition-case err
2487 (progn
2488 (org-table-import file-name separator)
2489 (delete-file file-name)
2490 (setq result (mapcar (lambda (row)
2491 (mapcar #'org-babel-string-read row))
2492 (org-table-to-lisp))))
2493 (error (message "Error reading results: %s" err) nil)))
2494 (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
2495 (if (consp (car result))
2496 (if (null (cdr (car result)))
2497 (caar result)
2498 result)
2499 (car result))
2500 result))))
2502 (defun org-babel-string-read (cell)
2503 "Strip nested \"s from around strings."
2504 (org-babel-read (or (and (stringp cell)
2505 (string-match "\\\"\\(.+\\)\\\"" cell)
2506 (match-string 1 cell))
2507 cell) t))
2509 (defun org-babel-chomp (string &optional regexp)
2510 "Strip trailing spaces and carriage returns from STRING.
2511 Default regexp used is \"[ \f\t\n\r\v]\" but can be
2512 overwritten by specifying a regexp as a second argument."
2513 (let ((regexp (or regexp "[ \f\t\n\r\v]")))
2514 (while (and (> (length string) 0)
2515 (string-match regexp (substring string -1)))
2516 (setq string (substring string 0 -1)))
2517 string))
2519 (defun org-babel-trim (string &optional regexp)
2520 "Strip leading and trailing spaces and carriage returns from STRING.
2521 Like `org-babel-chomp' only it runs on both the front and back
2522 of the string."
2523 (org-babel-chomp (org-reverse-string
2524 (org-babel-chomp (org-reverse-string string) regexp))
2525 regexp))
2527 (defvar org-babel-org-babel-call-process-region-original nil)
2528 (defun org-babel-tramp-handle-call-process-region
2529 (start end program &optional delete buffer display &rest args)
2530 "Use Tramp to handle `call-process-region'.
2531 Fixes a bug in `tramp-handle-call-process-region'."
2532 (if (and (featurep 'tramp) (file-remote-p default-directory))
2533 (let ((tmpfile (tramp-compat-make-temp-file "")))
2534 (write-region start end tmpfile)
2535 (when delete (delete-region start end))
2536 (unwind-protect
2537 ;; (apply 'call-process program tmpfile buffer display args)
2538 ;; bug in tramp
2539 (apply 'process-file program tmpfile buffer display args)
2540 (delete-file tmpfile)))
2541 ;; org-babel-call-process-region-original is the original emacs
2542 ;; definition. It is in scope from the let binding in
2543 ;; org-babel-execute-src-block
2544 (apply org-babel-call-process-region-original
2545 start end program delete buffer display args)))
2547 (defun org-babel-local-file-name (file)
2548 "Return the local name component of FILE."
2549 (if (file-remote-p file)
2550 (let (localname)
2551 (with-parsed-tramp-file-name file nil
2552 localname))
2553 file))
2555 (defun org-babel-process-file-name (name &optional no-quote-p)
2556 "Prepare NAME to be used in an external process.
2557 If NAME specifies a remote location, the remote portion of the
2558 name is removed, since in that case the process will be executing
2559 remotely. The file name is then processed by `expand-file-name'.
2560 Unless second argument NO-QUOTE-P is non-nil, the file name is
2561 additionally processed by `shell-quote-argument'"
2562 ((lambda (f) (if no-quote-p f (shell-quote-argument f)))
2563 (expand-file-name (org-babel-local-file-name name))))
2565 (defvar org-babel-temporary-directory)
2566 (unless (or noninteractive (boundp 'org-babel-temporary-directory))
2567 (defvar org-babel-temporary-directory
2568 (or (and (boundp 'org-babel-temporary-directory)
2569 (file-exists-p org-babel-temporary-directory)
2570 org-babel-temporary-directory)
2571 (make-temp-file "babel-" t))
2572 "Directory to hold temporary files created to execute code blocks.
2573 Used by `org-babel-temp-file'. This directory will be removed on
2574 Emacs shutdown."))
2576 (defmacro org-babel-result-cond (result-params scalar-form &rest table-forms)
2577 "Call the code to parse raw string results according to RESULT-PARAMS."
2578 (declare (indent 1)
2579 (debug (form form &rest form)))
2580 `(unless (member "none" ,result-params)
2581 (if (or (member "scalar" ,result-params)
2582 (member "verbatim" ,result-params)
2583 (member "html" ,result-params)
2584 (member "code" ,result-params)
2585 (member "pp" ,result-params)
2586 (and (member "output" ,result-params)
2587 (not (member "table" ,result-params))))
2588 ,scalar-form
2589 ,@table-forms)))
2591 (defun org-babel-temp-file (prefix &optional suffix)
2592 "Create a temporary file in the `org-babel-temporary-directory'.
2593 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2594 value of `temporary-file-directory' temporarily set to the value
2595 of `org-babel-temporary-directory'."
2596 (let ((temporary-file-directory
2597 (if (file-remote-p default-directory)
2598 (concat (file-remote-p default-directory) "/tmp")
2599 (or (and (boundp 'org-babel-temporary-directory)
2600 (file-exists-p org-babel-temporary-directory)
2601 org-babel-temporary-directory)
2602 temporary-file-directory))))
2603 (make-temp-file prefix nil suffix)))
2605 (defun org-babel-remove-temporary-directory ()
2606 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2607 (when (and (boundp 'org-babel-temporary-directory)
2608 (file-exists-p org-babel-temporary-directory))
2609 ;; taken from `delete-directory' in files.el
2610 (condition-case nil
2611 (progn
2612 (mapc (lambda (file)
2613 ;; This test is equivalent to
2614 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2615 ;; but more efficient
2616 (if (eq t (car (file-attributes file)))
2617 (delete-directory file)
2618 (delete-file file)))
2619 ;; We do not want to delete "." and "..".
2620 (directory-files org-babel-temporary-directory 'full
2621 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2622 (delete-directory org-babel-temporary-directory))
2623 (error
2624 (message "Failed to remove temporary Org-babel directory %s"
2625 (if (boundp 'org-babel-temporary-directory)
2626 org-babel-temporary-directory
2627 "[directory not defined]"))))))
2629 (add-hook 'kill-emacs-hook 'org-babel-remove-temporary-directory)
2631 (provide 'ob-core)
2633 ;; Local variables:
2634 ;; generated-autoload-file: "org-loaddefs.el"
2635 ;; End:
2637 ;;; ob-core.el ends here