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