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