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