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