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