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