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