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