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