Allow special editing of SETUPFILE keywords again
[org-mode.git] / lisp / ob-core.el
blob9e4c8b1ce797a1c27e399546ef04dbbc9a84f8d9
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:]]+\\)\\]\\)?\\:[ \t]*")
457 "Regular expression used to match result lines.
458 If the results are associated with a hash key then the hash will
459 be saved in the second match data.")
461 (defvar org-babel-result-w-name-regexp
462 (concat org-babel-result-regexp
463 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
465 (defvar org-babel-min-lines-for-block-output 10
466 "The minimum number of lines for block output.
467 If number of lines of output is equal to or exceeds this
468 value, the output is placed in a #+begin_example...#+end_example
469 block. Otherwise the output is marked as literal by inserting
470 colons at the starts of the lines. This variable only takes
471 effect if the :results output option is in effect.")
473 (defvar org-babel-noweb-error-langs nil
474 "Languages for which Babel will raise literate programming errors.
475 List of languages for which errors should be raised when the
476 source code block satisfying a noweb reference in this language
477 can not be resolved.")
479 (defvar org-babel-hash-show 4
480 "Number of initial characters to show of a hidden results hash.")
482 (defvar org-babel-after-execute-hook nil
483 "Hook for functions to be called after `org-babel-execute-src-block'")
485 (defun org-babel-named-src-block-regexp-for-name (name)
486 "This generates a regexp used to match a src block named NAME."
487 (concat org-babel-src-name-regexp (regexp-quote name)
488 "[ \t(]*[\r\n]\\(?:^#.*[\r\n]\\)*"
489 (substring org-babel-src-block-regexp 1)))
491 (defun org-babel-named-data-regexp-for-name (name)
492 "This generates a regexp used to match data named NAME."
493 (concat org-babel-result-regexp (regexp-quote name) "\\([ \t]\\|$\\)"))
495 ;;; functions
496 (defvar call-process-region)
498 ;;;###autoload
499 (defun org-babel-execute-src-block (&optional arg info params)
500 "Execute the current source code block.
501 Insert the results of execution into the buffer. Source code
502 execution and the collection and formatting of results can be
503 controlled through a variety of header arguments.
505 With prefix argument ARG, force re-execution even if an existing
506 result cached in the buffer would otherwise have been returned.
508 Optionally supply a value for INFO in the form returned by
509 `org-babel-get-src-block-info'.
511 Optionally supply a value for PARAMS which will be merged with
512 the header arguments specified at the front of the source code
513 block."
514 (interactive)
515 (let ((info (or info (org-babel-get-src-block-info))))
516 (when (org-babel-confirm-evaluate
517 (let ((i info))
518 (setf (nth 2 i) (org-babel-merge-params (nth 2 info) params))
520 (let* ((lang (nth 0 info))
521 (params (if params
522 (org-babel-process-params
523 (org-babel-merge-params (nth 2 info) params))
524 (nth 2 info)))
525 (cache? (and (not arg) (cdr (assoc :cache params))
526 (string= "yes" (cdr (assoc :cache params)))))
527 (result-params (cdr (assoc :result-params params)))
528 (new-hash (when cache? (org-babel-sha1-hash info)))
529 (old-hash (when cache? (org-babel-current-result-hash)))
530 (body (setf (nth 1 info)
531 (if (org-babel-noweb-p params :eval)
532 (org-babel-expand-noweb-references info)
533 (nth 1 info))))
534 (dir (cdr (assoc :dir params)))
535 (default-directory
536 (or (and dir (file-name-as-directory (expand-file-name dir)))
537 default-directory))
538 (org-babel-call-process-region-original
539 (if (boundp 'org-babel-call-process-region-original)
540 org-babel-call-process-region-original
541 (symbol-function 'call-process-region)))
542 (indent (car (last info)))
543 result cmd)
544 (unwind-protect
545 (let ((call-process-region
546 (lambda (&rest args)
547 (apply 'org-babel-tramp-handle-call-process-region args))))
548 (let ((lang-check (lambda (f)
549 (let ((f (intern (concat "org-babel-execute:" f))))
550 (when (fboundp f) f)))))
551 (setq cmd
552 (or (funcall lang-check lang)
553 (funcall lang-check (symbol-name
554 (cdr (assoc lang org-src-lang-modes))))
555 (error "No org-babel-execute function for %s!" lang))))
556 (if (and (not arg) new-hash (equal new-hash old-hash))
557 (save-excursion ;; return cached result
558 (goto-char (org-babel-where-is-src-block-result nil info))
559 (end-of-line 1) (forward-char 1)
560 (setq result (org-babel-read-result))
561 (message (replace-regexp-in-string
562 "%" "%%" (format "%S" result))) result)
563 (message "executing %s code block%s..."
564 (capitalize lang)
565 (if (nth 4 info) (format " (%s)" (nth 4 info)) ""))
566 (if (member "none" result-params)
567 (progn
568 (funcall cmd body params)
569 (message "result silenced"))
570 (setq result
571 ((lambda (result)
572 (if (and (eq (cdr (assoc :result-type params)) 'value)
573 (or (member "vector" result-params)
574 (member "table" result-params))
575 (not (listp result)))
576 (list (list result)) result))
577 (funcall cmd body params)))
578 ;; if non-empty result and :file then write to :file
579 (when (cdr (assoc :file params))
580 (when result
581 (with-temp-file (cdr (assoc :file params))
582 (insert
583 (org-babel-format-result
584 result (cdr (assoc :sep (nth 2 info)))))))
585 (setq result (cdr (assoc :file params))))
586 (org-babel-insert-result
587 result result-params info new-hash indent lang)
588 (run-hooks 'org-babel-after-execute-hook)
589 result
591 (setq call-process-region 'org-babel-call-process-region-original))))))
593 (defun org-babel-expand-body:generic (body params &optional var-lines)
594 "Expand BODY with PARAMS.
595 Expand a block of code with org-babel according to its header
596 arguments. This generic implementation of body expansion is
597 called for languages which have not defined their own specific
598 org-babel-expand-body:lang function."
599 (mapconcat #'identity (append var-lines (list body)) "\n"))
601 ;;;###autoload
602 (defun org-babel-expand-src-block (&optional arg info params)
603 "Expand the current source code block.
604 Expand according to the source code block's header
605 arguments and pop open the results in a preview buffer."
606 (interactive)
607 (let* ((info (or info (org-babel-get-src-block-info)))
608 (lang (nth 0 info))
609 (params (setf (nth 2 info)
610 (sort (org-babel-merge-params (nth 2 info) params)
611 (lambda (el1 el2) (string< (symbol-name (car el1))
612 (symbol-name (car el2)))))))
613 (body (setf (nth 1 info)
614 (if (org-babel-noweb-p params :eval)
615 (org-babel-expand-noweb-references info) (nth 1 info))))
616 (expand-cmd (intern (concat "org-babel-expand-body:" lang)))
617 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
618 lang)))
619 (expanded
620 (if (fboundp expand-cmd) (funcall expand-cmd body params)
621 (org-babel-expand-body:generic
622 body params (and (fboundp assignments-cmd)
623 (funcall assignments-cmd params))))))
624 (org-edit-src-code
625 nil expanded (concat "*Org-Babel Preview " (buffer-name) "[ " lang " ]*"))))
627 (defun org-babel-edit-distance (s1 s2)
628 "Return the edit (levenshtein) distance between strings S1 S2."
629 (let* ((l1 (length s1))
630 (l2 (length s2))
631 (dist (vconcat (mapcar (lambda (_) (make-vector (1+ l2) nil))
632 (number-sequence 1 (1+ l1)))))
633 (in (lambda (i j) (aref (aref dist i) j))))
634 (setf (aref (aref dist 0) 0) 0)
635 (dolist (j (number-sequence 1 l2))
636 (setf (aref (aref dist 0) j) j))
637 (dolist (i (number-sequence 1 l1))
638 (setf (aref (aref dist i) 0) i)
639 (dolist (j (number-sequence 1 l2))
640 (setf (aref (aref dist i) j)
641 (min
642 (1+ (funcall in (1- i) j))
643 (1+ (funcall in i (1- j)))
644 (+ (if (equal (aref s1 (1- i)) (aref s2 (1- j))) 0 1)
645 (funcall in (1- i) (1- j)))))))
646 (funcall in l1 l2)))
648 (defun org-babel-combine-header-arg-lists (original &rest others)
649 "Combine a number of lists of header argument names and arguments."
650 (let ((results (copy-sequence original)))
651 (dolist (new-list others)
652 (dolist (arg-pair new-list)
653 (let ((header (car arg-pair))
654 (args (cdr arg-pair)))
655 (setq results
656 (cons arg-pair (org-remove-if
657 (lambda (pair) (equal header (car pair)))
658 results))))))
659 results))
661 ;;;###autoload
662 (defun org-babel-check-src-block ()
663 "Check for misspelled header arguments in the current code block."
664 (interactive)
665 ;; TODO: report malformed code block
666 ;; TODO: report incompatible combinations of header arguments
667 ;; TODO: report uninitialized variables
668 (let ((too-close 2) ;; <- control closeness to report potential match
669 (names (mapcar #'symbol-name org-babel-header-arg-names)))
670 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg)) 1))
671 (and (org-babel-where-is-src-block-head)
672 (org-babel-parse-header-arguments
673 (org-no-properties
674 (match-string 4))))))
675 (dolist (name names)
676 (when (and (not (string= header name))
677 (<= (org-babel-edit-distance header name) too-close)
678 (not (member header names)))
679 (error "Supplied header \"%S\" is suspiciously close to \"%S\""
680 header name))))
681 (message "No suspicious header arguments found.")))
683 ;;;###autoload
684 (defun org-babel-insert-header-arg ()
685 "Insert a header argument selecting from lists of common args and values."
686 (interactive)
687 (let* ((lang (car (org-babel-get-src-block-info 'light)))
688 (lang-headers (intern (concat "org-babel-header-args:" lang)))
689 (headers (org-babel-combine-header-arg-lists
690 org-babel-common-header-args-w-values
691 (if (boundp lang-headers) (eval lang-headers) nil)))
692 (arg (org-icompleting-read
693 "Header Arg: "
694 (mapcar
695 (lambda (header-spec) (symbol-name (car header-spec)))
696 headers))))
697 (insert ":" arg)
698 (let ((vals (cdr (assoc (intern arg) headers))))
699 (when vals
700 (insert
702 (cond
703 ((eq vals :any)
704 (read-from-minibuffer "value: "))
705 ((listp vals)
706 (mapconcat
707 (lambda (group)
708 (let ((arg (org-icompleting-read
709 "value: "
710 (cons "default" (mapcar #'symbol-name group)))))
711 (if (and arg (not (string= "default" arg)))
712 (concat arg " ")
713 "")))
714 vals ""))))))))
716 ;; Add support for completing-read insertion of header arguments after ":"
717 (defun org-babel-header-arg-expand ()
718 "Call `org-babel-enter-header-arg-w-completion' in appropriate contexts."
719 (when (and (equal (char-before) ?\:) (org-babel-where-is-src-block-head))
720 (org-babel-enter-header-arg-w-completion (match-string 2))))
722 (defun org-babel-enter-header-arg-w-completion (&optional lang)
723 "Insert header argument appropriate for LANG with completion."
724 (let* ((lang-headers-var (intern (concat "org-babel-header-args:" lang)))
725 (lang-headers (when (boundp lang-headers-var) (eval lang-headers-var)))
726 (headers-w-values (org-babel-combine-header-arg-lists
727 org-babel-common-header-args-w-values lang-headers))
728 (headers (mapcar #'symbol-name (mapcar #'car headers-w-values)))
729 (header (org-completing-read "Header Arg: " headers))
730 (args (cdr (assoc (intern header) headers-w-values)))
731 (arg (when (and args (listp args))
732 (org-completing-read
733 (format "%s: " header)
734 (mapcar #'symbol-name (apply #'append args))))))
735 (insert (concat header " " (or arg "")))
736 (cons header arg)))
738 (add-hook 'org-tab-first-hook 'org-babel-header-arg-expand)
740 ;;;###autoload
741 (defun org-babel-load-in-session (&optional arg info)
742 "Load the body of the current source-code block.
743 Evaluate the header arguments for the source block before
744 entering the session. After loading the body this pops open the
745 session."
746 (interactive)
747 (let* ((info (or info (org-babel-get-src-block-info)))
748 (lang (nth 0 info))
749 (params (nth 2 info))
750 (body (setf (nth 1 info)
751 (if (org-babel-noweb-p params :eval)
752 (org-babel-expand-noweb-references info)
753 (nth 1 info))))
754 (session (cdr (assoc :session params)))
755 (dir (cdr (assoc :dir params)))
756 (default-directory
757 (or (and dir (file-name-as-directory dir)) default-directory))
758 (cmd (intern (concat "org-babel-load-session:" lang))))
759 (unless (fboundp cmd)
760 (error "No org-babel-load-session function for %s!" lang))
761 (pop-to-buffer (funcall cmd session body params))
762 (end-of-line 1)))
764 ;;;###autoload
765 (defun org-babel-initiate-session (&optional arg info)
766 "Initiate session for current code block.
767 If called with a prefix argument then resolve any variable
768 references in the header arguments and assign these variables in
769 the session. Copy the body of the code block to the kill ring."
770 (interactive "P")
771 (let* ((info (or info (org-babel-get-src-block-info (not arg))))
772 (lang (nth 0 info))
773 (body (nth 1 info))
774 (params (nth 2 info))
775 (session (cdr (assoc :session params)))
776 (dir (cdr (assoc :dir params)))
777 (default-directory
778 (or (and dir (file-name-as-directory dir)) default-directory))
779 (init-cmd (intern (format "org-babel-%s-initiate-session" lang)))
780 (prep-cmd (intern (concat "org-babel-prep-session:" lang))))
781 (if (and (stringp session) (string= session "none"))
782 (error "This block is not using a session!"))
783 (unless (fboundp init-cmd)
784 (error "No org-babel-initiate-session function for %s!" lang))
785 (with-temp-buffer (insert (org-babel-trim body))
786 (copy-region-as-kill (point-min) (point-max)))
787 (when arg
788 (unless (fboundp prep-cmd)
789 (error "No org-babel-prep-session function for %s!" lang))
790 (funcall prep-cmd session params))
791 (funcall init-cmd session params)))
793 ;;;###autoload
794 (defun org-babel-switch-to-session (&optional arg info)
795 "Switch to the session of the current code block.
796 Uses `org-babel-initiate-session' to start the session. If called
797 with a prefix argument then this is passed on to
798 `org-babel-initiate-session'."
799 (interactive "P")
800 (pop-to-buffer (org-babel-initiate-session arg info))
801 (end-of-line 1))
803 (defalias 'org-babel-pop-to-session 'org-babel-switch-to-session)
805 ;;;###autoload
806 (defun org-babel-switch-to-session-with-code (&optional arg info)
807 "Switch to code buffer and display session."
808 (interactive "P")
809 (let ((swap-windows
810 (lambda ()
811 (let ((other-window-buffer (window-buffer (next-window))))
812 (set-window-buffer (next-window) (current-buffer))
813 (set-window-buffer (selected-window) other-window-buffer))
814 (other-window 1)))
815 (info (org-babel-get-src-block-info))
816 (org-src-window-setup 'reorganize-frame))
817 (save-excursion
818 (org-babel-switch-to-session arg info))
819 (org-edit-src-code)
820 (funcall swap-windows)))
822 (defmacro org-babel-do-in-edit-buffer (&rest body)
823 "Evaluate BODY in edit buffer if there is a code block at point.
824 Return t if a code block was found at point, nil otherwise."
825 `(let ((org-src-window-setup 'switch-invisibly))
826 (when (and (org-babel-where-is-src-block-head)
827 (org-edit-src-code nil nil nil))
828 (unwind-protect (progn ,@body)
829 (if (org-bound-and-true-p org-edit-src-from-org-mode)
830 (org-edit-src-exit)))
831 t)))
832 (def-edebug-spec org-babel-do-in-edit-buffer (body))
834 (defun org-babel-do-key-sequence-in-edit-buffer (key)
835 "Read key sequence and execute the command in edit buffer.
836 Enter a key sequence to be executed in the language major-mode
837 edit buffer. For example, TAB will alter the contents of the
838 Org-mode code block according to the effect of TAB in the
839 language major-mode buffer. For languages that support
840 interactive sessions, this can be used to send code from the Org
841 buffer to the session for evaluation using the native major-mode
842 evaluation mechanisms."
843 (interactive "kEnter key-sequence to execute in edit buffer: ")
844 (org-babel-do-in-edit-buffer
845 (call-interactively
846 (key-binding (or key (read-key-sequence nil))))))
848 (defvar org-bracket-link-regexp)
850 ;;;###autoload
851 (defun org-babel-open-src-block-result (&optional re-run)
852 "If `point' is on a src block then open the results of the
853 source code block, otherwise return nil. With optional prefix
854 argument RE-RUN the source-code block is evaluated even if
855 results already exist."
856 (interactive "P")
857 (let ((info (org-babel-get-src-block-info)))
858 (when info
859 (save-excursion
860 ;; go to the results, if there aren't any then run the block
861 (goto-char (or (and (not re-run) (org-babel-where-is-src-block-result))
862 (progn (org-babel-execute-src-block)
863 (org-babel-where-is-src-block-result))))
864 (end-of-line 1)
865 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
866 ;; open the results
867 (if (looking-at org-bracket-link-regexp)
868 ;; file results
869 (org-open-at-point)
870 (let ((r (org-babel-format-result
871 (org-babel-read-result) (cdr (assoc :sep (nth 2 info))))))
872 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
873 (delete-region (point-min) (point-max))
874 (insert r)))
875 t))))
877 ;;;###autoload
878 (defmacro org-babel-map-src-blocks (file &rest body)
879 "Evaluate BODY forms on each source-block in FILE.
880 If FILE is nil evaluate BODY forms on source blocks in current
881 buffer. During evaluation of BODY the following local variables
882 are set relative to the currently matched code block.
884 full-block ------- string holding the entirety of the code block
885 beg-block -------- point at the beginning of the code block
886 end-block -------- point at the end of the matched code block
887 lang ------------- string holding the language of the code block
888 beg-lang --------- point at the beginning of the lang
889 end-lang --------- point at the end of the lang
890 switches --------- string holding the switches
891 beg-switches ----- point at the beginning of the switches
892 end-switches ----- point at the end of the switches
893 header-args ------ string holding the header-args
894 beg-header-args -- point at the beginning of the header-args
895 end-header-args -- point at the end of the header-args
896 body ------------- string holding the body of the code block
897 beg-body --------- point at the beginning of the body
898 end-body --------- point at the end of the body"
899 (declare (indent 1))
900 (let ((tempvar (make-symbol "file")))
901 `(let* ((,tempvar ,file)
902 (visited-p (or (null ,tempvar)
903 (get-file-buffer (expand-file-name ,tempvar))))
904 (point (point)) to-be-removed)
905 (save-window-excursion
906 (when ,tempvar (find-file ,tempvar))
907 (setq to-be-removed (current-buffer))
908 (goto-char (point-min))
909 (while (re-search-forward org-babel-src-block-regexp nil t)
910 (goto-char (match-beginning 0))
911 (let ((full-block (match-string 0))
912 (beg-block (match-beginning 0))
913 (end-block (match-end 0))
914 (lang (match-string 2))
915 (beg-lang (match-beginning 2))
916 (end-lang (match-end 2))
917 (switches (match-string 3))
918 (beg-switches (match-beginning 3))
919 (end-switches (match-end 3))
920 (header-args (match-string 4))
921 (beg-header-args (match-beginning 4))
922 (end-header-args (match-end 4))
923 (body (match-string 5))
924 (beg-body (match-beginning 5))
925 (end-body (match-end 5)))
926 ,@body
927 (goto-char end-block))))
928 (unless visited-p (kill-buffer to-be-removed))
929 (goto-char point))))
930 (def-edebug-spec org-babel-map-src-blocks (form body))
932 ;;;###autoload
933 (defmacro org-babel-map-inline-src-blocks (file &rest body)
934 "Evaluate BODY forms on each inline source-block in FILE.
935 If FILE is nil evaluate BODY forms on source blocks in current
936 buffer."
937 (declare (indent 1))
938 (let ((tempvar (make-symbol "file")))
939 `(let* ((,tempvar ,file)
940 (visited-p (or (null ,tempvar)
941 (get-file-buffer (expand-file-name ,tempvar))))
942 (point (point)) to-be-removed)
943 (save-window-excursion
944 (when ,tempvar (find-file ,tempvar))
945 (setq to-be-removed (current-buffer))
946 (goto-char (point-min))
947 (while (re-search-forward org-babel-inline-src-block-regexp nil t)
948 (goto-char (match-beginning 1))
949 (save-match-data ,@body)
950 (goto-char (match-end 0))))
951 (unless visited-p (kill-buffer to-be-removed))
952 (goto-char point))))
953 (def-edebug-spec org-babel-map-inline-src-blocks (form body))
955 (defvar org-babel-lob-one-liner-regexp)
957 ;;;###autoload
958 (defmacro org-babel-map-call-lines (file &rest body)
959 "Evaluate BODY forms on each call line in FILE.
960 If FILE is nil evaluate BODY forms on source blocks in current
961 buffer."
962 (declare (indent 1))
963 (let ((tempvar (make-symbol "file")))
964 `(let* ((,tempvar ,file)
965 (visited-p (or (null ,tempvar)
966 (get-file-buffer (expand-file-name ,tempvar))))
967 (point (point)) to-be-removed)
968 (save-window-excursion
969 (when ,tempvar (find-file ,tempvar))
970 (setq to-be-removed (current-buffer))
971 (goto-char (point-min))
972 (while (re-search-forward org-babel-lob-one-liner-regexp nil t)
973 (goto-char (match-beginning 1))
974 (save-match-data ,@body)
975 (goto-char (match-end 0))))
976 (unless visited-p (kill-buffer to-be-removed))
977 (goto-char point))))
978 (def-edebug-spec org-babel-map-call-lines (form body))
980 ;;;###autoload
981 (defmacro org-babel-map-executables (file &rest body)
982 (declare (indent 1))
983 (let ((tempvar (make-symbol "file"))
984 (rx (make-symbol "rx")))
985 `(let* ((,tempvar ,file)
986 (,rx (concat "\\(" org-babel-src-block-regexp
987 "\\|" org-babel-inline-src-block-regexp
988 "\\|" org-babel-lob-one-liner-regexp "\\)"))
989 (visited-p (or (null ,tempvar)
990 (get-file-buffer (expand-file-name ,tempvar))))
991 (point (point)) to-be-removed)
992 (save-window-excursion
993 (when ,tempvar (find-file ,tempvar))
994 (setq to-be-removed (current-buffer))
995 (goto-char (point-min))
996 (while (re-search-forward ,rx nil t)
997 (goto-char (match-beginning 1))
998 (when (looking-at org-babel-inline-src-block-regexp)(forward-char 1))
999 (save-match-data ,@body)
1000 (goto-char (match-end 0))))
1001 (unless visited-p (kill-buffer to-be-removed))
1002 (goto-char point))))
1003 (def-edebug-spec org-babel-map-executables (form body))
1005 ;;;###autoload
1006 (defun org-babel-execute-buffer (&optional arg)
1007 "Execute source code blocks in a buffer.
1008 Call `org-babel-execute-src-block' on every source block in
1009 the current buffer."
1010 (interactive "P")
1011 (org-babel-eval-wipe-error-buffer)
1012 (org-save-outline-visibility t
1013 (org-babel-map-executables nil
1014 (if (looking-at org-babel-lob-one-liner-regexp)
1015 (org-babel-lob-execute-maybe)
1016 (org-babel-execute-src-block arg)))))
1018 ;;;###autoload
1019 (defun org-babel-execute-subtree (&optional arg)
1020 "Execute source code blocks in a subtree.
1021 Call `org-babel-execute-src-block' on every source block in
1022 the current subtree."
1023 (interactive "P")
1024 (save-restriction
1025 (save-excursion
1026 (org-narrow-to-subtree)
1027 (org-babel-execute-buffer arg)
1028 (widen))))
1030 ;;;###autoload
1031 (defun org-babel-sha1-hash (&optional info)
1032 "Generate an sha1 hash based on the value of info."
1033 (interactive)
1034 (let ((print-level nil)
1035 (info (or info (org-babel-get-src-block-info))))
1036 (setf (nth 2 info)
1037 (sort (copy-sequence (nth 2 info))
1038 (lambda (a b) (string< (car a) (car b)))))
1039 (let* ((rm (lambda (lst)
1040 (dolist (p '("replace" "silent" "none"
1041 "append" "prepend"))
1042 (setq lst (remove p lst)))
1043 lst))
1044 (norm (lambda (arg)
1045 (let ((v (if (and (listp (cdr arg)) (null (cddr arg)))
1046 (copy-sequence (cdr arg))
1047 (cdr arg))))
1048 (when (and v (not (and (sequencep v)
1049 (not (consp v))
1050 (= (length v) 0))))
1051 (cond
1052 ((and (listp v) ; lists are sorted
1053 (member (car arg) '(:result-params)))
1054 (sort (funcall rm v) #'string<))
1055 ((and (stringp v) ; strings are sorted
1056 (member (car arg) '(:results :exports)))
1057 (mapconcat #'identity (sort (funcall rm (split-string v))
1058 #'string<) " "))
1059 (t v)))))))
1060 ((lambda (hash)
1061 (when (org-called-interactively-p 'interactive) (message hash)) hash)
1062 (let ((it (format "%s-%s"
1063 (mapconcat
1064 #'identity
1065 (delq nil (mapcar (lambda (arg)
1066 (let ((normalized (funcall norm arg)))
1067 (when normalized
1068 (format "%S" normalized))))
1069 (nth 2 info))) ":")
1070 (nth 1 info))))
1071 (sha1 it))))))
1073 (defun org-babel-current-result-hash ()
1074 "Return the current in-buffer hash."
1075 (org-babel-where-is-src-block-result)
1076 (org-no-properties (match-string 3)))
1078 (defun org-babel-set-current-result-hash (hash)
1079 "Set the current in-buffer hash to HASH."
1080 (org-babel-where-is-src-block-result)
1081 (save-excursion (goto-char (match-beginning 3))
1082 ;; (mapc #'delete-overlay (overlays-at (point)))
1083 (replace-match hash nil nil nil 3)
1084 (org-babel-hide-hash)))
1086 (defun org-babel-hide-hash ()
1087 "Hide the hash in the current results line.
1088 Only the initial `org-babel-hash-show' characters of the hash
1089 will remain visible."
1090 (add-to-invisibility-spec '(org-babel-hide-hash . t))
1091 (save-excursion
1092 (when (and (re-search-forward org-babel-result-regexp nil t)
1093 (match-string 3))
1094 (let* ((start (match-beginning 3))
1095 (hide-start (+ org-babel-hash-show start))
1096 (end (match-end 3))
1097 (hash (match-string 3))
1098 ov1 ov2)
1099 (setq ov1 (make-overlay start hide-start))
1100 (setq ov2 (make-overlay hide-start end))
1101 (overlay-put ov2 'invisible 'org-babel-hide-hash)
1102 (overlay-put ov1 'babel-hash hash)))))
1104 (defun org-babel-hide-all-hashes ()
1105 "Hide the hash in the current buffer.
1106 Only the initial `org-babel-hash-show' characters of each hash
1107 will remain visible. This function should be called as part of
1108 the `org-mode-hook'."
1109 (save-excursion
1110 (while (re-search-forward org-babel-result-regexp nil t)
1111 (goto-char (match-beginning 0))
1112 (org-babel-hide-hash)
1113 (goto-char (match-end 0)))))
1114 (add-hook 'org-mode-hook 'org-babel-hide-all-hashes)
1116 (defun org-babel-hash-at-point (&optional point)
1117 "Return the value of the hash at POINT.
1118 The hash is also added as the last element of the kill ring.
1119 This can be called with C-c C-c."
1120 (interactive)
1121 (let ((hash (car (delq nil (mapcar
1122 (lambda (ol) (overlay-get ol 'babel-hash))
1123 (overlays-at (or point (point))))))))
1124 (when hash (kill-new hash) (message hash))))
1125 (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-hash-at-point)
1127 (defun org-babel-result-hide-spec ()
1128 "Hide portions of results lines.
1129 Add `org-babel-hide-result' as an invisibility spec for hiding
1130 portions of results lines."
1131 (add-to-invisibility-spec '(org-babel-hide-result . t)))
1132 (add-hook 'org-mode-hook 'org-babel-result-hide-spec)
1134 (defvar org-babel-hide-result-overlays nil
1135 "Overlays hiding results.")
1137 (defun org-babel-result-hide-all ()
1138 "Fold all results in the current buffer."
1139 (interactive)
1140 (org-babel-show-result-all)
1141 (save-excursion
1142 (while (re-search-forward org-babel-result-regexp nil t)
1143 (save-excursion (goto-char (match-beginning 0))
1144 (org-babel-hide-result-toggle-maybe)))))
1146 (defun org-babel-show-result-all ()
1147 "Unfold all results in the current buffer."
1148 (mapc 'delete-overlay org-babel-hide-result-overlays)
1149 (setq org-babel-hide-result-overlays nil))
1151 ;;;###autoload
1152 (defun org-babel-hide-result-toggle-maybe ()
1153 "Toggle visibility of result at point."
1154 (interactive)
1155 (let ((case-fold-search t))
1156 (if (save-excursion
1157 (beginning-of-line 1)
1158 (looking-at org-babel-result-regexp))
1159 (progn (org-babel-hide-result-toggle)
1160 t) ;; to signal that we took action
1161 nil))) ;; to signal that we did not
1163 (defun org-babel-hide-result-toggle (&optional force)
1164 "Toggle the visibility of the current result."
1165 (interactive)
1166 (save-excursion
1167 (beginning-of-line)
1168 (if (re-search-forward org-babel-result-regexp nil t)
1169 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
1170 (end (progn
1171 (while (looking-at org-babel-multi-line-header-regexp)
1172 (forward-line 1))
1173 (goto-char (- (org-babel-result-end) 1)) (point)))
1175 (if (memq t (mapcar (lambda (overlay)
1176 (eq (overlay-get overlay 'invisible)
1177 'org-babel-hide-result))
1178 (overlays-at start)))
1179 (if (or (not force) (eq force 'off))
1180 (mapc (lambda (ov)
1181 (when (member ov org-babel-hide-result-overlays)
1182 (setq org-babel-hide-result-overlays
1183 (delq ov org-babel-hide-result-overlays)))
1184 (when (eq (overlay-get ov 'invisible)
1185 'org-babel-hide-result)
1186 (delete-overlay ov)))
1187 (overlays-at start)))
1188 (setq ov (make-overlay start end))
1189 (overlay-put ov 'invisible 'org-babel-hide-result)
1190 ;; make the block accessible to isearch
1191 (overlay-put
1192 ov 'isearch-open-invisible
1193 (lambda (ov)
1194 (when (member ov org-babel-hide-result-overlays)
1195 (setq org-babel-hide-result-overlays
1196 (delq ov org-babel-hide-result-overlays)))
1197 (when (eq (overlay-get ov 'invisible)
1198 'org-babel-hide-result)
1199 (delete-overlay ov))))
1200 (push ov org-babel-hide-result-overlays)))
1201 (error "Not looking at a result line"))))
1203 ;; org-tab-after-check-for-cycling-hook
1204 (add-hook 'org-tab-first-hook 'org-babel-hide-result-toggle-maybe)
1205 ;; Remove overlays when changing major mode
1206 (add-hook 'org-mode-hook
1207 (lambda () (org-add-hook 'change-major-mode-hook
1208 'org-babel-show-result-all 'append 'local)))
1210 (defvar org-file-properties)
1211 (defun org-babel-params-from-properties (&optional lang)
1212 "Retrieve parameters specified as properties.
1213 Return an association list of any source block params which
1214 may be specified in the properties of the current outline entry."
1215 (save-match-data
1216 (let (val sym)
1217 (org-babel-parse-multiple-vars
1218 (delq nil
1219 (mapcar
1220 (lambda (header-arg)
1221 (and (setq val (org-entry-get (point) header-arg t))
1222 (cons (intern (concat ":" header-arg))
1223 (org-babel-read val))))
1224 (mapcar
1225 #'symbol-name
1226 (mapcar
1227 #'car
1228 (org-babel-combine-header-arg-lists
1229 org-babel-common-header-args-w-values
1230 (progn
1231 (setq sym (intern (concat "org-babel-header-args:" lang)))
1232 (and (boundp sym) (eval sym))))))))))))
1234 (defvar org-src-preserve-indentation)
1235 (defun org-babel-parse-src-block-match ()
1236 "Parse the results from a match of the `org-babel-src-block-regexp'."
1237 (let* ((block-indentation (length (match-string 1)))
1238 (lang (org-no-properties (match-string 2)))
1239 (lang-headers (intern (concat "org-babel-default-header-args:" lang)))
1240 (switches (match-string 3))
1241 (body (org-no-properties
1242 (let* ((body (match-string 5))
1243 (sub-length (- (length body) 1)))
1244 (if (and (> sub-length 0)
1245 (string= "\n" (substring body sub-length)))
1246 (substring body 0 sub-length)
1247 (or body "")))))
1248 (preserve-indentation (or org-src-preserve-indentation
1249 (save-match-data
1250 (string-match "-i\\>" switches)))))
1251 (list lang
1252 ;; get block body less properties, protective commas, and indentation
1253 (with-temp-buffer
1254 (save-match-data
1255 (insert (org-unescape-code-in-string body))
1256 (unless preserve-indentation (org-do-remove-indentation))
1257 (buffer-string)))
1258 (org-babel-merge-params
1259 org-babel-default-header-args
1260 (org-babel-params-from-properties lang)
1261 (if (boundp lang-headers) (eval lang-headers) nil)
1262 (org-babel-parse-header-arguments
1263 (org-no-properties (or (match-string 4) ""))))
1264 switches
1265 block-indentation)))
1267 (defun org-babel-parse-inline-src-block-match ()
1268 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
1269 (let* ((lang (org-no-properties (match-string 2)))
1270 (lang-headers (intern (concat "org-babel-default-header-args:" lang))))
1271 (list lang
1272 (org-unescape-code-in-string (org-no-properties (match-string 5)))
1273 (org-babel-merge-params
1274 org-babel-default-inline-header-args
1275 (org-babel-params-from-properties lang)
1276 (if (boundp lang-headers) (eval lang-headers) nil)
1277 (org-babel-parse-header-arguments
1278 (org-no-properties (or (match-string 4) "")))))))
1280 (defun org-babel-balanced-split (string alts)
1281 "Split STRING on instances of ALTS.
1282 ALTS is a cons of two character options where each option may be
1283 either the numeric code of a single character or a list of
1284 character alternatives. For example to split on balanced
1285 instances of \"[ \t]:\" set ALTS to '((32 9) . 58)."
1286 (let* ((matches (lambda (ch spec) (if (listp spec) (member ch spec) (equal spec ch))))
1287 (matched (lambda (ch last)
1288 (if (consp alts)
1289 (and (funcall matches ch (cdr alts))
1290 (funcall matches last (car alts)))
1291 (funcall matches ch alts))))
1292 (balance 0) (last 0)
1293 quote partial lst)
1294 (mapc (lambda (ch) ; split on [], (), "" balanced instances of [ \t]:
1295 (setq balance (+ balance
1296 (cond ((or (equal 91 ch) (equal 40 ch)) 1)
1297 ((or (equal 93 ch) (equal 41 ch)) -1)
1298 (t 0))))
1299 (when (and (equal 34 ch) (not (equal 92 last)))
1300 (setq quote (not quote)))
1301 (setq partial (cons ch partial))
1302 (when (and (= balance 0) (not quote) (funcall matched ch last))
1303 (setq lst (cons (apply #'string (nreverse
1304 (if (consp alts)
1305 (cddr partial)
1306 (cdr partial))))
1307 lst))
1308 (setq partial nil))
1309 (setq last ch))
1310 (string-to-list string))
1311 (nreverse (cons (apply #'string (nreverse partial)) lst))))
1313 (defun org-babel-join-splits-near-ch (ch list)
1314 "Join splits where \"=\" is on either end of the split."
1315 (let ((last= (lambda (str) (= ch (aref str (1- (length str))))))
1316 (first= (lambda (str) (= ch (aref str 0)))))
1317 (reverse
1318 (org-reduce (lambda (acc el)
1319 (let ((head (car acc)))
1320 (if (and head (or (funcall last= head) (funcall first= el)))
1321 (cons (concat head el) (cdr acc))
1322 (cons el acc))))
1323 list :initial-value nil))))
1325 (defun org-babel-parse-header-arguments (arg-string)
1326 "Parse a string of header arguments returning an alist."
1327 (when (> (length arg-string) 0)
1328 (org-babel-parse-multiple-vars
1329 (delq nil
1330 (mapcar
1331 (lambda (arg)
1332 (if (string-match
1333 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1334 arg)
1335 (cons (intern (match-string 1 arg))
1336 (org-babel-read (org-babel-chomp (match-string 2 arg))))
1337 (cons (intern (org-babel-chomp arg)) nil)))
1338 ((lambda (raw)
1339 (cons (car raw) (mapcar (lambda (r) (concat ":" r)) (cdr raw))))
1340 (org-babel-balanced-split arg-string '((32 9) . 58))))))))
1342 (defun org-babel-parse-multiple-vars (header-arguments)
1343 "Expand multiple variable assignments behind a single :var keyword.
1345 This allows expression of multiple variables with one :var as
1346 shown below.
1348 #+PROPERTY: var foo=1, bar=2"
1349 (let (results)
1350 (mapc (lambda (pair)
1351 (if (eq (car pair) :var)
1352 (mapcar (lambda (v) (push (cons :var (org-babel-trim v)) results))
1353 (org-babel-join-splits-near-ch
1354 61 (org-babel-balanced-split (cdr pair) 32)))
1355 (push pair results)))
1356 header-arguments)
1357 (nreverse results)))
1359 (defun org-babel-process-params (params)
1360 "Expand variables in PARAMS and add summary parameters."
1361 (let* ((processed-vars (mapcar (lambda (el)
1362 (if (consp (cdr el))
1363 (cdr el)
1364 (org-babel-ref-parse (cdr el))))
1365 (org-babel-get-header params :var)))
1366 (vars-and-names (if (and (assoc :colname-names params)
1367 (assoc :rowname-names params))
1368 (list processed-vars)
1369 (org-babel-disassemble-tables
1370 processed-vars
1371 (cdr (assoc :hlines params))
1372 (cdr (assoc :colnames params))
1373 (cdr (assoc :rownames params)))))
1374 (raw-result (or (cdr (assoc :results params)) ""))
1375 (result-params (append
1376 (split-string (if (stringp raw-result)
1377 raw-result
1378 (eval raw-result)))
1379 (cdr (assoc :result-params params)))))
1380 (append
1381 (mapcar (lambda (var) (cons :var var)) (car vars-and-names))
1382 (list
1383 (cons :colname-names (or (cdr (assoc :colname-names params))
1384 (cadr vars-and-names)))
1385 (cons :rowname-names (or (cdr (assoc :rowname-names params))
1386 (caddr vars-and-names)))
1387 (cons :result-params result-params)
1388 (cons :result-type (cond ((member "output" result-params) 'output)
1389 ((member "value" result-params) 'value)
1390 (t 'value))))
1391 (org-babel-get-header params :var 'other))))
1393 ;; row and column names
1394 (defun org-babel-del-hlines (table)
1395 "Remove all 'hlines from TABLE."
1396 (remove 'hline table))
1398 (defun org-babel-get-colnames (table)
1399 "Return the column names of TABLE.
1400 Return a cons cell, the `car' of which contains the TABLE less
1401 colnames, and the `cdr' of which contains a list of the column
1402 names."
1403 (if (equal 'hline (nth 1 table))
1404 (cons (cddr table) (car table))
1405 (cons (cdr table) (car table))))
1407 (defun org-babel-get-rownames (table)
1408 "Return the row names of TABLE.
1409 Return a cons cell, the `car' of which contains the TABLE less
1410 colnames, and the `cdr' of which contains a list of the column
1411 names. Note: this function removes any hlines in TABLE."
1412 (let* ((trans (lambda (table) (apply #'mapcar* #'list table)))
1413 (width (apply 'max
1414 (mapcar (lambda (el) (if (listp el) (length el) 0)) table)))
1415 (table (funcall trans (mapcar (lambda (row)
1416 (if (not (equal row 'hline))
1418 (setq row '())
1419 (dotimes (n width)
1420 (setq row (cons 'hline row)))
1421 row))
1422 table))))
1423 (cons (mapcar (lambda (row) (if (equal (car row) 'hline) 'hline row))
1424 (funcall trans (cdr table)))
1425 (remove 'hline (car table)))))
1427 (defun org-babel-put-colnames (table colnames)
1428 "Add COLNAMES to TABLE if they exist."
1429 (if colnames (apply 'list colnames 'hline table) table))
1431 (defun org-babel-put-rownames (table rownames)
1432 "Add ROWNAMES to TABLE if they exist."
1433 (if rownames
1434 (mapcar (lambda (row)
1435 (if (listp row)
1436 (cons (or (pop rownames) "") row)
1437 row)) table)
1438 table))
1440 (defun org-babel-pick-name (names selector)
1441 "Select one out of an alist of row or column names.
1442 SELECTOR can be either a list of names in which case those names
1443 will be returned directly, or an index into the list NAMES in
1444 which case the indexed names will be return."
1445 (if (listp selector)
1446 selector
1447 (when names
1448 (if (and selector (symbolp selector) (not (equal t selector)))
1449 (cdr (assoc selector names))
1450 (if (integerp selector)
1451 (nth (- selector 1) names)
1452 (cdr (car (last names))))))))
1454 (defun org-babel-disassemble-tables (vars hlines colnames rownames)
1455 "Parse tables for further processing.
1456 Process the variables in VARS according to the HLINES,
1457 ROWNAMES and COLNAMES header arguments. Return a list consisting
1458 of the vars, cnames and rnames."
1459 (let (cnames rnames)
1460 (list
1461 (mapcar
1462 (lambda (var)
1463 (when (listp (cdr var))
1464 (when (and (not (equal colnames "no"))
1465 (or colnames (and (equal (nth 1 (cdr var)) 'hline)
1466 (not (member 'hline (cddr (cdr var)))))))
1467 (let ((both (org-babel-get-colnames (cdr var))))
1468 (setq cnames (cons (cons (car var) (cdr both))
1469 cnames))
1470 (setq var (cons (car var) (car both)))))
1471 (when (and rownames (not (equal rownames "no")))
1472 (let ((both (org-babel-get-rownames (cdr var))))
1473 (setq rnames (cons (cons (car var) (cdr both))
1474 rnames))
1475 (setq var (cons (car var) (car both)))))
1476 (when (and hlines (not (equal hlines "yes")))
1477 (setq var (cons (car var) (org-babel-del-hlines (cdr var))))))
1478 var)
1479 vars)
1480 (reverse cnames) (reverse rnames))))
1482 (defun org-babel-reassemble-table (table colnames rownames)
1483 "Add column and row names to a table.
1484 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1485 to the table for reinsertion to org-mode."
1486 (if (listp table)
1487 ((lambda (table)
1488 (if (and colnames (listp (car table)) (= (length (car table))
1489 (length colnames)))
1490 (org-babel-put-colnames table colnames) table))
1491 (if (and rownames (= (length table) (length rownames)))
1492 (org-babel-put-rownames table rownames) table))
1493 table))
1495 (defun org-babel-where-is-src-block-head ()
1496 "Find where the current source block begins.
1497 Return the point at the beginning of the current source
1498 block. Specifically at the beginning of the #+BEGIN_SRC line.
1499 If the point is not on a source block then return nil."
1500 (let ((initial (point)) (case-fold-search t) top bottom)
1502 (save-excursion ;; on a source name line or a #+header line
1503 (beginning-of-line 1)
1504 (and (or (looking-at org-babel-src-name-regexp)
1505 (looking-at org-babel-multi-line-header-regexp))
1506 (progn
1507 (while (and (forward-line 1)
1508 (or (looking-at org-babel-src-name-regexp)
1509 (looking-at org-babel-multi-line-header-regexp))))
1510 (looking-at org-babel-src-block-regexp))
1511 (point)))
1512 (save-excursion ;; on a #+begin_src line
1513 (beginning-of-line 1)
1514 (and (looking-at org-babel-src-block-regexp)
1515 (point)))
1516 (save-excursion ;; inside a src block
1517 (and
1518 (re-search-backward "^[ \t]*#\\+begin_src" nil t) (setq top (point))
1519 (re-search-forward "^[ \t]*#\\+end_src" nil t) (setq bottom (point))
1520 (< top initial) (< initial bottom)
1521 (progn (goto-char top) (beginning-of-line 1)
1522 (looking-at org-babel-src-block-regexp))
1523 (point))))))
1525 ;;;###autoload
1526 (defun org-babel-goto-src-block-head ()
1527 "Go to the beginning of the current code block."
1528 (interactive)
1529 ((lambda (head)
1530 (if head (goto-char head) (error "Not currently in a code block")))
1531 (org-babel-where-is-src-block-head)))
1533 ;;;###autoload
1534 (defun org-babel-goto-named-src-block (name)
1535 "Go to a named source-code block."
1536 (interactive
1537 (let ((completion-ignore-case t)
1538 (case-fold-search t)
1539 (under-point (thing-at-point 'line)))
1540 (list (org-icompleting-read
1541 "source-block name: " (org-babel-src-block-names) nil t
1542 (cond
1543 ;; noweb
1544 ((string-match (org-babel-noweb-wrap) under-point)
1545 (let ((block-name (match-string 1 under-point)))
1546 (string-match "[^(]*" block-name)
1547 (match-string 0 block-name)))
1548 ;; #+call:
1549 ((string-match org-babel-lob-one-liner-regexp under-point)
1550 (let ((source-info (car (org-babel-lob-get-info))))
1551 (if (string-match "^\\([^\\[]+?\\)\\(\\[.*\\]\\)?(" source-info)
1552 (let ((source-name (match-string 1 source-info)))
1553 source-name))))
1554 ;; #+results:
1555 ((string-match (concat "#\\+" org-babel-results-keyword
1556 "\\:\s+\\([^\\(]*\\)") under-point)
1557 (match-string 1 under-point))
1558 ;; symbol-at-point
1559 ((and (thing-at-point 'symbol))
1560 (org-babel-find-named-block (thing-at-point 'symbol))
1561 (thing-at-point 'symbol))
1562 (""))))))
1563 (let ((point (org-babel-find-named-block name)))
1564 (if point
1565 ;; taken from `org-open-at-point'
1566 (progn (org-mark-ring-push) (goto-char point) (org-show-context))
1567 (message "source-code block '%s' not found in this buffer" name))))
1569 (defun org-babel-find-named-block (name)
1570 "Find a named source-code block.
1571 Return the location of the source block identified by source
1572 NAME, or nil if no such block exists. Set match data according to
1573 org-babel-named-src-block-regexp."
1574 (save-excursion
1575 (let ((case-fold-search t)
1576 (regexp (org-babel-named-src-block-regexp-for-name name)) msg)
1577 (goto-char (point-min))
1578 (when (or (re-search-forward regexp nil t)
1579 (re-search-backward regexp nil t))
1580 (match-beginning 0)))))
1582 (defun org-babel-src-block-names (&optional file)
1583 "Returns the names of source blocks in FILE or the current buffer."
1584 (save-excursion
1585 (when file (find-file file)) (goto-char (point-min))
1586 (let ((case-fold-search t) names)
1587 (while (re-search-forward org-babel-src-name-w-name-regexp nil t)
1588 (setq names (cons (match-string 3) names)))
1589 names)))
1591 ;;;###autoload
1592 (defun org-babel-goto-named-result (name)
1593 "Go to a named result."
1594 (interactive
1595 (let ((completion-ignore-case t))
1596 (list (org-icompleting-read "source-block name: "
1597 (org-babel-result-names) nil t))))
1598 (let ((point (org-babel-find-named-result name)))
1599 (if point
1600 ;; taken from `org-open-at-point'
1601 (progn (goto-char point) (org-show-context))
1602 (message "result '%s' not found in this buffer" name))))
1604 (defun org-babel-find-named-result (name &optional point)
1605 "Find a named result.
1606 Return the location of the result named NAME in the current
1607 buffer or nil if no such result exists."
1608 (save-excursion
1609 (let ((case-fold-search t))
1610 (goto-char (or point (point-min)))
1611 (catch 'is-a-code-block
1612 (when (re-search-forward
1613 (concat org-babel-result-regexp
1614 "[ \t]" (regexp-quote name) "[ \t]*[\n\f\v\r]") nil t)
1615 (when (and (string= "name" (downcase (match-string 1)))
1616 (or (beginning-of-line 1)
1617 (looking-at org-babel-src-block-regexp)
1618 (looking-at org-babel-multi-line-header-regexp)))
1619 (throw 'is-a-code-block (org-babel-find-named-result name (point))))
1620 (beginning-of-line 0) (point))))))
1622 (defun org-babel-result-names (&optional file)
1623 "Returns the names of results in FILE or the current buffer."
1624 (save-excursion
1625 (when file (find-file file)) (goto-char (point-min))
1626 (let ((case-fold-search t) names)
1627 (while (re-search-forward org-babel-result-w-name-regexp nil t)
1628 (setq names (cons (match-string 4) names)))
1629 names)))
1631 ;;;###autoload
1632 (defun org-babel-next-src-block (&optional arg)
1633 "Jump to the next source block.
1634 With optional prefix argument ARG, jump forward ARG many source blocks."
1635 (interactive "P")
1636 (when (looking-at org-babel-src-block-regexp) (forward-char 1))
1637 (condition-case nil
1638 (re-search-forward org-babel-src-block-regexp nil nil (or arg 1))
1639 (error (error "No further code blocks")))
1640 (goto-char (match-beginning 0)) (org-show-context))
1642 ;;;###autoload
1643 (defun org-babel-previous-src-block (&optional arg)
1644 "Jump to the previous source block.
1645 With optional prefix argument ARG, jump backward ARG many source blocks."
1646 (interactive "P")
1647 (condition-case nil
1648 (re-search-backward org-babel-src-block-regexp nil nil (or arg 1))
1649 (error (error "No previous code blocks")))
1650 (goto-char (match-beginning 0)) (org-show-context))
1652 (defvar org-babel-load-languages)
1654 ;;;###autoload
1655 (defun org-babel-mark-block ()
1656 "Mark current src block."
1657 (interactive)
1658 ((lambda (head)
1659 (when head
1660 (save-excursion
1661 (goto-char head)
1662 (looking-at org-babel-src-block-regexp))
1663 (push-mark (match-end 5) nil t)
1664 (goto-char (match-beginning 5))))
1665 (org-babel-where-is-src-block-head)))
1667 (defun org-babel-demarcate-block (&optional arg)
1668 "Wrap or split the code in the region or on the point.
1669 When called from inside of a code block the current block is
1670 split. When called from outside of a code block a new code block
1671 is created. In both cases if the region is demarcated and if the
1672 region is not active then the point is demarcated."
1673 (interactive "P")
1674 (let ((info (org-babel-get-src-block-info 'light))
1675 (headers (progn (org-babel-where-is-src-block-head)
1676 (match-string 4)))
1677 (stars (concat (make-string (or (org-current-level) 1) ?*) " ")))
1678 (if info
1679 (mapc
1680 (lambda (place)
1681 (save-excursion
1682 (goto-char place)
1683 (let ((lang (nth 0 info))
1684 (indent (make-string (nth 5 info) ? )))
1685 (when (string-match "^[[:space:]]*$"
1686 (buffer-substring (point-at-bol)
1687 (point-at-eol)))
1688 (delete-region (point-at-bol) (point-at-eol)))
1689 (insert (concat
1690 (if (looking-at "^") "" "\n")
1691 indent "#+end_src\n"
1692 (if arg stars indent) "\n"
1693 indent "#+begin_src " lang
1694 (if (> (length headers) 1)
1695 (concat " " headers) headers)
1696 (if (looking-at "[\n\r]")
1698 (concat "\n" (make-string (current-column) ? )))))))
1699 (move-end-of-line 2))
1700 (sort (if (org-region-active-p) (list (mark) (point)) (list (point))) #'>))
1701 (let ((start (point))
1702 (lang (org-icompleting-read "Lang: "
1703 (mapcar (lambda (el) (symbol-name (car el)))
1704 org-babel-load-languages)))
1705 (body (delete-and-extract-region
1706 (if (org-region-active-p) (mark) (point)) (point))))
1707 (insert (concat (if (looking-at "^") "" "\n")
1708 (if arg (concat stars "\n") "")
1709 "#+begin_src " lang "\n"
1710 body
1711 (if (or (= (length body) 0)
1712 (string-match "[\r\n]$" body)) "" "\n")
1713 "#+end_src\n"))
1714 (goto-char start) (move-end-of-line 1)))))
1716 (defvar org-babel-lob-one-liner-regexp)
1717 (defun org-babel-where-is-src-block-result (&optional insert info hash indent)
1718 "Find where the current source block results begin.
1719 Return the point at the beginning of the result of the current
1720 source block. Specifically at the beginning of the results line.
1721 If no result exists for this block then create a results line
1722 following the source block."
1723 (save-excursion
1724 (let* ((case-fold-search t)
1725 (on-lob-line (save-excursion
1726 (beginning-of-line 1)
1727 (looking-at org-babel-lob-one-liner-regexp)))
1728 (inlinep (when (org-babel-get-inline-src-block-matches)
1729 (match-end 0)))
1730 (name (if on-lob-line
1731 (mapconcat #'identity (butlast (org-babel-lob-get-info)) "")
1732 (nth 4 (or info (org-babel-get-src-block-info 'light)))))
1733 (head (unless on-lob-line (org-babel-where-is-src-block-head)))
1734 found beg end)
1735 (when head (goto-char head))
1736 (org-with-wide-buffer
1737 (setq
1738 found ;; was there a result (before we potentially insert one)
1740 inlinep
1741 (and
1742 ;; named results:
1743 ;; - return t if it is found, else return nil
1744 ;; - if it does not need to be rebuilt, then don't set end
1745 ;; - if it does need to be rebuilt then do set end
1746 name (setq beg (org-babel-find-named-result name))
1747 (prog1 beg
1748 (when (and hash (not (string= hash (match-string 3))))
1749 (goto-char beg) (setq end beg) ;; beginning of result
1750 (forward-line 1)
1751 (delete-region end (org-babel-result-end)) nil)))
1752 (and
1753 ;; unnamed results:
1754 ;; - return t if it is found, else return nil
1755 ;; - if it is found, and the hash doesn't match, delete and set end
1756 (or on-lob-line (re-search-forward "^[ \t]*#\\+end_src" nil t))
1757 (progn (end-of-line 1)
1758 (if (eobp) (insert "\n") (forward-char 1))
1759 (setq end (point))
1760 (or (and (not name)
1761 (progn ;; unnamed results line already exists
1762 (re-search-forward "[^ \f\t\n\r\v]" nil t)
1763 (beginning-of-line 1)
1764 (looking-at
1765 (concat org-babel-result-regexp "\n")))
1766 (prog1 (point)
1767 ;; must remove and rebuild if hash!=old-hash
1768 (if (and hash (not (string= hash (match-string 3))))
1769 (prog1 nil
1770 (forward-line 1)
1771 (delete-region
1772 end (org-babel-result-end)))
1773 (setq end nil))))))))))
1774 (if (not (and insert end)) found
1775 (goto-char end)
1776 (unless beg
1777 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1778 (insert (concat
1779 (when (wholenump indent) (make-string indent ? ))
1780 "#+" org-babel-results-keyword
1781 (when hash (concat "["hash"]"))
1783 (when name (concat " " name)) "\n"))
1784 (unless beg (insert "\n") (backward-char))
1785 (beginning-of-line 0)
1786 (if hash (org-babel-hide-hash))
1787 (point)))))
1789 (defvar org-block-regexp)
1790 (defun org-babel-read-result ()
1791 "Read the result at `point' into emacs-lisp."
1792 (let ((case-fold-search t) result-string)
1793 (cond
1794 ((org-at-table-p) (org-babel-read-table))
1795 ((org-at-item-p) (org-babel-read-list))
1796 ((looking-at org-bracket-link-regexp) (org-babel-read-link))
1797 ((looking-at org-block-regexp) (org-babel-trim (match-string 4)))
1798 ((looking-at "^[ \t]*: ")
1799 (setq result-string
1800 (org-babel-trim
1801 (mapconcat (lambda (line)
1802 (if (and (> (length line) 1)
1803 (string-match "^[ \t]*: \\(.+\\)" line))
1804 (match-string 1 line)
1805 line))
1806 (split-string
1807 (buffer-substring
1808 (point) (org-babel-result-end)) "[\r\n]+")
1809 "\n")))
1810 (or (org-babel-number-p result-string) result-string))
1811 ((looking-at org-babel-result-regexp)
1812 (save-excursion (forward-line 1) (org-babel-read-result))))))
1814 (defun org-babel-read-table ()
1815 "Read the table at `point' into emacs-lisp."
1816 (mapcar (lambda (row)
1817 (if (and (symbolp row) (equal row 'hline)) row
1818 (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval)) row)))
1819 (org-table-to-lisp)))
1821 (defun org-babel-read-list ()
1822 "Read the list at `point' into emacs-lisp."
1823 (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval))
1824 (mapcar #'cadr (cdr (org-list-parse-list)))))
1826 (defvar org-link-types-re)
1827 (defun org-babel-read-link ()
1828 "Read the link at `point' into emacs-lisp.
1829 If the path of the link is a file path it is expanded using
1830 `expand-file-name'."
1831 (let* ((case-fold-search t)
1832 (raw (and (looking-at org-bracket-link-regexp)
1833 (org-no-properties (match-string 1))))
1834 (type (and (string-match org-link-types-re raw)
1835 (match-string 1 raw))))
1836 (cond
1837 ((not type) (expand-file-name raw))
1838 ((string= type "file")
1839 (and (string-match "file\\(.*\\):\\(.+\\)" raw)
1840 (expand-file-name (match-string 2 raw))))
1841 (t raw))))
1843 (defun org-babel-format-result (result &optional sep)
1844 "Format RESULT for writing to file."
1845 (let ((echo-res (lambda (r) (if (stringp r) r (format "%S" r)))))
1846 (if (listp result)
1847 ;; table result
1848 (orgtbl-to-generic
1849 result (list :sep (or sep "\t") :fmt echo-res))
1850 ;; scalar result
1851 (funcall echo-res result))))
1853 (defun org-babel-insert-result
1854 (result &optional result-params info hash indent lang)
1855 "Insert RESULT into the current buffer.
1856 By default RESULT is inserted after the end of the
1857 current source block. With optional argument RESULT-PARAMS
1858 controls insertion of results in the org-mode file.
1859 RESULT-PARAMS can take the following values:
1861 replace - (default option) insert results after the source block
1862 replacing any previously inserted results
1864 silent -- no results are inserted into the Org-mode buffer but
1865 the results are echoed to the minibuffer and are
1866 ingested by Emacs (a potentially time consuming
1867 process)
1869 file ---- the results are interpreted as a file path, and are
1870 inserted into the buffer using the Org-mode file syntax
1872 list ---- the results are interpreted as an Org-mode list.
1874 raw ----- results are added directly to the Org-mode file. This
1875 is a good option if you code block will output org-mode
1876 formatted text.
1878 drawer -- results are added directly to the Org-mode file as with
1879 \"raw\", but are wrapped in a RESULTS drawer, allowing
1880 them to later be replaced or removed automatically.
1882 org ----- results are added inside of a \"#+BEGIN_SRC org\" block.
1883 They are not comma-escaped when inserted, but Org syntax
1884 here will be discarded when exporting the file.
1886 html ---- results are added inside of a #+BEGIN_HTML block. This
1887 is a good option if you code block will output html
1888 formatted text.
1890 latex --- results are added inside of a #+BEGIN_LATEX block.
1891 This is a good option if you code block will output
1892 latex formatted text.
1894 code ---- the results are extracted in the syntax of the source
1895 code of the language being evaluated and are added
1896 inside of a #+BEGIN_SRC block with the source-code
1897 language set appropriately. Note this relies on the
1898 optional LANG argument."
1899 (if (stringp result)
1900 (progn
1901 (setq result (org-no-properties result))
1902 (when (member "file" result-params)
1903 (setq result (org-babel-result-to-file
1904 result (when (assoc :file-desc (nth 2 info))
1905 (or (cdr (assoc :file-desc (nth 2 info)))
1906 result))))))
1907 (unless (listp result) (setq result (format "%S" result))))
1908 (if (and result-params (member "silent" result-params))
1909 (progn
1910 (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
1911 result)
1912 (save-excursion
1913 (let* ((inlinep
1914 (save-excursion
1915 (when (or (org-babel-get-inline-src-block-matches)
1916 (org-babel-get-lob-one-liner-matches))
1917 (goto-char (match-end 0))
1918 (insert (if (listp result) "\n" " "))
1919 (point))))
1920 (existing-result (unless inlinep
1921 (org-babel-where-is-src-block-result
1922 t info hash indent)))
1923 (results-switches
1924 (cdr (assoc :results_switches (nth 2 info))))
1925 (visible-beg (copy-marker (point-min)))
1926 (visible-end (copy-marker (point-max)))
1927 ;; When results exist outside of the current visible
1928 ;; region of the buffer, be sure to widen buffer to
1929 ;; update them.
1930 (outside-scope-p (and existing-result
1931 (or (> visible-beg existing-result)
1932 (<= visible-end existing-result))))
1933 beg end)
1934 (when (and (stringp result) ; ensure results end in a newline
1935 (not inlinep)
1936 (> (length result) 0)
1937 (not (or (string-equal (substring result -1) "\n")
1938 (string-equal (substring result -1) "\r"))))
1939 (setq result (concat result "\n")))
1940 (unwind-protect
1941 (progn
1942 (when outside-scope-p (widen))
1943 (if (not existing-result)
1944 (setq beg (or inlinep (point)))
1945 (goto-char existing-result)
1946 (save-excursion
1947 (re-search-forward "#" nil t)
1948 (setq indent (- (current-column) 1)))
1949 (forward-line 1)
1950 (setq beg (point))
1951 (cond
1952 ((member "replace" result-params)
1953 (delete-region (point) (org-babel-result-end)))
1954 ((member "append" result-params)
1955 (goto-char (org-babel-result-end)) (setq beg (point-marker)))
1956 ((member "prepend" result-params)))) ; already there
1957 (setq results-switches
1958 (if results-switches (concat " " results-switches) ""))
1959 (let ((wrap (lambda (start finish &optional no-escape)
1960 (goto-char end) (insert (concat finish "\n"))
1961 (goto-char beg) (insert (concat start "\n"))
1962 (unless no-escape
1963 (org-escape-code-in-region (point) end))
1964 (goto-char end) (goto-char (point-at-eol))
1965 (setq end (point-marker))))
1966 (proper-list-p (lambda (it) (and (listp it) (null (cdr (last it)))))))
1967 ;; insert results based on type
1968 (cond
1969 ;; do nothing for an empty result
1970 ((null result))
1971 ;; insert a list if preferred
1972 ((member "list" result-params)
1973 (insert
1974 (org-babel-trim
1975 (org-list-to-generic
1976 (cons 'unordered
1977 (mapcar
1978 (lambda (el) (list nil (if (stringp el) el (format "%S" el))))
1979 (if (listp result) result (list result))))
1980 '(:splicep nil :istart "- " :iend "\n")))
1981 "\n"))
1982 ;; assume the result is a table if it's not a string
1983 ((funcall proper-list-p result)
1984 (goto-char beg)
1985 (insert (concat (orgtbl-to-orgtbl
1986 (if (or (eq 'hline (car result))
1987 (and (listp (car result))
1988 (listp (cdr (car result)))))
1989 result (list result))
1990 '(:fmt (lambda (cell) (format "%s" cell)))) "\n"))
1991 (goto-char beg) (when (org-at-table-p) (org-table-align)))
1992 ((and (listp result) (not (funcall proper-list-p result)))
1993 (insert (format "%s\n" result)))
1994 ((member "file" result-params)
1995 (when inlinep (goto-char inlinep))
1996 (insert result))
1997 (t (goto-char beg) (insert result)))
1998 (when (funcall proper-list-p result) (goto-char (org-table-end)))
1999 (setq end (point-marker))
2000 ;; possibly wrap result
2001 (cond
2002 ((assoc :wrap (nth 2 info))
2003 (let ((name (or (cdr (assoc :wrap (nth 2 info))) "RESULTS")))
2004 (funcall wrap (concat "#+BEGIN_" name)
2005 (concat "#+END_" (car (org-split-string name))))))
2006 ((member "html" result-params)
2007 (funcall wrap "#+BEGIN_HTML" "#+END_HTML"))
2008 ((member "latex" result-params)
2009 (funcall wrap "#+BEGIN_LaTeX" "#+END_LaTeX"))
2010 ((member "org" result-params)
2011 (funcall wrap "#+BEGIN_SRC org" "#+END_SRC"))
2012 ((member "code" result-params)
2013 (funcall wrap (format "#+BEGIN_SRC %s%s" (or lang "none") results-switches)
2014 "#+END_SRC"))
2015 ((member "raw" result-params)
2016 (goto-char beg) (if (org-at-table-p) (org-cycle)))
2017 ((or (member "drawer" result-params)
2018 ;; Stay backward compatible with <7.9.2
2019 (member "wrap" result-params))
2020 (funcall wrap ":RESULTS:" ":END:" 'no-escape))
2021 ((and (not (funcall proper-list-p result))
2022 (not (member "file" result-params)))
2023 (org-babel-examplize-region beg end results-switches)
2024 (setq end (point)))))
2025 ;; possibly indent the results to match the #+results line
2026 (when (and (not inlinep) (numberp indent) indent (> indent 0)
2027 ;; in this case `table-align' does the work for us
2028 (not (and (listp result)
2029 (member "append" result-params))))
2030 (indent-rigidly beg end indent))
2031 (if (null result)
2032 (if (member "value" result-params)
2033 (message "Code block returned no value.")
2034 (message "Code block produced no output."))
2035 (message "Code block evaluation complete.")))
2036 (when outside-scope-p (narrow-to-region visible-beg visible-end))
2037 (set-marker visible-beg nil)
2038 (set-marker visible-end nil))))))
2040 (defun org-babel-remove-result (&optional info)
2041 "Remove the result of the current source block."
2042 (interactive)
2043 (let ((location (org-babel-where-is-src-block-result nil info)) start)
2044 (when location
2045 (setq start (- location 1))
2046 (save-excursion
2047 (goto-char location) (forward-line 1)
2048 (delete-region start (org-babel-result-end))))))
2050 (defun org-babel-result-end ()
2051 "Return the point at the end of the current set of results."
2052 (save-excursion
2053 (cond
2054 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
2055 ((org-at-item-p) (let* ((struct (org-list-struct))
2056 (prvs (org-list-prevs-alist struct)))
2057 (org-list-get-list-end (point-at-bol) struct prvs)))
2058 ((let ((case-fold-search t)) (looking-at "^\\([ \t]*\\):results:"))
2059 (progn (re-search-forward (concat "^" (match-string 1) ":END:"))
2060 (forward-char 1) (point)))
2062 (let ((case-fold-search t))
2063 (if (looking-at (concat "[ \t]*#\\+begin_\\([^ \t\n\r]+\\)"))
2064 (progn (re-search-forward (concat "[ \t]*#\\+end_" (match-string 1))
2065 nil t)
2066 (forward-char 1))
2067 (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
2068 (forward-line 1))))
2069 (point)))))
2071 (defun org-babel-result-to-file (result &optional description)
2072 "Convert RESULT into an `org-mode' link with optional DESCRIPTION.
2073 If the `default-directory' is different from the containing
2074 file's directory then expand relative links."
2075 (when (stringp result)
2076 (format "[[file:%s]%s]"
2077 (if (and default-directory
2078 buffer-file-name
2079 (not (string= (expand-file-name default-directory)
2080 (expand-file-name
2081 (file-name-directory buffer-file-name)))))
2082 (expand-file-name result default-directory)
2083 result)
2084 (if description (concat "[" description "]") ""))))
2086 (defvar org-babel-capitalize-examplize-region-markers nil
2087 "Make true to capitalize begin/end example markers inserted by code blocks.")
2089 (defun org-babel-examplize-region (beg end &optional results-switches)
2090 "Comment out region using the inline '==' or ': ' org example quote."
2091 (interactive "*r")
2092 (let ((chars-between (lambda (b e)
2093 (not (string-match "^[\\s]*$" (buffer-substring b e)))))
2094 (maybe-cap (lambda (str) (if org-babel-capitalize-examplize-region-markers
2095 (upcase str) str))))
2096 (if (or (funcall chars-between (save-excursion (goto-char beg) (point-at-bol)) beg)
2097 (funcall chars-between end (save-excursion (goto-char end) (point-at-eol))))
2098 (save-excursion
2099 (goto-char beg)
2100 (insert (format "=%s=" (prog1 (buffer-substring beg end)
2101 (delete-region beg end)))))
2102 (let ((size (count-lines beg end)))
2103 (save-excursion
2104 (cond ((= size 0)) ; do nothing for an empty result
2105 ((< size org-babel-min-lines-for-block-output)
2106 (goto-char beg)
2107 (dotimes (n size)
2108 (beginning-of-line 1) (insert ": ") (forward-line 1)))
2110 (goto-char beg)
2111 (insert (if results-switches
2112 (format "%s%s\n"
2113 (funcall maybe-cap "#+begin_example")
2114 results-switches)
2115 (funcall maybe-cap "#+begin_example\n")))
2116 (if (markerp end) (goto-char end) (forward-char (- end beg)))
2117 (insert (funcall maybe-cap "#+end_example\n")))))))))
2119 (defun org-babel-update-block-body (new-body)
2120 "Update the body of the current code block to NEW-BODY."
2121 (if (not (org-babel-where-is-src-block-head))
2122 (error "Not in a source block")
2123 (save-match-data
2124 (replace-match (concat (org-babel-trim new-body) "\n") nil t nil 5))
2125 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
2127 (defun org-babel-merge-params (&rest plists)
2128 "Combine all parameter association lists in PLISTS.
2129 Later elements of PLISTS override the values of previous elements.
2130 This takes into account some special considerations for certain
2131 parameters when merging lists."
2132 (let* ((results-exclusive-groups
2133 (mapcar (lambda (group) (mapcar #'symbol-name group))
2134 (cdr (assoc 'results org-babel-common-header-args-w-values))))
2135 (exports-exclusive-groups
2136 (mapcar (lambda (group) (mapcar #'symbol-name group))
2137 (cdr (assoc 'exports org-babel-common-header-args-w-values))))
2138 (variable-index 0)
2139 (e-merge (lambda (exclusive-groups &rest result-params)
2140 ;; maintain exclusivity of mutually exclusive parameters
2141 (let (output)
2142 (mapc (lambda (new-params)
2143 (mapc (lambda (new-param)
2144 (mapc (lambda (exclusive-group)
2145 (when (member new-param exclusive-group)
2146 (mapcar (lambda (excluded-param)
2147 (setq output
2148 (delete
2149 excluded-param
2150 output)))
2151 exclusive-group)))
2152 exclusive-groups)
2153 (setq output (org-uniquify
2154 (cons new-param output))))
2155 new-params))
2156 result-params)
2157 output)))
2158 params results exports tangle noweb cache vars shebang comments padline)
2160 (mapc
2161 (lambda (plist)
2162 (mapc
2163 (lambda (pair)
2164 (case (car pair)
2165 (:var
2166 (let ((name (if (listp (cdr pair))
2167 (cadr pair)
2168 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
2169 (cdr pair))
2170 (intern (match-string 1 (cdr pair)))))))
2171 (if name
2172 (setq vars
2173 (append
2174 (if (member name (mapcar #'car vars))
2175 (delq nil
2176 (mapcar
2177 (lambda (p)
2178 (unless (equal (car p) name) p))
2179 vars))
2180 vars)
2181 (list (cons name pair))))
2182 ;; if no name is given and we already have named variables
2183 ;; then assign to named variables in order
2184 (if (and vars (nth variable-index vars))
2185 (prog1 (setf (cddr (nth variable-index vars))
2186 (concat (symbol-name
2187 (car (nth variable-index vars)))
2188 "=" (cdr pair)))
2189 (incf variable-index))
2190 (error "Variable \"%s\" must be assigned a default value"
2191 (cdr pair))))))
2192 (:results
2193 (setq results (funcall e-merge results-exclusive-groups
2194 results
2195 (split-string
2196 (let ((r (cdr pair)))
2197 (if (stringp r) r (eval r)))))))
2198 (:file
2199 (when (cdr pair)
2200 (setq results (funcall e-merge results-exclusive-groups
2201 results '("file")))
2202 (unless (or (member "both" exports)
2203 (member "none" exports)
2204 (member "code" exports))
2205 (setq exports (funcall e-merge exports-exclusive-groups
2206 exports '("results"))))
2207 (setq params (cons pair (assq-delete-all (car pair) params)))))
2208 (:exports
2209 (setq exports (funcall e-merge exports-exclusive-groups
2210 exports (split-string (cdr pair)))))
2211 (:tangle ;; take the latest -- always overwrite
2212 (setq tangle (or (list (cdr pair)) tangle)))
2213 (:noweb
2214 (setq noweb (funcall e-merge
2215 '(("yes" "no" "tangle" "no-export"
2216 "strip-export" "eval"))
2217 noweb
2218 (split-string (or (cdr pair) "")))))
2219 (:cache
2220 (setq cache (funcall e-merge '(("yes" "no")) cache
2221 (split-string (or (cdr pair) "")))))
2222 (:padline
2223 (setq padline (funcall e-merge '(("yes" "no")) padline
2224 (split-string (or (cdr pair) "")))))
2225 (:shebang ;; take the latest -- always overwrite
2226 (setq shebang (or (list (cdr pair)) shebang)))
2227 (:comments
2228 (setq comments (funcall e-merge '(("yes" "no")) comments
2229 (split-string (or (cdr pair) "")))))
2230 (t ;; replace: this covers e.g. :session
2231 (setq params (cons pair (assq-delete-all (car pair) params))))))
2232 plist))
2233 plists)
2234 (setq vars (reverse vars))
2235 (while vars (setq params (cons (cons :var (cddr (pop vars))) params)))
2236 (mapc
2237 (lambda (hd)
2238 (let ((key (intern (concat ":" (symbol-name hd))))
2239 (val (eval hd)))
2240 (setf params (cons (cons key (mapconcat 'identity val " ")) params))))
2241 '(results exports tangle noweb padline cache shebang comments))
2242 params))
2244 (defvar org-babel-use-quick-and-dirty-noweb-expansion nil
2245 "Set to true to use regular expressions to expand noweb references.
2246 This results in much faster noweb reference expansion but does
2247 not properly allow code blocks to inherit the \":noweb-ref\"
2248 header argument from buffer or subtree wide properties.")
2250 (defun org-babel-noweb-p (params context)
2251 "Check if PARAMS require expansion in CONTEXT.
2252 CONTEXT may be one of :tangle, :export or :eval."
2253 (let* (intersect
2254 (intersect (lambda (as bs)
2255 (when as
2256 (if (member (car as) bs)
2257 (car as)
2258 (funcall intersect (cdr as) bs))))))
2259 (funcall intersect (case context
2260 (:tangle '("yes" "tangle" "no-export" "strip-export"))
2261 (:eval '("yes" "no-export" "strip-export" "eval"))
2262 (:export '("yes")))
2263 (split-string (or (cdr (assoc :noweb params)) "")))))
2265 (defun org-babel-expand-noweb-references (&optional info parent-buffer)
2266 "Expand Noweb references in the body of the current source code block.
2268 For example the following reference would be replaced with the
2269 body of the source-code block named 'example-block'.
2271 <<example-block>>
2273 Note that any text preceding the <<foo>> construct on a line will
2274 be interposed between the lines of the replacement text. So for
2275 example if <<foo>> is placed behind a comment, then the entire
2276 replacement text will also be commented.
2278 This function must be called from inside of the buffer containing
2279 the source-code block which holds BODY.
2281 In addition the following syntax can be used to insert the
2282 results of evaluating the source-code block named 'example-block'.
2284 <<example-block()>>
2286 Any optional arguments can be passed to example-block by placing
2287 the arguments inside the parenthesis following the convention
2288 defined by `org-babel-lob'. For example
2290 <<example-block(a=9)>>
2292 would set the value of argument \"a\" equal to \"9\". Note that
2293 these arguments are not evaluated in the current source-code
2294 block but are passed literally to the \"example-block\"."
2295 (let* ((parent-buffer (or parent-buffer (current-buffer)))
2296 (info (or info (org-babel-get-src-block-info)))
2297 (lang (nth 0 info))
2298 (body (nth 1 info))
2299 (ob-nww-start org-babel-noweb-wrap-start)
2300 (ob-nww-end org-babel-noweb-wrap-end)
2301 (comment (string= "noweb" (cdr (assoc :comments (nth 2 info)))))
2302 (rx-prefix (concat "\\(" org-babel-src-name-regexp "\\|"
2303 ":noweb-ref[ \t]+" "\\)"))
2304 (new-body "")
2305 (nb-add (lambda (text) (setq new-body (concat new-body text))))
2306 (c-wrap (lambda (text)
2307 (with-temp-buffer
2308 (funcall (intern (concat lang "-mode")))
2309 (comment-region (point) (progn (insert text) (point)))
2310 (org-babel-trim (buffer-string)))))
2311 index source-name evaluate prefix blocks-in-buffer)
2312 (with-temp-buffer
2313 (org-set-local 'org-babel-noweb-wrap-start ob-nww-start)
2314 (org-set-local 'org-babel-noweb-wrap-end ob-nww-end)
2315 (insert body) (goto-char (point-min))
2316 (setq index (point))
2317 (while (and (re-search-forward (org-babel-noweb-wrap) nil t))
2318 (save-match-data (setf source-name (match-string 1)))
2319 (save-match-data (setq evaluate (string-match "\(.*\)" source-name)))
2320 (save-match-data
2321 (setq prefix
2322 (buffer-substring (match-beginning 0)
2323 (save-excursion
2324 (beginning-of-line 1) (point)))))
2325 ;; add interval to new-body (removing noweb reference)
2326 (goto-char (match-beginning 0))
2327 (funcall nb-add (buffer-substring index (point)))
2328 (goto-char (match-end 0))
2329 (setq index (point))
2330 (funcall nb-add
2331 (with-current-buffer parent-buffer
2332 (save-restriction
2333 (widen)
2334 (mapconcat ;; interpose PREFIX between every line
2335 #'identity
2336 (split-string
2337 (if evaluate
2338 (let ((raw (org-babel-ref-resolve source-name)))
2339 (if (stringp raw) raw (format "%S" raw)))
2341 ;; retrieve from the library of babel
2342 (nth 2 (assoc (intern source-name)
2343 org-babel-library-of-babel))
2344 ;; return the contents of headlines literally
2345 (save-excursion
2346 (when (org-babel-ref-goto-headline-id source-name)
2347 (org-babel-ref-headline-body)))
2348 ;; find the expansion of reference in this buffer
2349 (let ((rx (concat rx-prefix source-name "[ \t\n]"))
2350 expansion)
2351 (save-excursion
2352 (goto-char (point-min))
2353 (if org-babel-use-quick-and-dirty-noweb-expansion
2354 (while (re-search-forward rx nil t)
2355 (let* ((i (org-babel-get-src-block-info 'light))
2356 (body (org-babel-expand-noweb-references i))
2357 (sep (or (cdr (assoc :noweb-sep (nth 2 i)))
2358 "\n"))
2359 (full (if comment
2360 ((lambda (cs)
2361 (concat (funcall c-wrap (car cs)) "\n"
2362 body "\n"
2363 (funcall c-wrap (cadr cs))))
2364 (org-babel-tangle-comment-links i))
2365 body)))
2366 (setq expansion (cons sep (cons full expansion)))))
2367 (org-babel-map-src-blocks nil
2368 (let ((i (org-babel-get-src-block-info 'light)))
2369 (when (equal (or (cdr (assoc :noweb-ref (nth 2 i)))
2370 (nth 4 i))
2371 source-name)
2372 (let* ((body (org-babel-expand-noweb-references i))
2373 (sep (or (cdr (assoc :noweb-sep (nth 2 i)))
2374 "\n"))
2375 (full (if comment
2376 ((lambda (cs)
2377 (concat (funcall c-wrap (car cs)) "\n"
2378 body "\n"
2379 (funcall c-wrap (cadr cs))))
2380 (org-babel-tangle-comment-links i))
2381 body)))
2382 (setq expansion
2383 (cons sep (cons full expansion)))))))))
2384 (and expansion
2385 (mapconcat #'identity (nreverse (cdr expansion)) "")))
2386 ;; possibly raise an error if named block doesn't exist
2387 (if (member lang org-babel-noweb-error-langs)
2388 (error "%s" (concat
2389 (org-babel-noweb-wrap source-name)
2390 "could not be resolved (see "
2391 "`org-babel-noweb-error-langs')"))
2392 "")))
2393 "[\n\r]") (concat "\n" prefix))))))
2394 (funcall nb-add (buffer-substring index (point-max))))
2395 new-body))
2397 (defun org-babel-script-escape (str &optional force)
2398 "Safely convert tables into elisp lists."
2399 (let (in-single in-double out)
2400 ((lambda (escaped) (condition-case nil (org-babel-read escaped) (error escaped)))
2401 (if (or force
2402 (and (stringp str)
2403 (> (length str) 2)
2404 (or (and (string-equal "[" (substring str 0 1))
2405 (string-equal "]" (substring str -1)))
2406 (and (string-equal "{" (substring str 0 1))
2407 (string-equal "}" (substring str -1)))
2408 (and (string-equal "(" (substring str 0 1))
2409 (string-equal ")" (substring str -1))))))
2410 (org-babel-read
2411 (concat
2413 (progn
2414 (mapc
2415 (lambda (ch)
2416 (setq
2418 (case ch
2419 (91 (if (or in-double in-single) ; [
2420 (cons 91 out)
2421 (cons 40 out)))
2422 (93 (if (or in-double in-single) ; ]
2423 (cons 93 out)
2424 (cons 41 out)))
2425 (123 (if (or in-double in-single) ; {
2426 (cons 123 out)
2427 (cons 40 out)))
2428 (125 (if (or in-double in-single) ; }
2429 (cons 125 out)
2430 (cons 41 out)))
2431 (44 (if (or in-double in-single) ; ,
2432 (cons 44 out) (cons 32 out)))
2433 (39 (if in-double ; '
2434 (cons 39 out)
2435 (setq in-single (not in-single)) (cons 34 out)))
2436 (34 (if in-single ; "
2437 (append (list 34 32) out)
2438 (setq in-double (not in-double)) (cons 34 out)))
2439 (t (cons ch out)))))
2440 (string-to-list str))
2441 (apply #'string (reverse out)))))
2442 str))))
2444 (defun org-babel-read (cell &optional inhibit-lisp-eval)
2445 "Convert the string value of CELL to a number if appropriate.
2446 Otherwise if cell looks like lisp (meaning it starts with a
2447 \"(\", \"'\", \"`\" or a \"[\") then read it as lisp, otherwise
2448 return it unmodified as a string. Optional argument NO-LISP-EVAL
2449 inhibits lisp evaluation for situations in which is it not
2450 appropriate."
2451 (if (and (stringp cell) (not (equal cell "")))
2452 (or (org-babel-number-p cell)
2453 (if (and (not inhibit-lisp-eval)
2454 (member (substring cell 0 1) '("(" "'" "`" "[")))
2455 (eval (read cell))
2456 (if (string= (substring cell 0 1) "\"")
2457 (read cell)
2458 (progn (set-text-properties 0 (length cell) nil cell) cell))))
2459 cell))
2461 (defun org-babel-number-p (string)
2462 "If STRING represents a number return its value."
2463 (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string)
2464 (= (length (substring string (match-beginning 0)
2465 (match-end 0)))
2466 (length string)))
2467 (string-to-number string)))
2469 (defun org-babel-import-elisp-from-file (file-name &optional separator)
2470 "Read the results located at FILE-NAME into an elisp table.
2471 If the table is trivial, then return it as a scalar."
2472 (let (result)
2473 (save-window-excursion
2474 (with-temp-buffer
2475 (condition-case err
2476 (progn
2477 (org-table-import file-name separator)
2478 (delete-file file-name)
2479 (setq result (mapcar (lambda (row)
2480 (mapcar #'org-babel-string-read row))
2481 (org-table-to-lisp))))
2482 (error (message "Error reading results: %s" err) nil)))
2483 (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
2484 (if (consp (car result))
2485 (if (null (cdr (car result)))
2486 (caar result)
2487 result)
2488 (car result))
2489 result))))
2491 (defun org-babel-string-read (cell)
2492 "Strip nested \"s from around strings."
2493 (org-babel-read (or (and (stringp cell)
2494 (string-match "\\\"\\(.+\\)\\\"" cell)
2495 (match-string 1 cell))
2496 cell) t))
2498 (defun org-babel-reverse-string (string)
2499 "Return the reverse of STRING."
2500 (apply 'string (reverse (string-to-list string))))
2502 (defun org-babel-chomp (string &optional regexp)
2503 "Strip trailing spaces and carriage returns from STRING.
2504 Default regexp used is \"[ \f\t\n\r\v]\" but can be
2505 overwritten by specifying a regexp as a second argument."
2506 (let ((regexp (or regexp "[ \f\t\n\r\v]")))
2507 (while (and (> (length string) 0)
2508 (string-match regexp (substring string -1)))
2509 (setq string (substring string 0 -1)))
2510 string))
2512 (defun org-babel-trim (string &optional regexp)
2513 "Strip leading and trailing spaces and carriage returns from STRING.
2514 Like `org-babel-chomp' only it runs on both the front and back
2515 of the string."
2516 (org-babel-chomp (org-babel-reverse-string
2517 (org-babel-chomp (org-babel-reverse-string string) regexp))
2518 regexp))
2520 (defvar org-babel-org-babel-call-process-region-original nil)
2521 (defun org-babel-tramp-handle-call-process-region
2522 (start end program &optional delete buffer display &rest args)
2523 "Use Tramp to handle `call-process-region'.
2524 Fixes a bug in `tramp-handle-call-process-region'."
2525 (if (and (featurep 'tramp) (file-remote-p default-directory))
2526 (let ((tmpfile (tramp-compat-make-temp-file "")))
2527 (write-region start end tmpfile)
2528 (when delete (delete-region start end))
2529 (unwind-protect
2530 ;; (apply 'call-process program tmpfile buffer display args)
2531 ;; bug in tramp
2532 (apply 'process-file program tmpfile buffer display args)
2533 (delete-file tmpfile)))
2534 ;; org-babel-call-process-region-original is the original emacs
2535 ;; definition. It is in scope from the let binding in
2536 ;; org-babel-execute-src-block
2537 (apply org-babel-call-process-region-original
2538 start end program delete buffer display args)))
2540 (defun org-babel-local-file-name (file)
2541 "Return the local name component of FILE."
2542 (if (file-remote-p file)
2543 (let (localname)
2544 (with-parsed-tramp-file-name file nil
2545 localname))
2546 file))
2548 (defun org-babel-process-file-name (name &optional no-quote-p)
2549 "Prepare NAME to be used in an external process.
2550 If NAME specifies a remote location, the remote portion of the
2551 name is removed, since in that case the process will be executing
2552 remotely. The file name is then processed by `expand-file-name'.
2553 Unless second argument NO-QUOTE-P is non-nil, the file name is
2554 additionally processed by `shell-quote-argument'"
2555 ((lambda (f) (if no-quote-p f (shell-quote-argument f)))
2556 (expand-file-name (org-babel-local-file-name name))))
2558 (defvar org-babel-temporary-directory)
2559 (unless (or noninteractive (boundp 'org-babel-temporary-directory))
2560 (defvar org-babel-temporary-directory
2561 (or (and (boundp 'org-babel-temporary-directory)
2562 (file-exists-p org-babel-temporary-directory)
2563 org-babel-temporary-directory)
2564 (make-temp-file "babel-" t))
2565 "Directory to hold temporary files created to execute code blocks.
2566 Used by `org-babel-temp-file'. This directory will be removed on
2567 Emacs shutdown."))
2569 (defmacro org-babel-result-cond (result-params scalar-form &rest table-forms)
2570 "Call the code to parse raw string results according to RESULT-PARAMS."
2571 (declare (indent 1))
2572 `(unless (member "none" ,result-params)
2573 (if (or (member "scalar" ,result-params)
2574 (member "verbatim" ,result-params)
2575 (member "html" ,result-params)
2576 (member "code" ,result-params)
2577 (member "pp" ,result-params)
2578 (and (member "output" ,result-params)
2579 (not (member "table" ,result-params))))
2580 ,scalar-form
2581 ,@table-forms)))
2583 (defun org-babel-temp-file (prefix &optional suffix)
2584 "Create a temporary file in the `org-babel-temporary-directory'.
2585 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2586 value of `temporary-file-directory' temporarily set to the value
2587 of `org-babel-temporary-directory'."
2588 (let ((temporary-file-directory
2589 (if (file-remote-p default-directory)
2590 (concat (file-remote-p default-directory) "/tmp")
2591 (or (and (boundp 'org-babel-temporary-directory)
2592 (file-exists-p org-babel-temporary-directory)
2593 org-babel-temporary-directory)
2594 temporary-file-directory))))
2595 (make-temp-file prefix nil suffix)))
2597 (defun org-babel-remove-temporary-directory ()
2598 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2599 (when (and (boundp 'org-babel-temporary-directory)
2600 (file-exists-p org-babel-temporary-directory))
2601 ;; taken from `delete-directory' in files.el
2602 (condition-case nil
2603 (progn
2604 (mapc (lambda (file)
2605 ;; This test is equivalent to
2606 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2607 ;; but more efficient
2608 (if (eq t (car (file-attributes file)))
2609 (delete-directory file)
2610 (delete-file file)))
2611 ;; We do not want to delete "." and "..".
2612 (directory-files org-babel-temporary-directory 'full
2613 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2614 (delete-directory org-babel-temporary-directory))
2615 (error
2616 (message "Failed to remove temporary Org-babel directory %s"
2617 (if (boundp 'org-babel-temporary-directory)
2618 org-babel-temporary-directory
2619 "[directory not defined]"))))))
2621 (add-hook 'kill-emacs-hook 'org-babel-remove-temporary-directory)
2623 (provide 'ob-core)
2625 ;; Local variables:
2626 ;; generated-autoload-file: "org-loaddefs.el"
2627 ;; End:
2629 ;;; ob-core.el ends here