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