use batch-byte-recompile-directory instead of batch-byte-compile
[org-mode/org-tableheadings.git] / lisp / ob.el
blob160c63ac5bceda589735a3b3a6d850d6684377f5
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)) 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 (under-point (thing-at-point 'line)))
1505 (list (org-icompleting-read
1506 "source-block name: " (org-babel-src-block-names) nil t
1507 (cond
1508 ;; noweb
1509 ((string-match (org-babel-noweb-wrap) under-point)
1510 (let ((block-name (match-string 1 under-point)))
1511 (string-match "[^(]*" block-name)
1512 (match-string 0 block-name)))
1513 ;; #+call:
1514 ((string-match org-babel-lob-one-liner-regexp under-point)
1515 (let ((source-info (car (org-babel-lob-get-info))))
1516 (if (string-match "^\\([^\\[]+?\\)\\(\\[.*\\]\\)?(" source-info)
1517 (let ((source-name (match-string 1 source-info)))
1518 source-name))))
1519 ;; #+results:
1520 ((string-match (concat "#\\+" org-babel-results-keyword
1521 "\\:\s+\\([^\\(]*\\)") under-point)
1522 (match-string 1 under-point))
1523 ;; symbol-at-point
1524 ((and (thing-at-point 'symbol))
1525 (org-babel-find-named-block (thing-at-point 'symbol))
1526 (thing-at-point 'symbol))
1527 (""))))))
1528 (let ((point (org-babel-find-named-block name)))
1529 (if point
1530 ;; taken from `org-open-at-point'
1531 (progn (org-mark-ring-push) (goto-char point) (org-show-context))
1532 (message "source-code block '%s' not found in this buffer" name))))
1534 (defun org-babel-find-named-block (name)
1535 "Find a named source-code block.
1536 Return the location of the source block identified by source
1537 NAME, or nil if no such block exists. Set match data according to
1538 org-babel-named-src-block-regexp."
1539 (save-excursion
1540 (let ((case-fold-search t)
1541 (regexp (org-babel-named-src-block-regexp-for-name name)) msg)
1542 (goto-char (point-min))
1543 (when (or (re-search-forward regexp nil t)
1544 (re-search-backward regexp nil t))
1545 (match-beginning 0)))))
1547 (defun org-babel-src-block-names (&optional file)
1548 "Returns the names of source blocks in FILE or the current buffer."
1549 (save-excursion
1550 (when file (find-file file)) (goto-char (point-min))
1551 (let (names)
1552 (while (re-search-forward org-babel-src-name-w-name-regexp nil t)
1553 (setq names (cons (match-string 3) names)))
1554 names)))
1556 ;;;###autoload
1557 (defun org-babel-goto-named-result (name)
1558 "Go to a named result."
1559 (interactive
1560 (let ((completion-ignore-case t))
1561 (list (org-icompleting-read "source-block name: "
1562 (org-babel-result-names) nil t))))
1563 (let ((point (org-babel-find-named-result name)))
1564 (if point
1565 ;; taken from `org-open-at-point'
1566 (progn (goto-char point) (org-show-context))
1567 (message "result '%s' not found in this buffer" name))))
1569 (defun org-babel-find-named-result (name &optional point)
1570 "Find a named result.
1571 Return the location of the result named NAME in the current
1572 buffer or nil if no such result exists."
1573 (save-excursion
1574 (goto-char (or point (point-min)))
1575 (catch 'is-a-code-block
1576 (when (re-search-forward
1577 (concat org-babel-result-regexp
1578 "[ \t]" (regexp-quote name) "[ \t\n\f\v\r]+") nil t)
1579 (when (and (string= "name" (downcase (match-string 1)))
1580 (or (beginning-of-line 1)
1581 (looking-at org-babel-src-block-regexp)
1582 (looking-at org-babel-multi-line-header-regexp)))
1583 (throw 'is-a-code-block (org-babel-find-named-result name (point))))
1584 (beginning-of-line 0) (point)))))
1586 (defun org-babel-result-names (&optional file)
1587 "Returns the names of results in FILE or the current buffer."
1588 (save-excursion
1589 (when file (find-file file)) (goto-char (point-min))
1590 (let (names)
1591 (while (re-search-forward org-babel-result-w-name-regexp nil t)
1592 (setq names (cons (match-string 4) names)))
1593 names)))
1595 ;;;###autoload
1596 (defun org-babel-next-src-block (&optional arg)
1597 "Jump to the next source block.
1598 With optional prefix argument ARG, jump forward ARG many source blocks."
1599 (interactive "P")
1600 (when (looking-at org-babel-src-block-regexp) (forward-char 1))
1601 (condition-case nil
1602 (re-search-forward org-babel-src-block-regexp nil nil (or arg 1))
1603 (error (error "No further code blocks")))
1604 (goto-char (match-beginning 0)) (org-show-context))
1606 ;;;###autoload
1607 (defun org-babel-previous-src-block (&optional arg)
1608 "Jump to the previous source block.
1609 With optional prefix argument ARG, jump backward ARG many source blocks."
1610 (interactive "P")
1611 (condition-case nil
1612 (re-search-backward org-babel-src-block-regexp nil nil (or arg 1))
1613 (error (error "No previous code blocks")))
1614 (goto-char (match-beginning 0)) (org-show-context))
1616 (defvar org-babel-load-languages)
1618 ;;;###autoload
1619 (defun org-babel-mark-block ()
1620 "Mark current src block"
1621 (interactive)
1622 ((lambda (head)
1623 (when head
1624 (save-excursion
1625 (goto-char head)
1626 (looking-at org-babel-src-block-regexp))
1627 (push-mark (match-end 5) nil t)
1628 (goto-char (match-beginning 5))))
1629 (org-babel-where-is-src-block-head)))
1631 (defun org-babel-demarcate-block (&optional arg)
1632 "Wrap or split the code in the region or on the point.
1633 When called from inside of a code block the current block is
1634 split. When called from outside of a code block a new code block
1635 is created. In both cases if the region is demarcated and if the
1636 region is not active then the point is demarcated."
1637 (interactive "P")
1638 (let ((info (org-babel-get-src-block-info 'light))
1639 (headers (progn (org-babel-where-is-src-block-head)
1640 (match-string 4)))
1641 (stars (concat (make-string (or (org-current-level) 1) ?*) " ")))
1642 (if info
1643 (mapc
1644 (lambda (place)
1645 (save-excursion
1646 (goto-char place)
1647 (let ((lang (nth 0 info))
1648 (indent (make-string (nth 5 info) ? )))
1649 (when (string-match "^[[:space:]]*$"
1650 (buffer-substring (point-at-bol)
1651 (point-at-eol)))
1652 (delete-region (point-at-bol) (point-at-eol)))
1653 (insert (concat
1654 (if (looking-at "^") "" "\n")
1655 indent "#+end_src\n"
1656 (if arg stars indent) "\n"
1657 indent "#+begin_src " lang
1658 (if (> (length headers) 1)
1659 (concat " " headers) headers)
1660 (if (looking-at "[\n\r]")
1662 (concat "\n" (make-string (current-column) ? )))))))
1663 (move-end-of-line 2))
1664 (sort (if (region-active-p) (list (mark) (point)) (list (point))) #'>))
1665 (let ((start (point))
1666 (lang (org-icompleting-read "Lang: "
1667 (mapcar (lambda (el) (symbol-name (car el)))
1668 org-babel-load-languages)))
1669 (body (delete-and-extract-region
1670 (if (region-active-p) (mark) (point)) (point))))
1671 (insert (concat (if (looking-at "^") "" "\n")
1672 (if arg (concat stars "\n") "")
1673 "#+begin_src " lang "\n"
1674 body
1675 (if (or (= (length body) 0)
1676 (string-match "[\r\n]$" body)) "" "\n")
1677 "#+end_src\n"))
1678 (goto-char start) (move-end-of-line 1)))))
1680 (defvar org-babel-lob-one-liner-regexp)
1681 (defun org-babel-where-is-src-block-result (&optional insert info hash indent)
1682 "Find where the current source block results begin.
1683 Return the point at the beginning of the result of the current
1684 source block. Specifically at the beginning of the results line.
1685 If no result exists for this block then create a results line
1686 following the source block."
1687 (save-excursion
1688 (let* ((on-lob-line (save-excursion
1689 (beginning-of-line 1)
1690 (looking-at org-babel-lob-one-liner-regexp)))
1691 (inlinep (when (org-babel-get-inline-src-block-matches)
1692 (match-end 0)))
1693 (name (if on-lob-line
1694 (mapconcat #'identity (butlast (org-babel-lob-get-info)) "")
1695 (nth 4 (or info (org-babel-get-src-block-info 'light)))))
1696 (head (unless on-lob-line (org-babel-where-is-src-block-head)))
1697 found beg end)
1698 (when head (goto-char head))
1699 (setq
1700 found ;; was there a result (before we potentially insert one)
1702 inlinep
1703 (and
1704 ;; named results:
1705 ;; - return t if it is found, else return nil
1706 ;; - if it does not need to be rebuilt, then don't set end
1707 ;; - if it does need to be rebuilt then do set end
1708 name (setq beg (org-babel-find-named-result name))
1709 (prog1 beg
1710 (when (and hash (not (string= hash (match-string 3))))
1711 (goto-char beg) (setq end beg) ;; beginning of result
1712 (forward-line 1)
1713 (delete-region end (org-babel-result-end)) nil)))
1714 (and
1715 ;; unnamed results:
1716 ;; - return t if it is found, else return nil
1717 ;; - if it is found, and the hash doesn't match, delete and set end
1718 (or on-lob-line (re-search-forward "^[ \t]*#\\+end_src" nil t))
1719 (progn (end-of-line 1)
1720 (if (eobp) (insert "\n") (forward-char 1))
1721 (setq end (point))
1722 (or (and (not name)
1723 (progn ;; unnamed results line already exists
1724 (re-search-forward "[^ \f\t\n\r\v]" nil t)
1725 (beginning-of-line 1)
1726 (looking-at
1727 (concat org-babel-result-regexp "\n")))
1728 (prog1 (point)
1729 ;; must remove and rebuild if hash!=old-hash
1730 (if (and hash (not (string= hash (match-string 3))))
1731 (prog1 nil
1732 (forward-line 1)
1733 (delete-region
1734 end (org-babel-result-end)))
1735 (setq end nil)))))))))
1736 (if (and insert end)
1737 (progn
1738 (goto-char end)
1739 (unless beg
1740 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1741 (insert (concat
1742 (if indent
1743 (mapconcat
1744 (lambda (el) " ")
1745 (org-number-sequence 1 indent) "")
1747 "#+" org-babel-results-keyword
1748 (when hash (concat "["hash"]"))
1750 (when name (concat " " name)) "\n"))
1751 (unless beg (insert "\n") (backward-char))
1752 (beginning-of-line 0)
1753 (if hash (org-babel-hide-hash))
1754 (point))
1755 found))))
1757 (defvar org-block-regexp)
1758 (defun org-babel-read-result ()
1759 "Read the result at `point' into emacs-lisp."
1760 (let ((case-fold-search t) result-string)
1761 (cond
1762 ((org-at-table-p) (org-babel-read-table))
1763 ((org-at-item-p) (org-babel-read-list))
1764 ((looking-at org-bracket-link-regexp) (org-babel-read-link))
1765 ((looking-at org-block-regexp) (org-babel-trim (match-string 4)))
1766 ((looking-at "^[ \t]*: ")
1767 (setq result-string
1768 (org-babel-trim
1769 (mapconcat (lambda (line)
1770 (if (and (> (length line) 1)
1771 (string-match "^[ \t]*: \\(.+\\)" line))
1772 (match-string 1 line)
1773 line))
1774 (split-string
1775 (buffer-substring
1776 (point) (org-babel-result-end)) "[\r\n]+")
1777 "\n")))
1778 (or (org-babel-number-p result-string) result-string))
1779 ((looking-at org-babel-result-regexp)
1780 (save-excursion (forward-line 1) (org-babel-read-result))))))
1782 (defun org-babel-read-table ()
1783 "Read the table at `point' into emacs-lisp."
1784 (mapcar (lambda (row)
1785 (if (and (symbolp row) (equal row 'hline)) row
1786 (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval)) row)))
1787 (org-table-to-lisp)))
1789 (defun org-babel-read-list ()
1790 "Read the list at `point' into emacs-lisp."
1791 (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval))
1792 (mapcar #'cadr (cdr (org-list-parse-list)))))
1794 (defvar org-link-types-re)
1795 (defun org-babel-read-link ()
1796 "Read the link at `point' into emacs-lisp.
1797 If the path of the link is a file path it is expanded using
1798 `expand-file-name'."
1799 (let* ((case-fold-search t)
1800 (raw (and (looking-at org-bracket-link-regexp)
1801 (org-babel-clean-text-properties (match-string 1))))
1802 (type (and (string-match org-link-types-re raw)
1803 (match-string 1 raw))))
1804 (cond
1805 ((not type) (expand-file-name raw))
1806 ((string= type "file")
1807 (and (string-match "file\\(.*\\):\\(.+\\)" raw)
1808 (expand-file-name (match-string 2 raw))))
1809 (t raw))))
1811 (defun org-babel-format-result (result &optional sep)
1812 "Format RESULT for writing to file."
1813 (flet ((echo-res (result)
1814 (if (stringp result) result (format "%S" result))))
1815 (if (listp result)
1816 ;; table result
1817 (orgtbl-to-generic
1818 result
1819 (list
1820 :sep (or sep "\t")
1821 :fmt 'echo-res))
1822 ;; scalar result
1823 (echo-res result))))
1825 (defun org-babel-insert-result
1826 (result &optional result-params info hash indent lang)
1827 "Insert RESULT into the current buffer.
1828 By default RESULT is inserted after the end of the
1829 current source block. With optional argument RESULT-PARAMS
1830 controls insertion of results in the org-mode file.
1831 RESULT-PARAMS can take the following values...
1833 replace - (default option) insert results after the source block
1834 replacing any previously inserted results
1836 silent -- no results are inserted
1838 file ---- the results are interpreted as a file path, and are
1839 inserted into the buffer using the Org-mode file syntax
1841 list ---- the results are interpreted as an Org-mode list.
1843 raw ----- results are added directly to the Org-mode file. This
1844 is a good option if you code block will output org-mode
1845 formatted text.
1847 wrap ---- results are added directly to the Org-mode file as with
1848 \"raw\", but are wrapped in a RESULTS drawer, allowing
1849 them to later be replaced or removed automatically.
1851 org ----- similar in effect to raw, only the results are wrapped
1852 in an org code block. Similar to the raw option, on
1853 export the results will be interpreted as org-formatted
1854 text, however by wrapping the results in an org code
1855 block they can be replaced upon re-execution of the
1856 code block.
1858 html ---- results are added inside of a #+BEGIN_HTML block. This
1859 is a good option if you code block will output html
1860 formatted text.
1862 latex --- results are added inside of a #+BEGIN_LATEX block.
1863 This is a good option if you code block will output
1864 latex formatted text.
1866 code ---- the results are extracted in the syntax of the source
1867 code of the language being evaluated and are added
1868 inside of a #+BEGIN_SRC block with the source-code
1869 language set appropriately. Note this relies on the
1870 optional LANG argument."
1871 (if (stringp result)
1872 (progn
1873 (setq result (org-babel-clean-text-properties result))
1874 (when (member "file" result-params)
1875 (setq result (org-babel-result-to-file
1876 result (when (assoc :file-desc (nth 2 info))
1877 (or (cdr (assoc :file-desc (nth 2 info)))
1878 result))))))
1879 (unless (listp result) (setq result (format "%S" result))))
1880 (if (and result-params (member "silent" result-params))
1881 (progn
1882 (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
1883 result)
1884 (save-excursion
1885 (let* ((inlinep
1886 (save-excursion
1887 (when (or (org-babel-get-inline-src-block-matches)
1888 (org-babel-get-lob-one-liner-matches))
1889 (goto-char (match-end 0))
1890 (insert (if (listp result) "\n" " "))
1891 (point))))
1892 (existing-result (unless inlinep
1893 (org-babel-where-is-src-block-result
1894 t info hash indent)))
1895 (results-switches
1896 (cdr (assoc :results_switches (nth 2 info))))
1897 beg end)
1898 (when (and (stringp result) ; ensure results end in a newline
1899 (not inlinep)
1900 (> (length result) 0)
1901 (not (or (string-equal (substring result -1) "\n")
1902 (string-equal (substring result -1) "\r"))))
1903 (setq result (concat result "\n")))
1904 (if (not existing-result)
1905 (setq beg (or inlinep (point)))
1906 (goto-char existing-result)
1907 (save-excursion
1908 (re-search-forward "#" nil t)
1909 (setq indent (- (current-column) 1)))
1910 (forward-line 1)
1911 (setq beg (point))
1912 (cond
1913 ((member "replace" result-params)
1914 (delete-region (point) (org-babel-result-end)))
1915 ((member "append" result-params)
1916 (goto-char (org-babel-result-end)) (setq beg (point-marker)))
1917 ((member "prepend" result-params)))) ; already there
1918 (setq results-switches
1919 (if results-switches (concat " " results-switches) ""))
1920 (flet ((wrap (start finish)
1921 (goto-char end) (insert (concat finish "\n"))
1922 (goto-char beg) (insert (concat start "\n"))
1923 (goto-char end) (goto-char (point-at-eol))
1924 (setq end (point-marker)))
1925 (proper-list-p (it) (and (listp it) (null (cdr (last it))))))
1926 ;; insert results based on type
1927 (cond
1928 ;; do nothing for an empty result
1929 ((null result))
1930 ;; insert a list if preferred
1931 ((member "list" result-params)
1932 (insert
1933 (org-babel-trim
1934 (org-list-to-generic
1935 (cons 'unordered
1936 (mapcar
1937 (lambda (el) (list nil (if (stringp el) el (format "%S" el))))
1938 (if (listp result) result (list result))))
1939 '(:splicep nil :istart "- " :iend "\n")))
1940 "\n"))
1941 ;; assume the result is a table if it's not a string
1942 ((proper-list-p result)
1943 (goto-char beg)
1944 (insert (concat (orgtbl-to-orgtbl
1945 (if (or (eq 'hline (car result))
1946 (and (listp (car result))
1947 (listp (cdr (car result)))))
1948 result (list result))
1949 '(:fmt (lambda (cell) (format "%s" cell)))) "\n"))
1950 (goto-char beg) (when (org-at-table-p) (org-table-align)))
1951 ((and (listp result) (not (proper-list-p result)))
1952 (insert (format "%s\n" result)))
1953 ((member "file" result-params)
1954 (when inlinep (goto-char inlinep))
1955 (insert result))
1956 (t (goto-char beg) (insert result)))
1957 (when (proper-list-p result) (goto-char (org-table-end)))
1958 (setq end (point-marker))
1959 ;; possibly wrap result
1960 (cond
1961 ((assoc :wrap (nth 2 info))
1962 (let ((name (or (cdr (assoc :wrap (nth 2 info))) "RESULTS")))
1963 (wrap (concat "#+BEGIN_" name) (concat "#+END_" name))))
1964 ((member "html" result-params)
1965 (wrap "#+BEGIN_HTML" "#+END_HTML"))
1966 ((member "latex" result-params)
1967 (wrap "#+BEGIN_LaTeX" "#+END_LaTeX"))
1968 ((member "code" result-params)
1969 (wrap (format "#+BEGIN_SRC %s%s" (or lang "none") results-switches)
1970 "#+END_SRC"))
1971 ((member "org" result-params)
1972 (wrap "#+BEGIN_ORG" "#+END_ORG"))
1973 ((member "raw" result-params)
1974 (goto-char beg) (if (org-at-table-p) (org-cycle)))
1975 ((member "wrap" result-params)
1976 (wrap ":RESULTS:" ":END:"))
1977 ((and (not (proper-list-p result))
1978 (not (member "file" result-params)))
1979 (org-babel-examplize-region beg end results-switches)
1980 (setq end (point)))))
1981 ;; possibly indent the results to match the #+results line
1982 (when (and (not inlinep) (numberp indent) indent (> indent 0)
1983 ;; in this case `table-align' does the work for us
1984 (not (and (listp result)
1985 (member "append" result-params))))
1986 (indent-rigidly beg end indent))))
1987 (if (null result)
1988 (if (member "value" result-params)
1989 (message "Code block returned no value.")
1990 (message "Code block produced no output."))
1991 (message "Code block evaluation complete."))))
1993 (defun org-babel-remove-result (&optional info)
1994 "Remove the result of the current source block."
1995 (interactive)
1996 (let ((location (org-babel-where-is-src-block-result nil info)) start)
1997 (when location
1998 (setq start (- location 1))
1999 (save-excursion
2000 (goto-char location) (forward-line 1)
2001 (delete-region start (org-babel-result-end))))))
2003 (defun org-babel-result-end ()
2004 "Return the point at the end of the current set of results"
2005 (save-excursion
2006 (cond
2007 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
2008 ((org-at-item-p) (let* ((struct (org-list-struct))
2009 (prvs (org-list-prevs-alist struct)))
2010 (org-list-get-list-end (point-at-bol) struct prvs)))
2011 ((looking-at "^\\([ \t]*\\):RESULTS:")
2012 (progn (re-search-forward (concat "^" (match-string 1) ":END:"))
2013 (forward-char 1) (point)))
2015 (let ((case-fold-search t))
2016 (if (looking-at (concat "[ \t]*#\\+begin_\\([^ \t\n\r]+\\)"))
2017 (progn (re-search-forward (concat "[ \t]*#\\+end_" (match-string 1))
2018 nil t)
2019 (forward-char 1))
2020 (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
2021 (forward-line 1))))
2022 (point)))))
2024 (defun org-babel-result-to-file (result &optional description)
2025 "Convert RESULT into an `org-mode' link with optional DESCRIPTION.
2026 If the `default-directory' is different from the containing
2027 file's directory then expand relative links."
2028 (when (stringp result)
2029 (format "[[file:%s]%s]"
2030 (if (and default-directory
2031 buffer-file-name
2032 (not (string= (expand-file-name default-directory)
2033 (expand-file-name
2034 (file-name-directory buffer-file-name)))))
2035 (expand-file-name result default-directory)
2036 result)
2037 (if description (concat "[" description "]") ""))))
2039 (defun org-babel-examplize-region (beg end &optional results-switches)
2040 "Comment out region using the inline '==' or ': ' org example quote."
2041 (interactive "*r")
2042 (flet ((chars-between (b e)
2043 (not (string-match "^[\\s]*$" (buffer-substring b e)))))
2044 (if (or (chars-between (save-excursion (goto-char beg) (point-at-bol)) beg)
2045 (chars-between end (save-excursion (goto-char end) (point-at-eol))))
2046 (save-excursion
2047 (goto-char beg)
2048 (insert (format "=%s=" (prog1 (buffer-substring beg end)
2049 (delete-region beg end)))))
2050 (let ((size (count-lines beg end)))
2051 (save-excursion
2052 (cond ((= size 0)) ; do nothing for an empty result
2053 ((< size org-babel-min-lines-for-block-output)
2054 (goto-char beg)
2055 (dotimes (n size)
2056 (beginning-of-line 1) (insert ": ") (forward-line 1)))
2058 (goto-char beg)
2059 (insert (if results-switches
2060 (format "#+begin_example%s\n" results-switches)
2061 "#+begin_example\n"))
2062 (if (markerp end) (goto-char end) (forward-char (- end beg)))
2063 (insert "#+end_example\n"))))))))
2065 (defun org-babel-update-block-body (new-body)
2066 "Update the body of the current code block to NEW-BODY."
2067 (if (not (org-babel-where-is-src-block-head))
2068 (error "not in source block")
2069 (save-match-data
2070 (replace-match (concat (org-babel-trim new-body) "\n") nil t nil 5))
2071 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
2073 (defun org-babel-merge-params (&rest plists)
2074 "Combine all parameter association lists in PLISTS.
2075 Later elements of PLISTS override the values of previous elements.
2076 This takes into account some special considerations for certain
2077 parameters when merging lists."
2078 (let ((results-exclusive-groups
2079 (mapcar (lambda (group) (mapcar #'symbol-name group))
2080 (cdr (assoc 'results org-babel-common-header-args-w-values))))
2081 (exports-exclusive-groups
2082 (mapcar (lambda (group) (mapcar #'symbol-name group))
2083 (cdr (assoc 'exports org-babel-common-header-args-w-values))))
2084 (variable-index 0)
2085 params results exports tangle noweb cache vars shebang comments padline)
2086 (flet ((e-merge (exclusive-groups &rest result-params)
2087 ;; maintain exclusivity of mutually exclusive parameters
2088 (let (output)
2089 (mapc (lambda (new-params)
2090 (mapc (lambda (new-param)
2091 (mapc (lambda (exclusive-group)
2092 (when (member new-param exclusive-group)
2093 (mapcar (lambda (excluded-param)
2094 (setq output
2095 (delete
2096 excluded-param
2097 output)))
2098 exclusive-group)))
2099 exclusive-groups)
2100 (setq output (org-uniquify
2101 (cons new-param output))))
2102 new-params))
2103 result-params)
2104 output)))
2105 (mapc
2106 (lambda (plist)
2107 (mapc
2108 (lambda (pair)
2109 (case (car pair)
2110 (:var
2111 (let ((name (if (listp (cdr pair))
2112 (cadr pair)
2113 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
2114 (cdr pair))
2115 (intern (match-string 1 (cdr pair)))))))
2116 (if name
2117 (setq vars
2118 (append
2119 (if (member name (mapcar #'car vars))
2120 (delq nil
2121 (mapcar
2122 (lambda (p)
2123 (unless (equal (car p) name) p))
2124 vars))
2125 vars)
2126 (list (cons name pair))))
2127 ;; if no name is given and we already have named variables
2128 ;; then assign to named variables in order
2129 (if (and vars (nth variable-index vars))
2130 (prog1 (setf (cddr (nth variable-index vars))
2131 (concat (symbol-name
2132 (car (nth variable-index vars)))
2133 "=" (cdr pair)))
2134 (incf variable-index))
2135 (error "variable \"%s\" must be assigned a default value"
2136 (cdr pair))))))
2137 (:results
2138 (setq results (e-merge results-exclusive-groups
2139 results
2140 (split-string
2141 (let ((r (cdr pair)))
2142 (if (stringp r) r (eval r)))))))
2143 (:file
2144 (when (cdr pair)
2145 (setq results (e-merge results-exclusive-groups
2146 results '("file")))
2147 (unless (or (member "both" exports)
2148 (member "none" exports)
2149 (member "code" exports))
2150 (setq exports (e-merge exports-exclusive-groups
2151 exports '("results"))))
2152 (setq params (cons pair (assq-delete-all (car pair) params)))))
2153 (:exports
2154 (setq exports (e-merge exports-exclusive-groups
2155 exports (split-string (cdr pair)))))
2156 (:tangle ;; take the latest -- always overwrite
2157 (setq tangle (or (list (cdr pair)) tangle)))
2158 (:noweb
2159 (setq noweb (e-merge
2160 '(("yes" "no" "tangle" "no-export"
2161 "strip-export" "eval"))
2162 noweb
2163 (split-string (or (cdr pair) "")))))
2164 (:cache
2165 (setq cache (e-merge '(("yes" "no")) cache
2166 (split-string (or (cdr pair) "")))))
2167 (:padline
2168 (setq padline (e-merge '(("yes" "no")) padline
2169 (split-string (or (cdr pair) "")))))
2170 (:shebang ;; take the latest -- always overwrite
2171 (setq shebang (or (list (cdr pair)) shebang)))
2172 (:comments
2173 (setq comments (e-merge '(("yes" "no")) comments
2174 (split-string (or (cdr pair) "")))))
2175 (t ;; replace: this covers e.g. :session
2176 (setq params (cons pair (assq-delete-all (car pair) params))))))
2177 plist))
2178 plists))
2179 (setq vars (reverse vars))
2180 (while vars (setq params (cons (cons :var (cddr (pop vars))) params)))
2181 (mapc
2182 (lambda (hd)
2183 (let ((key (intern (concat ":" (symbol-name hd))))
2184 (val (eval hd)))
2185 (setf params (cons (cons key (mapconcat 'identity val " ")) params))))
2186 '(results exports tangle noweb padline cache shebang comments))
2187 params))
2189 (defvar *org-babel-use-quick-and-dirty-noweb-expansion* nil
2190 "Set to true to use regular expressions to expand noweb references.
2191 This results in much faster noweb reference expansion but does
2192 not properly allow code blocks to inherit the \":noweb-ref\"
2193 header argument from buffer or subtree wide properties.")
2195 (defun org-babel-noweb-p (params context)
2196 "Check if PARAMS require expansion in CONTEXT.
2197 CONTEXT may be one of :tangle, :export or :eval."
2198 (flet ((intersect (as bs)
2199 (when as
2200 (if (member (car as) bs)
2201 (car as)
2202 (intersect (cdr as) bs)))))
2203 (intersect (case context
2204 (:tangle '("yes" "tangle" "no-export" "strip-export"))
2205 (:eval '("yes" "no-export" "strip-export" "eval"))
2206 (:export '("yes")))
2207 (split-string (or (cdr (assoc :noweb params)) "")))))
2209 (defun org-babel-expand-noweb-references (&optional info parent-buffer)
2210 "Expand Noweb references in the body of the current source code block.
2212 For example the following reference would be replaced with the
2213 body of the source-code block named 'example-block'.
2215 <<example-block>>
2217 Note that any text preceding the <<foo>> construct on a line will
2218 be interposed between the lines of the replacement text. So for
2219 example if <<foo>> is placed behind a comment, then the entire
2220 replacement text will also be commented.
2222 This function must be called from inside of the buffer containing
2223 the source-code block which holds BODY.
2225 In addition the following syntax can be used to insert the
2226 results of evaluating the source-code block named 'example-block'.
2228 <<example-block()>>
2230 Any optional arguments can be passed to example-block by placing
2231 the arguments inside the parenthesis following the convention
2232 defined by `org-babel-lob'. For example
2234 <<example-block(a=9)>>
2236 would set the value of argument \"a\" equal to \"9\". Note that
2237 these arguments are not evaluated in the current source-code
2238 block but are passed literally to the \"example-block\"."
2239 (let* ((parent-buffer (or parent-buffer (current-buffer)))
2240 (info (or info (org-babel-get-src-block-info)))
2241 (lang (nth 0 info))
2242 (body (nth 1 info))
2243 (comment (string= "noweb" (cdr (assoc :comments (nth 2 info)))))
2244 (rx-prefix (concat "\\(" org-babel-src-name-regexp "\\|"
2245 ":noweb-ref[ \t]+" "\\)"))
2246 (new-body "") index source-name evaluate prefix blocks-in-buffer)
2247 (flet ((nb-add (text) (setq new-body (concat new-body text)))
2248 (c-wrap (text)
2249 (with-temp-buffer
2250 (funcall (intern (concat lang "-mode")))
2251 (comment-region (point) (progn (insert text) (point)))
2252 (org-babel-trim (buffer-string)))))
2253 (with-temp-buffer
2254 (insert body) (goto-char (point-min))
2255 (setq index (point))
2256 (while (and (re-search-forward (org-babel-noweb-wrap) nil t))
2257 (save-match-data (setf source-name (match-string 1)))
2258 (save-match-data (setq evaluate (string-match "\(.*\)" source-name)))
2259 (save-match-data
2260 (setq prefix
2261 (buffer-substring (match-beginning 0)
2262 (save-excursion
2263 (beginning-of-line 1) (point)))))
2264 ;; add interval to new-body (removing noweb reference)
2265 (goto-char (match-beginning 0))
2266 (nb-add (buffer-substring index (point)))
2267 (goto-char (match-end 0))
2268 (setq index (point))
2269 (nb-add
2270 (with-current-buffer parent-buffer
2271 (save-restriction
2272 (widen)
2273 (mapconcat ;; interpose PREFIX between every line
2274 #'identity
2275 (split-string
2276 (if evaluate
2277 (let ((raw (org-babel-ref-resolve source-name)))
2278 (if (stringp raw) raw (format "%S" raw)))
2280 ;; retrieve from the library of babel
2281 (nth 2 (assoc (intern source-name)
2282 org-babel-library-of-babel))
2283 ;; return the contents of headlines literally
2284 (save-excursion
2285 (when (org-babel-ref-goto-headline-id source-name)
2286 (org-babel-ref-headline-body)))
2287 ;; find the expansion of reference in this buffer
2288 (let ((rx (concat rx-prefix source-name "[ \t\n]"))
2289 expansion)
2290 (save-excursion
2291 (goto-char (point-min))
2292 (if *org-babel-use-quick-and-dirty-noweb-expansion*
2293 (while (re-search-forward rx nil t)
2294 (let* ((i (org-babel-get-src-block-info 'light))
2295 (body (org-babel-expand-noweb-references i))
2296 (sep (or (cdr (assoc :noweb-sep (nth 2 i)))
2297 "\n"))
2298 (full (if comment
2299 ((lambda (cs)
2300 (concat (c-wrap (car cs)) "\n"
2301 body "\n"
2302 (c-wrap (cadr cs))))
2303 (org-babel-tangle-comment-links i))
2304 body)))
2305 (setq expansion (cons sep (cons full expansion)))))
2306 (org-babel-map-src-blocks nil
2307 (let ((i (org-babel-get-src-block-info 'light)))
2308 (when (equal (or (cdr (assoc :noweb-ref (nth 2 i)))
2309 (nth 4 i))
2310 source-name)
2311 (let* ((body (org-babel-expand-noweb-references i))
2312 (sep (or (cdr (assoc :noweb-sep (nth 2 i)))
2313 "\n"))
2314 (full (if comment
2315 ((lambda (cs)
2316 (concat (c-wrap (car cs)) "\n"
2317 body "\n"
2318 (c-wrap (cadr cs))))
2319 (org-babel-tangle-comment-links i))
2320 body)))
2321 (setq expansion
2322 (cons sep (cons full expansion)))))))))
2323 (and expansion
2324 (mapconcat #'identity (nreverse (cdr expansion)) "")))
2325 ;; possibly raise an error if named block doesn't exist
2326 (if (member lang org-babel-noweb-error-langs)
2327 (error "%s" (concat
2328 (org-babel-noweb-wrap source-name)
2329 "could not be resolved (see "
2330 "`org-babel-noweb-error-langs')"))
2331 "")))
2332 "[\n\r]") (concat "\n" prefix))))))
2333 (nb-add (buffer-substring index (point-max)))))
2334 new-body))
2336 (defun org-babel-clean-text-properties (text)
2337 "Strip all properties from text return."
2338 (when text
2339 (set-text-properties 0 (length text) nil text) text))
2341 (defun org-babel-strip-protective-commas (body &optional lang)
2342 "Strip protective commas from bodies of source blocks."
2343 (with-temp-buffer
2344 (insert body)
2345 (if (and lang (string= lang "org"))
2346 (progn (goto-char (point-min))
2347 (while (re-search-forward "^[ \t]*\\(,\\)" nil t)
2348 (replace-match "" nil nil nil 1)))
2349 (org-strip-protective-commas (point-min) (point-max)))
2350 (buffer-string)))
2352 (defun org-babel-script-escape (str &optional force)
2353 "Safely convert tables into elisp lists."
2354 (let (in-single in-double out)
2355 ((lambda (escaped) (condition-case nil (org-babel-read escaped) (error escaped)))
2356 (if (or force
2357 (and (stringp str)
2358 (> (length str) 2)
2359 (or (and (string-equal "[" (substring str 0 1))
2360 (string-equal "]" (substring str -1)))
2361 (and (string-equal "{" (substring str 0 1))
2362 (string-equal "}" (substring str -1)))
2363 (and (string-equal "(" (substring str 0 1))
2364 (string-equal ")" (substring str -1))))))
2365 (org-babel-read
2366 (concat
2368 (progn
2369 (mapc
2370 (lambda (ch)
2371 (setq
2373 (case ch
2374 (91 (if (or in-double in-single) ; [
2375 (cons 91 out)
2376 (cons 40 out)))
2377 (93 (if (or in-double in-single) ; ]
2378 (cons 93 out)
2379 (cons 41 out)))
2380 (123 (if (or in-double in-single) ; {
2381 (cons 123 out)
2382 (cons 40 out)))
2383 (125 (if (or in-double in-single) ; }
2384 (cons 125 out)
2385 (cons 41 out)))
2386 (44 (if (or in-double in-single) ; ,
2387 (cons 44 out) (cons 32 out)))
2388 (39 (if in-double ; '
2389 (cons 39 out)
2390 (setq in-single (not in-single)) (cons 34 out)))
2391 (34 (if in-single ; "
2392 (append (list 34 32) out)
2393 (setq in-double (not in-double)) (cons 34 out)))
2394 (t (cons ch out)))))
2395 (string-to-list str))
2396 (apply #'string (reverse out)))))
2397 str))))
2399 (defun org-babel-read (cell &optional inhibit-lisp-eval)
2400 "Convert the string value of CELL to a number if appropriate.
2401 Otherwise if cell looks like lisp (meaning it starts with a
2402 \"(\", \"'\", \"`\" or a \"[\") then read it as lisp, otherwise
2403 return it unmodified as a string. Optional argument NO-LISP-EVAL
2404 inhibits lisp evaluation for situations in which is it not
2405 appropriate."
2406 (if (and (stringp cell) (not (equal cell "")))
2407 (or (org-babel-number-p cell)
2408 (if (and (not inhibit-lisp-eval)
2409 (member (substring cell 0 1) '("(" "'" "`" "[")))
2410 (eval (read cell))
2411 (if (string= (substring cell 0 1) "\"")
2412 (read cell)
2413 (progn (set-text-properties 0 (length cell) nil cell) cell))))
2414 cell))
2416 (defun org-babel-number-p (string)
2417 "If STRING represents a number return its value."
2418 (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string)
2419 (= (length (substring string (match-beginning 0)
2420 (match-end 0)))
2421 (length string)))
2422 (string-to-number string)))
2424 (defun org-babel-import-elisp-from-file (file-name &optional separator)
2425 "Read the results located at FILE-NAME into an elisp table.
2426 If the table is trivial, then return it as a scalar."
2427 (let (result)
2428 (save-window-excursion
2429 (with-temp-buffer
2430 (condition-case nil
2431 (progn
2432 (org-table-import file-name separator)
2433 (delete-file file-name)
2434 (setq result (mapcar (lambda (row)
2435 (mapcar #'org-babel-string-read row))
2436 (org-table-to-lisp))))
2437 (error nil)))
2438 (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
2439 (if (consp (car result))
2440 (if (null (cdr (car result)))
2441 (caar result)
2442 result)
2443 (car result))
2444 result))))
2446 (defun org-babel-string-read (cell)
2447 "Strip nested \"s from around strings."
2448 (org-babel-read (or (and (stringp cell)
2449 (string-match "\\\"\\(.+\\)\\\"" cell)
2450 (match-string 1 cell))
2451 cell)))
2453 (defun org-babel-reverse-string (string)
2454 "Return the reverse of STRING."
2455 (apply 'string (reverse (string-to-list string))))
2457 (defun org-babel-chomp (string &optional regexp)
2458 "Strip trailing spaces and carriage returns from STRING.
2459 Default regexp used is \"[ \f\t\n\r\v]\" but can be
2460 overwritten by specifying a regexp as a second argument."
2461 (let ((regexp (or regexp "[ \f\t\n\r\v]")))
2462 (while (and (> (length string) 0)
2463 (string-match regexp (substring string -1)))
2464 (setq string (substring string 0 -1)))
2465 string))
2467 (defun org-babel-trim (string &optional regexp)
2468 "Strip leading and trailing spaces and carriage returns from STRING.
2469 Like `org-babel-chomp' only it runs on both the front and back
2470 of the string."
2471 (org-babel-chomp (org-babel-reverse-string
2472 (org-babel-chomp (org-babel-reverse-string string) regexp))
2473 regexp))
2475 (defvar org-babel-org-babel-call-process-region-original nil)
2476 (defun org-babel-tramp-handle-call-process-region
2477 (start end program &optional delete buffer display &rest args)
2478 "Use tramp to handle call-process-region.
2479 Fixes a bug in `tramp-handle-call-process-region'."
2480 (if (and (featurep 'tramp) (file-remote-p default-directory))
2481 (let ((tmpfile (tramp-compat-make-temp-file "")))
2482 (write-region start end tmpfile)
2483 (when delete (delete-region start end))
2484 (unwind-protect
2485 ;; (apply 'call-process program tmpfile buffer display args)
2486 ;; bug in tramp
2487 (apply 'process-file program tmpfile buffer display args)
2488 (delete-file tmpfile)))
2489 ;; org-babel-call-process-region-original is the original emacs
2490 ;; definition. It is in scope from the let binding in
2491 ;; org-babel-execute-src-block
2492 (apply org-babel-call-process-region-original
2493 start end program delete buffer display args)))
2495 (defun org-babel-local-file-name (file)
2496 "Return the local name component of FILE."
2497 (if (file-remote-p file)
2498 (let (localname)
2499 (with-parsed-tramp-file-name file nil
2500 localname))
2501 file))
2503 (defun org-babel-process-file-name (name &optional no-quote-p)
2504 "Prepare NAME to be used in an external process.
2505 If NAME specifies a remote location, the remote portion of the
2506 name is removed, since in that case the process will be executing
2507 remotely. The file name is then processed by
2508 `expand-file-name'. Unless second argument NO-QUOTE-P is non-nil,
2509 the file name is additionally processed by
2510 `shell-quote-argument'"
2511 ((lambda (f) (if no-quote-p f (shell-quote-argument f)))
2512 (expand-file-name (org-babel-local-file-name name))))
2514 (defvar org-babel-temporary-directory)
2515 (unless (or noninteractive (boundp 'org-babel-temporary-directory))
2516 (defvar org-babel-temporary-directory
2517 (or (and (boundp 'org-babel-temporary-directory)
2518 (file-exists-p org-babel-temporary-directory)
2519 org-babel-temporary-directory)
2520 (make-temp-file "babel-" t))
2521 "Directory to hold temporary files created to execute code blocks.
2522 Used by `org-babel-temp-file'. This directory will be removed on
2523 Emacs shutdown."))
2525 (defun org-babel-temp-file (prefix &optional suffix)
2526 "Create a temporary file in the `org-babel-temporary-directory'.
2527 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2528 value of `temporary-file-directory' temporarily set to the value
2529 of `org-babel-temporary-directory'."
2530 (if (file-remote-p default-directory)
2531 (make-temp-file
2532 (concat (file-remote-p default-directory)
2533 (expand-file-name
2534 prefix temporary-file-directory)
2535 nil suffix))
2536 (let ((temporary-file-directory
2537 (or (and (boundp 'org-babel-temporary-directory)
2538 (file-exists-p org-babel-temporary-directory)
2539 org-babel-temporary-directory)
2540 temporary-file-directory)))
2541 (make-temp-file prefix nil suffix))))
2543 (defun org-babel-remove-temporary-directory ()
2544 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2545 (when (and (boundp 'org-babel-temporary-directory)
2546 (file-exists-p org-babel-temporary-directory))
2547 ;; taken from `delete-directory' in files.el
2548 (condition-case nil
2549 (progn
2550 (mapc (lambda (file)
2551 ;; This test is equivalent to
2552 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2553 ;; but more efficient
2554 (if (eq t (car (file-attributes file)))
2555 (delete-directory file)
2556 (delete-file file)))
2557 ;; We do not want to delete "." and "..".
2558 (directory-files org-babel-temporary-directory 'full
2559 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2560 (delete-directory org-babel-temporary-directory))
2561 (error
2562 (message "Failed to remove temporary Org-babel directory %s"
2563 (if (boundp 'org-babel-temporary-directory)
2564 org-babel-temporary-directory
2565 "[directory not defined]"))))))
2567 (add-hook 'kill-emacs-hook 'org-babel-remove-temporary-directory)
2569 (provide 'ob)
2573 ;;; ob.el ends here