Don't skip call lines searching for results
[org-mode.git] / lisp / ob-core.el
blob85bd27dc0046165150cc4d5dbf3b602208340222
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")
534 (:exports . "results") (:hlines . "yes"))
535 "Default arguments to use when evaluating an inline source block.")
536 (put 'org-babel-default-inline-header-args 'safe-local-variable
537 (org-babel-header-args-safe-fn org-babel-safe-header-args))
539 (defvar org-babel-data-names '("tblname" "results" "name"))
541 (defvar org-babel-result-regexp
542 (concat "^[ \t]*#\\+"
543 (regexp-opt org-babel-data-names t)
544 "\\(\\[\\("
545 ;; FIXME The string below is `org-ts-regexp'
546 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
547 " \\)?\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*")
548 "Regular expression used to match result lines.
549 If the results are associated with a hash key then the hash will
550 be saved in the second match data.")
552 (defvar org-babel-result-w-name-regexp
553 (concat org-babel-result-regexp
554 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
556 (defvar org-babel-min-lines-for-block-output 10
557 "The minimum number of lines for block output.
558 If number of lines of output is equal to or exceeds this
559 value, the output is placed in a #+begin_example...#+end_example
560 block. Otherwise the output is marked as literal by inserting
561 colons at the starts of the lines. This variable only takes
562 effect if the :results output option is in effect.")
564 (defvar org-babel-noweb-error-langs nil
565 "Languages for which Babel will raise literate programming errors.
566 List of languages for which errors should be raised when the
567 source code block satisfying a noweb reference in this language
568 can not be resolved.")
570 (defvar org-babel-hash-show 4
571 "Number of initial characters to show of a hidden results hash.")
573 (defvar org-babel-hash-show-time nil
574 "Non-nil means show the time the code block was evaluated in the result hash.")
576 (defvar org-babel-after-execute-hook nil
577 "Hook for functions to be called after `org-babel-execute-src-block'")
579 (defun org-babel-named-src-block-regexp-for-name (name)
580 "This generates a regexp used to match a src block named NAME."
581 (concat org-babel-src-name-regexp (regexp-quote name)
582 "[ \t(]*[\r\n]\\(?:^#.*[\r\n]\\)*"
583 (substring org-babel-src-block-regexp 1)))
585 (defun org-babel-named-data-regexp-for-name (name)
586 "This generates a regexp used to match data named NAME."
587 (concat org-babel-result-regexp (regexp-quote name) "\\([ \t]\\|$\\)"))
589 ;;; functions
590 (defvar call-process-region)
591 (defvar org-babel-current-src-block-location nil
592 "Marker pointing to the src block currently being executed.
593 This may also point to a call line or an inline code block. If
594 multiple blocks are being executed (e.g., in chained execution
595 through use of the :var header argument) this marker points to
596 the outer-most code block.")
598 ;;;###autoload
599 (defun org-babel-execute-src-block (&optional arg info params)
600 "Execute the current source code block.
601 Insert the results of execution into the buffer. Source code
602 execution and the collection and formatting of results can be
603 controlled through a variety of header arguments.
605 With prefix argument ARG, force re-execution even if an existing
606 result cached in the buffer would otherwise have been returned.
608 Optionally supply a value for INFO in the form returned by
609 `org-babel-get-src-block-info'.
611 Optionally supply a value for PARAMS which will be merged with
612 the header arguments specified at the front of the source code
613 block."
614 (interactive)
615 (let* ((org-babel-current-src-block-location
616 (or org-babel-current-src-block-location
617 (nth 6 info)
618 (org-babel-where-is-src-block-head)))
619 (info (if info
620 (copy-tree info)
621 (org-babel-get-src-block-info)))
622 (merged-params (org-babel-merge-params (nth 2 info) params)))
623 (when (org-babel-check-evaluate
624 (let ((i info)) (setf (nth 2 i) merged-params) i))
625 (let* ((params (if params
626 (org-babel-process-params merged-params)
627 (nth 2 info)))
628 (cachep (and (not arg) (cdr (assoc :cache params))
629 (string= "yes" (cdr (assoc :cache params)))))
630 (new-hash (when cachep (org-babel-sha1-hash info)))
631 (old-hash (when cachep (org-babel-current-result-hash)))
632 (cache-current-p (and (not arg) new-hash
633 (equal new-hash old-hash))))
634 (cond
635 (cache-current-p
636 (save-excursion ;; return cached result
637 (goto-char (org-babel-where-is-src-block-result nil info))
638 (end-of-line 1) (forward-char 1)
639 (let ((result (org-babel-read-result)))
640 (message (replace-regexp-in-string
641 "%" "%%" (format "%S" result))) result)))
642 ((org-babel-confirm-evaluate
643 (let ((i info)) (setf (nth 2 i) merged-params) i))
644 (let* ((lang (nth 0 info))
645 (result-params (cdr (assoc :result-params params)))
646 (body (setf (nth 1 info)
647 (if (org-babel-noweb-p params :eval)
648 (org-babel-expand-noweb-references info)
649 (nth 1 info))))
650 (dir (cdr (assoc :dir params)))
651 (default-directory
652 (or (and dir (file-name-as-directory (expand-file-name dir)))
653 default-directory))
654 (org-babel-call-process-region-original ;; for tramp handler
655 (or (org-bound-and-true-p
656 org-babel-call-process-region-original)
657 (symbol-function 'call-process-region)))
658 (indent (nth 5 info))
659 result cmd)
660 (unwind-protect
661 (let ((call-process-region
662 (lambda (&rest args)
663 (apply 'org-babel-tramp-handle-call-process-region
664 args))))
665 (let ((lang-check
666 (lambda (f)
667 (let ((f (intern (concat "org-babel-execute:" f))))
668 (when (fboundp f) f)))))
669 (setq cmd
670 (or (funcall lang-check lang)
671 (funcall lang-check
672 (symbol-name
673 (cdr (assoc lang org-src-lang-modes))))
674 (error "No org-babel-execute function for %s!"
675 lang))))
676 (message "executing %s code block%s..."
677 (capitalize lang)
678 (if (nth 4 info) (format " (%s)" (nth 4 info)) ""))
679 (if (member "none" result-params)
680 (progn
681 (funcall cmd body params)
682 (message "result silenced")
683 (setq result nil))
684 (setq result
685 (let ((result (funcall cmd body params)))
686 (if (and (eq (cdr (assoc :result-type params))
687 'value)
688 (or (member "vector" result-params)
689 (member "table" result-params))
690 (not (listp result)))
691 (list (list result)) result)))
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 (defvar org-src-window-setup)
953 ;;;###autoload
954 (defun org-babel-switch-to-session-with-code (&optional arg info)
955 "Switch to code buffer and display session."
956 (interactive "P")
957 (let ((swap-windows
958 (lambda ()
959 (let ((other-window-buffer (window-buffer (next-window))))
960 (set-window-buffer (next-window) (current-buffer))
961 (set-window-buffer (selected-window) other-window-buffer))
962 (other-window 1)))
963 (info (org-babel-get-src-block-info))
964 (org-src-window-setup 'reorganize-frame))
965 (save-excursion
966 (org-babel-switch-to-session arg info))
967 (org-edit-src-code)
968 (funcall swap-windows)))
970 (defmacro org-babel-do-in-edit-buffer (&rest body)
971 "Evaluate BODY in edit buffer if there is a code block at point.
972 Return t if a code block was found at point, nil otherwise."
973 `(let ((org-src-window-setup 'switch-invisibly))
974 (when (and (org-babel-where-is-src-block-head)
975 (org-edit-src-code nil nil nil))
976 (unwind-protect (progn ,@body)
977 (if (org-bound-and-true-p org-edit-src-from-org-mode)
978 (org-edit-src-exit)))
979 t)))
980 (def-edebug-spec org-babel-do-in-edit-buffer (body))
982 (defun org-babel-do-key-sequence-in-edit-buffer (key)
983 "Read key sequence and execute the command in edit buffer.
984 Enter a key sequence to be executed in the language major-mode
985 edit buffer. For example, TAB will alter the contents of the
986 Org-mode code block according to the effect of TAB in the
987 language major-mode buffer. For languages that support
988 interactive sessions, this can be used to send code from the Org
989 buffer to the session for evaluation using the native major-mode
990 evaluation mechanisms."
991 (interactive "kEnter key-sequence to execute in edit buffer: ")
992 (org-babel-do-in-edit-buffer
993 (call-interactively
994 (key-binding (or key (read-key-sequence nil))))))
996 (defvar org-bracket-link-regexp)
998 (defun org-babel-active-location-p ()
999 (memq (car (save-match-data (org-element-context)))
1000 '(babel-call inline-babel-call inline-src-block src-block)))
1002 ;;;###autoload
1003 (defun org-babel-open-src-block-result (&optional re-run)
1004 "If `point' is on a src block then open the results of the
1005 source code block, otherwise return nil. With optional prefix
1006 argument RE-RUN the source-code block is evaluated even if
1007 results already exist."
1008 (interactive "P")
1009 (let ((info (org-babel-get-src-block-info 'light)))
1010 (when info
1011 (save-excursion
1012 ;; go to the results, if there aren't any then run the block
1013 (goto-char (or (and (not re-run) (org-babel-where-is-src-block-result))
1014 (progn (org-babel-execute-src-block)
1015 (org-babel-where-is-src-block-result))))
1016 (end-of-line 1)
1017 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
1018 ;; open the results
1019 (if (looking-at org-bracket-link-regexp)
1020 ;; file results
1021 (org-open-at-point)
1022 (let ((r (org-babel-format-result
1023 (org-babel-read-result) (cdr (assoc :sep (nth 2 info))))))
1024 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
1025 (delete-region (point-min) (point-max))
1026 (insert r)))
1027 t))))
1029 ;;;###autoload
1030 (defmacro org-babel-map-src-blocks (file &rest body)
1031 "Evaluate BODY forms on each source-block in FILE.
1032 If FILE is nil evaluate BODY forms on source blocks in current
1033 buffer. During evaluation of BODY the following local variables
1034 are set relative to the currently matched code block.
1036 full-block ------- string holding the entirety of the code block
1037 beg-block -------- point at the beginning of the code block
1038 end-block -------- point at the end of the matched code block
1039 lang ------------- string holding the language of the code block
1040 beg-lang --------- point at the beginning of the lang
1041 end-lang --------- point at the end of the lang
1042 switches --------- string holding the switches
1043 beg-switches ----- point at the beginning of the switches
1044 end-switches ----- point at the end of the switches
1045 header-args ------ string holding the header-args
1046 beg-header-args -- point at the beginning of the header-args
1047 end-header-args -- point at the end of the header-args
1048 body ------------- string holding the body of the code block
1049 beg-body --------- point at the beginning of the body
1050 end-body --------- point at the end of the body"
1051 (declare (indent 1))
1052 (let ((tempvar (make-symbol "file")))
1053 `(let* ((,tempvar ,file)
1054 (visited-p (or (null ,tempvar)
1055 (get-file-buffer (expand-file-name ,tempvar))))
1056 (point (point)) to-be-removed)
1057 (save-window-excursion
1058 (when ,tempvar (find-file ,tempvar))
1059 (setq to-be-removed (current-buffer))
1060 (goto-char (point-min))
1061 (while (re-search-forward org-babel-src-block-regexp nil t)
1062 (when (org-babel-active-location-p)
1063 (goto-char (match-beginning 0))
1064 (let ((full-block (match-string 0))
1065 (beg-block (match-beginning 0))
1066 (end-block (match-end 0))
1067 (lang (match-string 2))
1068 (beg-lang (match-beginning 2))
1069 (end-lang (match-end 2))
1070 (switches (match-string 3))
1071 (beg-switches (match-beginning 3))
1072 (end-switches (match-end 3))
1073 (header-args (match-string 4))
1074 (beg-header-args (match-beginning 4))
1075 (end-header-args (match-end 4))
1076 (body (match-string 5))
1077 (beg-body (match-beginning 5))
1078 (end-body (match-end 5)))
1079 ,@body
1080 (goto-char end-block)))))
1081 (unless visited-p (kill-buffer to-be-removed))
1082 (goto-char point))))
1083 (def-edebug-spec org-babel-map-src-blocks (form body))
1085 ;;;###autoload
1086 (defmacro org-babel-map-inline-src-blocks (file &rest body)
1087 "Evaluate BODY forms on each inline source-block in FILE.
1088 If FILE is nil evaluate BODY forms on source blocks in current
1089 buffer."
1090 (declare (indent 1))
1091 (let ((tempvar (make-symbol "file")))
1092 `(let* ((,tempvar ,file)
1093 (visited-p (or (null ,tempvar)
1094 (get-file-buffer (expand-file-name ,tempvar))))
1095 (point (point)) to-be-removed)
1096 (save-window-excursion
1097 (when ,tempvar (find-file ,tempvar))
1098 (setq to-be-removed (current-buffer))
1099 (goto-char (point-min))
1100 (while (re-search-forward org-babel-inline-src-block-regexp nil t)
1101 (when (org-babel-active-location-p)
1102 (goto-char (match-beginning 1))
1103 (save-match-data ,@body))
1104 (goto-char (match-end 0))))
1105 (unless visited-p (kill-buffer to-be-removed))
1106 (goto-char point))))
1107 (def-edebug-spec org-babel-map-inline-src-blocks (form body))
1109 (defvar org-babel-lob-one-liner-regexp)
1111 ;;;###autoload
1112 (defmacro org-babel-map-call-lines (file &rest body)
1113 "Evaluate BODY forms on each call line in FILE.
1114 If FILE is nil evaluate BODY forms on source blocks in current
1115 buffer."
1116 (declare (indent 1))
1117 (let ((tempvar (make-symbol "file")))
1118 `(let* ((,tempvar ,file)
1119 (visited-p (or (null ,tempvar)
1120 (get-file-buffer (expand-file-name ,tempvar))))
1121 (point (point)) to-be-removed)
1122 (save-window-excursion
1123 (when ,tempvar (find-file ,tempvar))
1124 (setq to-be-removed (current-buffer))
1125 (goto-char (point-min))
1126 (while (re-search-forward org-babel-lob-one-liner-regexp nil t)
1127 (when (org-babel-active-location-p)
1128 (goto-char (match-beginning 1))
1129 (save-match-data ,@body))
1130 (goto-char (match-end 0))))
1131 (unless visited-p (kill-buffer to-be-removed))
1132 (goto-char point))))
1133 (def-edebug-spec org-babel-map-call-lines (form body))
1135 ;;;###autoload
1136 (defmacro org-babel-map-executables (file &rest body)
1137 (declare (indent 1))
1138 (let ((tempvar (make-symbol "file"))
1139 (rx (make-symbol "rx")))
1140 `(let* ((,tempvar ,file)
1141 (,rx (concat "\\(" org-babel-src-block-regexp
1142 "\\|" org-babel-inline-src-block-regexp
1143 "\\|" org-babel-lob-one-liner-regexp "\\)"))
1144 (visited-p (or (null ,tempvar)
1145 (get-file-buffer (expand-file-name ,tempvar))))
1146 (point (point)) to-be-removed)
1147 (save-window-excursion
1148 (when ,tempvar (find-file ,tempvar))
1149 (setq to-be-removed (current-buffer))
1150 (goto-char (point-min))
1151 (while (re-search-forward ,rx nil t)
1152 (when (org-babel-active-location-p)
1153 (goto-char (match-beginning 1))
1154 (when (looking-at org-babel-inline-src-block-regexp)
1155 (forward-char 1))
1156 (save-match-data ,@body))
1157 (goto-char (match-end 0))))
1158 (unless visited-p (kill-buffer to-be-removed))
1159 (goto-char point))))
1160 (def-edebug-spec org-babel-map-executables (form body))
1162 ;;;###autoload
1163 (defun org-babel-execute-buffer (&optional arg)
1164 "Execute source code blocks in a buffer.
1165 Call `org-babel-execute-src-block' on every source block in
1166 the current buffer."
1167 (interactive "P")
1168 (org-babel-eval-wipe-error-buffer)
1169 (org-save-outline-visibility t
1170 (org-babel-map-executables nil
1171 (if (looking-at org-babel-lob-one-liner-regexp)
1172 (org-babel-lob-execute-maybe)
1173 (org-babel-execute-src-block arg)))))
1175 ;;;###autoload
1176 (defun org-babel-execute-subtree (&optional arg)
1177 "Execute source code blocks in a subtree.
1178 Call `org-babel-execute-src-block' on every source block in
1179 the current subtree."
1180 (interactive "P")
1181 (save-restriction
1182 (save-excursion
1183 (org-narrow-to-subtree)
1184 (org-babel-execute-buffer arg)
1185 (widen))))
1187 ;;;###autoload
1188 (defun org-babel-sha1-hash (&optional info)
1189 "Generate an sha1 hash based on the value of info."
1190 (interactive)
1191 (let ((print-level nil)
1192 (info (or info (org-babel-get-src-block-info))))
1193 (setf (nth 2 info)
1194 (sort (copy-sequence (nth 2 info))
1195 (lambda (a b) (string< (car a) (car b)))))
1196 (let* ((rm (lambda (lst)
1197 (dolist (p '("replace" "silent" "none"
1198 "append" "prepend"))
1199 (setq lst (remove p lst)))
1200 lst))
1201 (norm (lambda (arg)
1202 (let ((v (if (and (listp (cdr arg)) (null (cddr arg)))
1203 (copy-sequence (cdr arg))
1204 (cdr arg))))
1205 (when (and v (not (and (sequencep v)
1206 (not (consp v))
1207 (= (length v) 0))))
1208 (cond
1209 ((and (listp v) ; lists are sorted
1210 (member (car arg) '(:result-params)))
1211 (sort (funcall rm v) #'string<))
1212 ((and (stringp v) ; strings are sorted
1213 (member (car arg) '(:results :exports)))
1214 (mapconcat #'identity (sort (funcall rm (split-string v))
1215 #'string<) " "))
1216 (t v)))))))
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 (hash (sha1 it)))
1227 (when (org-called-interactively-p 'interactive) (message hash))
1228 hash))))
1230 (defun org-babel-current-result-hash ()
1231 "Return the current in-buffer hash."
1232 (org-babel-where-is-src-block-result)
1233 (org-no-properties (match-string 5)))
1235 (defun org-babel-set-current-result-hash (hash)
1236 "Set the current in-buffer hash to HASH."
1237 (org-babel-where-is-src-block-result)
1238 (save-excursion (goto-char (match-beginning 5))
1239 (mapc #'delete-overlay (overlays-at (point)))
1240 (forward-char org-babel-hash-show)
1241 (mapc #'delete-overlay (overlays-at (point)))
1242 (replace-match hash nil nil nil 5)
1243 (goto-char (point-at-bol))
1244 (org-babel-hide-hash)))
1246 (defun org-babel-hide-hash ()
1247 "Hide the hash in the current results line.
1248 Only the initial `org-babel-hash-show' characters of the hash
1249 will remain visible."
1250 (add-to-invisibility-spec '(org-babel-hide-hash . t))
1251 (save-excursion
1252 (when (and (re-search-forward org-babel-result-regexp nil t)
1253 (match-string 5))
1254 (let* ((start (match-beginning 5))
1255 (hide-start (+ org-babel-hash-show start))
1256 (end (match-end 5))
1257 (hash (match-string 5))
1258 ov1 ov2)
1259 (setq ov1 (make-overlay start hide-start))
1260 (setq ov2 (make-overlay hide-start end))
1261 (overlay-put ov2 'invisible 'org-babel-hide-hash)
1262 (overlay-put ov1 'babel-hash hash)))))
1264 (defun org-babel-hide-all-hashes ()
1265 "Hide the hash in the current buffer.
1266 Only the initial `org-babel-hash-show' characters of each hash
1267 will remain visible. This function should be called as part of
1268 the `org-mode-hook'."
1269 (save-excursion
1270 (while (and (not org-babel-hash-show-time)
1271 (re-search-forward org-babel-result-regexp nil t))
1272 (goto-char (match-beginning 0))
1273 (org-babel-hide-hash)
1274 (goto-char (match-end 0)))))
1275 (add-hook 'org-mode-hook 'org-babel-hide-all-hashes)
1277 (defun org-babel-hash-at-point (&optional point)
1278 "Return the value of the hash at POINT.
1279 The hash is also added as the last element of the kill ring.
1280 This can be called with C-c C-c."
1281 (interactive)
1282 (let ((hash (car (delq nil (mapcar
1283 (lambda (ol) (overlay-get ol 'babel-hash))
1284 (overlays-at (or point (point))))))))
1285 (when hash (kill-new hash) (message hash))))
1286 (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-hash-at-point)
1288 (defun org-babel-result-hide-spec ()
1289 "Hide portions of results lines.
1290 Add `org-babel-hide-result' as an invisibility spec for hiding
1291 portions of results lines."
1292 (add-to-invisibility-spec '(org-babel-hide-result . t)))
1293 (add-hook 'org-mode-hook 'org-babel-result-hide-spec)
1295 (defvar org-babel-hide-result-overlays nil
1296 "Overlays hiding results.")
1298 (defun org-babel-result-hide-all ()
1299 "Fold all results in the current buffer."
1300 (interactive)
1301 (org-babel-show-result-all)
1302 (save-excursion
1303 (while (re-search-forward org-babel-result-regexp nil t)
1304 (save-excursion (goto-char (match-beginning 0))
1305 (org-babel-hide-result-toggle-maybe)))))
1307 (defun org-babel-show-result-all ()
1308 "Unfold all results in the current buffer."
1309 (mapc 'delete-overlay org-babel-hide-result-overlays)
1310 (setq org-babel-hide-result-overlays nil))
1312 ;;;###autoload
1313 (defun org-babel-hide-result-toggle-maybe ()
1314 "Toggle visibility of result at point."
1315 (interactive)
1316 (let ((case-fold-search t))
1317 (if (save-excursion
1318 (beginning-of-line 1)
1319 (looking-at org-babel-result-regexp))
1320 (progn (org-babel-hide-result-toggle)
1321 t) ;; to signal that we took action
1322 nil))) ;; to signal that we did not
1324 (defun org-babel-hide-result-toggle (&optional force)
1325 "Toggle the visibility of the current result."
1326 (interactive)
1327 (save-excursion
1328 (beginning-of-line)
1329 (if (re-search-forward org-babel-result-regexp nil t)
1330 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
1331 (end (progn
1332 (while (looking-at org-babel-multi-line-header-regexp)
1333 (forward-line 1))
1334 (goto-char (- (org-babel-result-end) 1)) (point)))
1336 (if (memq t (mapcar (lambda (overlay)
1337 (eq (overlay-get overlay 'invisible)
1338 'org-babel-hide-result))
1339 (overlays-at start)))
1340 (if (or (not force) (eq force 'off))
1341 (mapc (lambda (ov)
1342 (when (member ov org-babel-hide-result-overlays)
1343 (setq org-babel-hide-result-overlays
1344 (delq ov org-babel-hide-result-overlays)))
1345 (when (eq (overlay-get ov 'invisible)
1346 'org-babel-hide-result)
1347 (delete-overlay ov)))
1348 (overlays-at start)))
1349 (setq ov (make-overlay start end))
1350 (overlay-put ov 'invisible 'org-babel-hide-result)
1351 ;; make the block accessible to isearch
1352 (overlay-put
1353 ov 'isearch-open-invisible
1354 (lambda (ov)
1355 (when (member ov org-babel-hide-result-overlays)
1356 (setq org-babel-hide-result-overlays
1357 (delq ov org-babel-hide-result-overlays)))
1358 (when (eq (overlay-get ov 'invisible)
1359 'org-babel-hide-result)
1360 (delete-overlay ov))))
1361 (push ov org-babel-hide-result-overlays)))
1362 (error "Not looking at a result line"))))
1364 ;; org-tab-after-check-for-cycling-hook
1365 (add-hook 'org-tab-first-hook 'org-babel-hide-result-toggle-maybe)
1366 ;; Remove overlays when changing major mode
1367 (add-hook 'org-mode-hook
1368 (lambda () (org-add-hook 'change-major-mode-hook
1369 'org-babel-show-result-all 'append 'local)))
1371 (defvar org-file-properties)
1372 (defun org-babel-params-from-properties (&optional lang)
1373 "Retrieve parameters specified as properties.
1374 Return a list of association lists of source block params
1375 specified in the properties of the current outline entry."
1376 (save-match-data
1377 (list
1378 ;; DEPRECATED header arguments specified as separate property at
1379 ;; point of definition
1380 (let (val sym)
1381 (org-babel-parse-multiple-vars
1382 (delq nil
1383 (mapcar
1384 (lambda (header-arg)
1385 (and (setq val (org-entry-get (point) header-arg t))
1386 (cons (intern (concat ":" header-arg))
1387 (org-babel-read val))))
1388 (mapcar
1389 #'symbol-name
1390 (mapcar
1391 #'car
1392 (org-babel-combine-header-arg-lists
1393 org-babel-common-header-args-w-values
1394 (progn
1395 (setq sym (intern (concat "org-babel-header-args:" lang)))
1396 (and (boundp sym) (eval sym))))))))))
1397 ;; header arguments specified with the header-args property at
1398 ;; point of call
1399 (org-babel-parse-header-arguments
1400 (org-entry-get org-babel-current-src-block-location
1401 "header-args" 'inherit))
1402 (when lang ;; language-specific header arguments at point of call
1403 (org-babel-parse-header-arguments
1404 (org-entry-get org-babel-current-src-block-location
1405 (concat "header-args:" lang) 'inherit))))))
1407 (defvar org-src-preserve-indentation)
1408 (defun org-babel-parse-src-block-match ()
1409 "Parse the results from a match of the `org-babel-src-block-regexp'."
1410 (let* ((block-indentation (length (match-string 1)))
1411 (lang (org-no-properties (match-string 2)))
1412 (lang-headers (intern (concat "org-babel-default-header-args:" lang)))
1413 (switches (match-string 3))
1414 (body (org-no-properties
1415 (let* ((body (match-string 5))
1416 (sub-length (- (length body) 1)))
1417 (if (and (> sub-length 0)
1418 (string= "\n" (substring body sub-length)))
1419 (substring body 0 sub-length)
1420 (or body "")))))
1421 (preserve-indentation (or org-src-preserve-indentation
1422 (save-match-data
1423 (string-match "-i\\>" switches)))))
1424 (list lang
1425 ;; get block body less properties, protective commas, and indentation
1426 (with-temp-buffer
1427 (save-match-data
1428 (insert (org-unescape-code-in-string body))
1429 (unless preserve-indentation (org-do-remove-indentation))
1430 (buffer-string)))
1431 (apply #'org-babel-merge-params
1432 org-babel-default-header-args
1433 (when (boundp lang-headers) (eval lang-headers))
1434 (append
1435 (org-babel-params-from-properties lang)
1436 (list (org-babel-parse-header-arguments
1437 (org-no-properties (or (match-string 4) ""))))))
1438 switches
1439 block-indentation)))
1441 (defun org-babel-parse-inline-src-block-match ()
1442 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
1443 (let* ((lang (org-no-properties (match-string 2)))
1444 (lang-headers (intern (concat "org-babel-default-header-args:" lang))))
1445 (list lang
1446 (org-unescape-code-in-string (org-no-properties (match-string 5)))
1447 (apply #'org-babel-merge-params
1448 org-babel-default-inline-header-args
1449 (if (boundp lang-headers) (eval lang-headers) nil)
1450 (append
1451 (org-babel-params-from-properties lang)
1452 (list (org-babel-parse-header-arguments
1453 (org-no-properties (or (match-string 4) "")))))))))
1455 (defun org-babel-balanced-split (string alts)
1456 "Split STRING on instances of ALTS.
1457 ALTS is a cons of two character options where each option may be
1458 either the numeric code of a single character or a list of
1459 character alternatives. For example to split on balanced
1460 instances of \"[ \t]:\" set ALTS to '((32 9) . 58)."
1461 (let* ((matches (lambda (ch spec) (if (listp spec) (member ch spec) (equal spec ch))))
1462 (matched (lambda (ch last)
1463 (if (consp alts)
1464 (and (funcall matches ch (cdr alts))
1465 (funcall matches last (car alts)))
1466 (funcall matches ch alts))))
1467 (balance 0) (last 0)
1468 quote partial lst)
1469 (mapc (lambda (ch) ; split on [], (), "" balanced instances of [ \t]:
1470 (setq balance (+ balance
1471 (cond ((or (equal 91 ch) (equal 40 ch)) 1)
1472 ((or (equal 93 ch) (equal 41 ch)) -1)
1473 (t 0))))
1474 (when (and (equal 34 ch) (not (equal 92 last)))
1475 (setq quote (not quote)))
1476 (setq partial (cons ch partial))
1477 (when (and (= balance 0) (not quote) (funcall matched ch last))
1478 (setq lst (cons (apply #'string (nreverse
1479 (if (consp alts)
1480 (cddr partial)
1481 (cdr partial))))
1482 lst))
1483 (setq partial nil))
1484 (setq last ch))
1485 (string-to-list string))
1486 (nreverse (cons (apply #'string (nreverse partial)) lst))))
1488 (defun org-babel-join-splits-near-ch (ch list)
1489 "Join splits where \"=\" is on either end of the split."
1490 (let ((last= (lambda (str) (= ch (aref str (1- (length str))))))
1491 (first= (lambda (str) (= ch (aref str 0)))))
1492 (reverse
1493 (org-reduce (lambda (acc el)
1494 (let ((head (car acc)))
1495 (if (and head (or (funcall last= head) (funcall first= el)))
1496 (cons (concat head el) (cdr acc))
1497 (cons el acc))))
1498 list :initial-value nil))))
1500 (defun org-babel-parse-header-arguments (arg-string)
1501 "Parse a string of header arguments returning an alist."
1502 (when (> (length arg-string) 0)
1503 (org-babel-parse-multiple-vars
1504 (delq nil
1505 (mapcar
1506 (lambda (arg)
1507 (if (string-match
1508 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1509 arg)
1510 (cons (intern (match-string 1 arg))
1511 (org-babel-read (org-babel-chomp (match-string 2 arg))))
1512 (cons (intern (org-babel-chomp arg)) nil)))
1513 (let ((raw (org-babel-balanced-split arg-string '((32 9) . 58))))
1514 (cons (car raw) (mapcar (lambda (r) (concat ":" r)) (cdr raw)))))))))
1516 (defun org-babel-parse-multiple-vars (header-arguments)
1517 "Expand multiple variable assignments behind a single :var keyword.
1519 This allows expression of multiple variables with one :var as
1520 shown below.
1522 #+PROPERTY: var foo=1, bar=2"
1523 (let (results)
1524 (mapc (lambda (pair)
1525 (if (eq (car pair) :var)
1526 (mapcar (lambda (v) (push (cons :var (org-babel-trim v)) results))
1527 (org-babel-join-splits-near-ch
1528 61 (org-babel-balanced-split (cdr pair) 32)))
1529 (push pair results)))
1530 header-arguments)
1531 (nreverse results)))
1533 (defun org-babel-process-params (params)
1534 "Expand variables in PARAMS and add summary parameters."
1535 (let* ((processed-vars (mapcar (lambda (el)
1536 (if (consp (cdr el))
1537 (cdr el)
1538 (org-babel-ref-parse (cdr el))))
1539 (org-babel-get-header params :var)))
1540 (vars-and-names (if (and (assoc :colname-names params)
1541 (assoc :rowname-names params))
1542 (list processed-vars)
1543 (org-babel-disassemble-tables
1544 processed-vars
1545 (cdr (assoc :hlines params))
1546 (cdr (assoc :colnames params))
1547 (cdr (assoc :rownames params)))))
1548 (raw-result (or (cdr (assoc :results params)) ""))
1549 (result-params (append
1550 (split-string (if (stringp raw-result)
1551 raw-result
1552 (eval raw-result)))
1553 (cdr (assoc :result-params params)))))
1554 (append
1555 (mapcar (lambda (var) (cons :var var)) (car vars-and-names))
1556 (list
1557 (cons :colname-names (or (cdr (assoc :colname-names params))
1558 (cadr vars-and-names)))
1559 (cons :rowname-names (or (cdr (assoc :rowname-names params))
1560 (caddr vars-and-names)))
1561 (cons :result-params result-params)
1562 (cons :result-type (cond ((member "output" result-params) 'output)
1563 ((member "value" result-params) 'value)
1564 (t 'value))))
1565 (org-babel-get-header params :var 'other))))
1567 ;; row and column names
1568 (defun org-babel-del-hlines (table)
1569 "Remove all 'hlines from TABLE."
1570 (remove 'hline table))
1572 (defun org-babel-get-colnames (table)
1573 "Return the column names of TABLE.
1574 Return a cons cell, the `car' of which contains the TABLE less
1575 colnames, and the `cdr' of which contains a list of the column
1576 names."
1577 (if (equal 'hline (nth 1 table))
1578 (cons (cddr table) (car table))
1579 (cons (cdr table) (car table))))
1581 (defun org-babel-get-rownames (table)
1582 "Return the row names of TABLE.
1583 Return a cons cell, the `car' of which contains the TABLE less
1584 rownames, and the `cdr' of which contains a list of the rownames.
1585 Note: this function removes any hlines in TABLE."
1586 (let* ((table (org-babel-del-hlines table))
1587 (rownames (funcall (lambda ()
1588 (let ((tp table))
1589 (mapcar
1590 (lambda (row)
1591 (prog1
1592 (pop (car tp))
1593 (setq tp (cdr tp))))
1594 table))))))
1595 (cons table rownames)))
1597 (defun org-babel-put-colnames (table colnames)
1598 "Add COLNAMES to TABLE if they exist."
1599 (if colnames (apply 'list colnames 'hline table) table))
1601 (defun org-babel-put-rownames (table rownames)
1602 "Add ROWNAMES to TABLE if they exist."
1603 (if rownames
1604 (mapcar (lambda (row)
1605 (if (listp row)
1606 (cons (or (pop rownames) "") row)
1607 row)) table)
1608 table))
1610 (defun org-babel-pick-name (names selector)
1611 "Select one out of an alist of row or column names.
1612 SELECTOR can be either a list of names in which case those names
1613 will be returned directly, or an index into the list NAMES in
1614 which case the indexed names will be return."
1615 (if (listp selector)
1616 selector
1617 (when names
1618 (if (and selector (symbolp selector) (not (equal t selector)))
1619 (cdr (assoc selector names))
1620 (if (integerp selector)
1621 (nth (- selector 1) names)
1622 (cdr (car (last names))))))))
1624 (defun org-babel-disassemble-tables (vars hlines colnames rownames)
1625 "Parse tables for further processing.
1626 Process the variables in VARS according to the HLINES,
1627 ROWNAMES and COLNAMES header arguments. Return a list consisting
1628 of the vars, cnames and rnames."
1629 (let (cnames rnames)
1630 (list
1631 (mapcar
1632 (lambda (var)
1633 (when (listp (cdr var))
1634 (when (and (not (equal colnames "no"))
1635 (or colnames (and (equal (nth 1 (cdr var)) 'hline)
1636 (not (member 'hline (cddr (cdr var)))))))
1637 (let ((both (org-babel-get-colnames (cdr var))))
1638 (setq cnames (cons (cons (car var) (cdr both))
1639 cnames))
1640 (setq var (cons (car var) (car both)))))
1641 (when (and rownames (not (equal rownames "no")))
1642 (let ((both (org-babel-get-rownames (cdr var))))
1643 (setq rnames (cons (cons (car var) (cdr both))
1644 rnames))
1645 (setq var (cons (car var) (car both)))))
1646 (when (and hlines (not (equal hlines "yes")))
1647 (setq var (cons (car var) (org-babel-del-hlines (cdr var))))))
1648 var)
1649 vars)
1650 (reverse cnames) (reverse rnames))))
1652 (defun org-babel-reassemble-table (table colnames rownames)
1653 "Add column and row names to a table.
1654 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1655 to the table for reinsertion to org-mode."
1656 (if (listp table)
1657 (let ((table (if (and rownames (= (length table) (length rownames)))
1658 (org-babel-put-rownames table rownames) table)))
1659 (if (and colnames (listp (car table)) (= (length (car table))
1660 (length colnames)))
1661 (org-babel-put-colnames table colnames) 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 (let ((head (org-babel-where-is-src-block-head)))
1699 (if head (goto-char head) (error "Not currently in a code block"))))
1701 ;;;###autoload
1702 (defun org-babel-goto-named-src-block (name)
1703 "Go to a named source-code block."
1704 (interactive
1705 (let ((completion-ignore-case t)
1706 (case-fold-search t)
1707 (under-point (thing-at-point 'line)))
1708 (list (org-icompleting-read
1709 "source-block name: " (org-babel-src-block-names) nil t
1710 (cond
1711 ;; noweb
1712 ((string-match (org-babel-noweb-wrap) under-point)
1713 (let ((block-name (match-string 1 under-point)))
1714 (string-match "[^(]*" block-name)
1715 (match-string 0 block-name)))
1716 ;; #+call:
1717 ((string-match org-babel-lob-one-liner-regexp under-point)
1718 (let ((source-info (car (org-babel-lob-get-info))))
1719 (if (string-match "^\\([^\\[]+?\\)\\(\\[.*\\]\\)?(" source-info)
1720 (let ((source-name (match-string 1 source-info)))
1721 source-name))))
1722 ;; #+results:
1723 ((string-match (concat "#\\+" org-babel-results-keyword
1724 "\\:\s+\\([^\\(]*\\)") under-point)
1725 (match-string 1 under-point))
1726 ;; symbol-at-point
1727 ((and (thing-at-point 'symbol))
1728 (org-babel-find-named-block (thing-at-point 'symbol))
1729 (thing-at-point 'symbol))
1730 (""))))))
1731 (let ((point (org-babel-find-named-block name)))
1732 (if point
1733 ;; taken from `org-open-at-point'
1734 (progn (org-mark-ring-push) (goto-char point) (org-show-context))
1735 (message "source-code block '%s' not found in this buffer" name))))
1737 (defun org-babel-find-named-block (name)
1738 "Find a named source-code block.
1739 Return the location of the source block identified by source
1740 NAME, or nil if no such block exists. Set match data according to
1741 org-babel-named-src-block-regexp."
1742 (save-excursion
1743 (let ((case-fold-search t)
1744 (regexp (org-babel-named-src-block-regexp-for-name name)) msg)
1745 (goto-char (point-min))
1746 (when (or (re-search-forward regexp nil t)
1747 (re-search-backward regexp nil t))
1748 (match-beginning 0)))))
1750 (defun org-babel-src-block-names (&optional file)
1751 "Returns the names of source blocks in FILE or the current buffer."
1752 (save-excursion
1753 (when file (find-file file)) (goto-char (point-min))
1754 (let ((case-fold-search t) names)
1755 (while (re-search-forward org-babel-src-name-w-name-regexp nil t)
1756 (setq names (cons (match-string 3) names)))
1757 names)))
1759 ;;;###autoload
1760 (defun org-babel-goto-named-result (name)
1761 "Go to a named result."
1762 (interactive
1763 (let ((completion-ignore-case t))
1764 (list (org-icompleting-read "source-block name: "
1765 (org-babel-result-names) nil t))))
1766 (let ((point (org-babel-find-named-result name)))
1767 (if point
1768 ;; taken from `org-open-at-point'
1769 (progn (goto-char point) (org-show-context))
1770 (message "result '%s' not found in this buffer" name))))
1772 (defun org-babel-find-named-result (name &optional point)
1773 "Find a named result.
1774 Return the location of the result named NAME in the current
1775 buffer or nil if no such result exists."
1776 (save-excursion
1777 (let ((case-fold-search t))
1778 (goto-char (or point (point-min)))
1779 (catch 'is-a-code-block
1780 (when (re-search-forward
1781 (concat org-babel-result-regexp
1782 "[ \t]" (regexp-quote name) "[ \t]*[\n\f\v\r]") nil t)
1783 (when (and (string= "name" (downcase (match-string 1)))
1784 (or (beginning-of-line 1)
1785 (looking-at org-babel-src-block-regexp)
1786 (looking-at org-babel-multi-line-header-regexp)
1787 (looking-at org-babel-lob-one-liner-regexp)))
1788 (throw 'is-a-code-block (org-babel-find-named-result name (point))))
1789 (beginning-of-line 0) (point))))))
1791 (defun org-babel-result-names (&optional file)
1792 "Returns the names of results in FILE or the current buffer."
1793 (save-excursion
1794 (when file (find-file file)) (goto-char (point-min))
1795 (let ((case-fold-search t) names)
1796 (while (re-search-forward org-babel-result-w-name-regexp nil t)
1797 (setq names (cons (match-string 4) names)))
1798 names)))
1800 ;;;###autoload
1801 (defun org-babel-next-src-block (&optional arg)
1802 "Jump to the next source block.
1803 With optional prefix argument ARG, jump forward ARG many source blocks."
1804 (interactive "p")
1805 (org-next-block arg nil org-babel-src-block-regexp))
1807 ;;;###autoload
1808 (defun org-babel-previous-src-block (&optional arg)
1809 "Jump to the previous source block.
1810 With optional prefix argument ARG, jump backward ARG many source blocks."
1811 (interactive "p")
1812 (org-previous-block arg org-babel-src-block-regexp))
1814 (defvar org-babel-load-languages)
1816 ;;;###autoload
1817 (defun org-babel-mark-block ()
1818 "Mark current src block."
1819 (interactive)
1820 (let ((head (org-babel-where-is-src-block-head)))
1821 (when head
1822 (save-excursion
1823 (goto-char head)
1824 (looking-at org-babel-src-block-regexp))
1825 (push-mark (match-end 5) nil t)
1826 (goto-char (match-beginning 5)))))
1828 (defun org-babel-demarcate-block (&optional arg)
1829 "Wrap or split the code in the region or on the point.
1830 When called from inside of a code block the current block is
1831 split. When called from outside of a code block a new code block
1832 is created. In both cases if the region is demarcated and if the
1833 region is not active then the point is demarcated."
1834 (interactive "P")
1835 (let ((info (org-babel-get-src-block-info 'light))
1836 (headers (progn (org-babel-where-is-src-block-head)
1837 (match-string 4)))
1838 (stars (concat (make-string (or (org-current-level) 1) ?*) " ")))
1839 (if info
1840 (mapc
1841 (lambda (place)
1842 (save-excursion
1843 (goto-char place)
1844 (let ((lang (nth 0 info))
1845 (indent (make-string (nth 5 info) ? )))
1846 (when (string-match "^[[:space:]]*$"
1847 (buffer-substring (point-at-bol)
1848 (point-at-eol)))
1849 (delete-region (point-at-bol) (point-at-eol)))
1850 (insert (concat
1851 (if (looking-at "^") "" "\n")
1852 indent "#+end_src\n"
1853 (if arg stars indent) "\n"
1854 indent "#+begin_src " lang
1855 (if (> (length headers) 1)
1856 (concat " " headers) headers)
1857 (if (looking-at "[\n\r]")
1859 (concat "\n" (make-string (current-column) ? )))))))
1860 (move-end-of-line 2))
1861 (sort (if (org-region-active-p) (list (mark) (point)) (list (point))) #'>))
1862 (let ((start (point))
1863 (lang (org-icompleting-read
1864 "Lang: "
1865 (mapcar #'symbol-name
1866 (delete-dups
1867 (append (mapcar #'car org-babel-load-languages)
1868 (mapcar (lambda (el) (intern (car el)))
1869 org-src-lang-modes))))))
1870 (body (delete-and-extract-region
1871 (if (org-region-active-p) (mark) (point)) (point))))
1872 (insert (concat (if (looking-at "^") "" "\n")
1873 (if arg (concat stars "\n") "")
1874 "#+begin_src " lang "\n"
1875 body
1876 (if (or (= (length body) 0)
1877 (string-match "[\r\n]$" body)) "" "\n")
1878 "#+end_src\n"))
1879 (goto-char start) (move-end-of-line 1)))))
1881 (defvar org-babel-lob-one-liner-regexp)
1882 (defun org-babel-where-is-src-block-result (&optional insert info hash indent)
1883 "Find where the current source block results begin.
1884 Return the point at the beginning of the result of the current
1885 source block. Specifically at the beginning of the results line.
1886 If no result exists for this block then create a results line
1887 following the source block."
1888 (save-excursion
1889 (let* ((case-fold-search t)
1890 (on-lob-line (save-excursion
1891 (beginning-of-line 1)
1892 (looking-at org-babel-lob-one-liner-regexp)))
1893 (inlinep (when (org-babel-get-inline-src-block-matches)
1894 (match-end 0)))
1895 (name (nth 4 (or info (org-babel-get-src-block-info 'light))))
1896 (head (unless on-lob-line (org-babel-where-is-src-block-head)))
1897 found beg end)
1898 (when head (goto-char head))
1899 (org-with-wide-buffer
1900 (setq
1901 found ;; was there a result (before we potentially insert one)
1903 inlinep
1904 (and
1905 ;; named results:
1906 ;; - return t if it is found, else return nil
1907 ;; - if it does not need to be rebuilt, then don't set end
1908 ;; - if it does need to be rebuilt then do set end
1909 name (setq beg (org-babel-find-named-result name))
1910 (prog1 beg
1911 (when (and hash (not (string= hash (match-string 5))))
1912 (goto-char beg) (setq end beg) ;; beginning of result
1913 (forward-line 1)
1914 (delete-region end (org-babel-result-end)) nil)))
1915 (and
1916 ;; unnamed results:
1917 ;; - return t if it is found, else return nil
1918 ;; - if it is found, and the hash doesn't match, delete and set end
1919 (or on-lob-line (re-search-forward "^[ \t]*#\\+end_src" nil t))
1920 (progn (end-of-line 1)
1921 (if (eobp) (insert "\n") (forward-char 1))
1922 (setq end (point))
1923 (or (and
1924 (not name)
1925 (progn ;; unnamed results line already exists
1926 (catch 'non-comment
1927 (while (re-search-forward "[^ \f\t\n\r\v]" nil t)
1928 (beginning-of-line 1)
1929 (cond
1930 ((looking-at (concat org-babel-result-regexp "\n"))
1931 (throw 'non-comment t))
1932 ((and (looking-at "^[ \t]*#")
1933 (not (looking-at
1934 org-babel-lob-one-liner-regexp)))
1935 (end-of-line 1))
1936 (t (throw 'non-comment nil))))))
1937 (let ((this-hash (match-string 5)))
1938 (prog1 (point)
1939 ;; must remove and rebuild if hash!=old-hash
1940 (if (and hash (not (string= hash this-hash)))
1941 (prog1 nil
1942 (forward-line 1)
1943 (delete-region
1944 end (org-babel-result-end)))
1945 (setq end nil)))))))))))
1946 (if (not (and insert end)) found
1947 (goto-char end)
1948 (unless beg
1949 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1950 (insert (concat
1951 (when (wholenump indent) (make-string indent ? ))
1952 "#+" org-babel-results-keyword
1953 (when hash
1954 (if org-babel-hash-show-time
1955 (concat
1956 "["(format-time-string "<%Y-%m-%d %H:%M:%S>")" "hash"]")
1957 (concat "["hash"]")))
1959 (when name (concat " " name)) "\n"))
1960 (unless beg (insert "\n") (backward-char))
1961 (beginning-of-line 0)
1962 (if hash (org-babel-hide-hash))
1963 (point)))))
1965 (defvar org-block-regexp)
1966 (defun org-babel-read-result ()
1967 "Read the result at `point' into emacs-lisp."
1968 (let ((case-fold-search t) result-string)
1969 (cond
1970 ((org-at-table-p) (org-babel-read-table))
1971 ((org-at-item-p) (org-babel-read-list))
1972 ((looking-at org-bracket-link-regexp) (org-babel-read-link))
1973 ((looking-at org-block-regexp) (org-babel-trim (match-string 4)))
1974 ((or (looking-at "^[ \t]*: ") (looking-at "^[ \t]*:$"))
1975 (setq result-string
1976 (org-babel-trim
1977 (mapconcat (lambda (line)
1978 (or (and (> (length line) 1)
1979 (string-match "^[ \t]*: ?\\(.+\\)" line)
1980 (match-string 1 line))
1981 ""))
1982 (split-string
1983 (buffer-substring
1984 (point) (org-babel-result-end)) "[\r\n]+")
1985 "\n")))
1986 (or (org-babel-number-p result-string) result-string))
1987 ((looking-at org-babel-result-regexp)
1988 (save-excursion (forward-line 1) (org-babel-read-result))))))
1990 (defun org-babel-read-table ()
1991 "Read the table at `point' into emacs-lisp."
1992 (mapcar (lambda (row)
1993 (if (and (symbolp row) (equal row 'hline)) row
1994 (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval)) row)))
1995 (org-table-to-lisp)))
1997 (defun org-babel-read-list ()
1998 "Read the list at `point' into emacs-lisp."
1999 (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval))
2000 (mapcar #'cadr (cdr (org-list-parse-list)))))
2002 (defvar org-link-types-re)
2003 (defun org-babel-read-link ()
2004 "Read the link at `point' into emacs-lisp.
2005 If the path of the link is a file path it is expanded using
2006 `expand-file-name'."
2007 (let* ((case-fold-search t)
2008 (raw (and (looking-at org-bracket-link-regexp)
2009 (org-no-properties (match-string 1))))
2010 (type (and (string-match org-link-types-re raw)
2011 (match-string 1 raw))))
2012 (cond
2013 ((not type) (expand-file-name raw))
2014 ((string= type "file")
2015 (and (string-match "file\\(.*\\):\\(.+\\)" raw)
2016 (expand-file-name (match-string 2 raw))))
2017 (t raw))))
2019 (defun org-babel-format-result (result &optional sep)
2020 "Format RESULT for writing to file."
2021 (let ((echo-res (lambda (r) (if (stringp r) r (format "%S" r)))))
2022 (if (listp result)
2023 ;; table result
2024 (orgtbl-to-generic
2025 result (list :sep (or sep "\t") :fmt echo-res))
2026 ;; scalar result
2027 (funcall echo-res result))))
2029 (defun org-babel-insert-result
2030 (result &optional result-params info hash indent lang)
2031 "Insert RESULT into the current buffer.
2032 By default RESULT is inserted after the end of the
2033 current source block. With optional argument RESULT-PARAMS
2034 controls insertion of results in the org-mode file.
2035 RESULT-PARAMS can take the following values:
2037 replace - (default option) insert results after the source block
2038 replacing any previously inserted results
2040 silent -- no results are inserted into the Org-mode buffer but
2041 the results are echoed to the minibuffer and are
2042 ingested by Emacs (a potentially time consuming
2043 process)
2045 file ---- the results are interpreted as a file path, and are
2046 inserted into the buffer using the Org-mode file syntax
2048 list ---- the results are interpreted as an Org-mode list.
2050 raw ----- results are added directly to the Org-mode file. This
2051 is a good option if you code block will output org-mode
2052 formatted text.
2054 drawer -- results are added directly to the Org-mode file as with
2055 \"raw\", but are wrapped in a RESULTS drawer, allowing
2056 them to later be replaced or removed automatically.
2058 org ----- results are added inside of a \"#+BEGIN_SRC org\" block.
2059 They are not comma-escaped when inserted, but Org syntax
2060 here will be discarded when exporting the file.
2062 html ---- results are added inside of a #+BEGIN_HTML block. This
2063 is a good option if you code block will output html
2064 formatted text.
2066 latex --- results are added inside of a #+BEGIN_LATEX block.
2067 This is a good option if you code block will output
2068 latex formatted text.
2070 code ---- the results are extracted in the syntax of the source
2071 code of the language being evaluated and are added
2072 inside of a #+BEGIN_SRC block with the source-code
2073 language set appropriately. Note this relies on the
2074 optional LANG argument."
2075 (if (stringp result)
2076 (progn
2077 (setq result (org-no-properties result))
2078 (when (member "file" result-params)
2079 (setq result (org-babel-result-to-file
2080 result (when (assoc :file-desc (nth 2 info))
2081 (or (cdr (assoc :file-desc (nth 2 info)))
2082 result))))))
2083 (unless (listp result) (setq result (format "%S" result))))
2084 (if (and result-params (member "silent" result-params))
2085 (progn
2086 (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
2087 result)
2088 (save-excursion
2089 (let* ((inlinep
2090 (save-excursion
2091 (when (or (org-babel-get-inline-src-block-matches)
2092 (org-babel-get-lob-one-liner-matches))
2093 (goto-char (match-end 0))
2094 (insert (if (listp result) "\n" " "))
2095 (point))))
2096 (existing-result (unless inlinep
2097 (org-babel-where-is-src-block-result
2098 t info hash indent)))
2099 (results-switches
2100 (cdr (assoc :results_switches (nth 2 info))))
2101 (visible-beg (copy-marker (point-min)))
2102 (visible-end (copy-marker (point-max)))
2103 ;; When results exist outside of the current visible
2104 ;; region of the buffer, be sure to widen buffer to
2105 ;; update them.
2106 (outside-scope-p (and existing-result
2107 (or (> visible-beg existing-result)
2108 (<= visible-end existing-result))))
2109 beg end)
2110 (when (and (stringp result) ; ensure results end in a newline
2111 (not inlinep)
2112 (> (length result) 0)
2113 (not (or (string-equal (substring result -1) "\n")
2114 (string-equal (substring result -1) "\r"))))
2115 (setq result (concat result "\n")))
2116 (unwind-protect
2117 (progn
2118 (when outside-scope-p (widen))
2119 (if (not existing-result)
2120 (setq beg (or inlinep (point)))
2121 (goto-char existing-result)
2122 (save-excursion
2123 (re-search-forward "#" nil t)
2124 (setq indent (- (current-column) 1)))
2125 (forward-line 1)
2126 (setq beg (point))
2127 (cond
2128 ((member "replace" result-params)
2129 (delete-region (point) (org-babel-result-end)))
2130 ((member "append" result-params)
2131 (goto-char (org-babel-result-end)) (setq beg (point-marker)))
2132 ((member "prepend" result-params)))) ; already there
2133 (setq results-switches
2134 (if results-switches (concat " " results-switches) ""))
2135 (let ((wrap (lambda (start finish &optional no-escape)
2136 (goto-char end) (insert (concat finish "\n"))
2137 (goto-char beg) (insert (concat start "\n"))
2138 (unless no-escape
2139 (org-escape-code-in-region (min (point) end) end))
2140 (goto-char end) (goto-char (point-at-eol))
2141 (setq end (point-marker))))
2142 (proper-list-p (lambda (it) (and (listp it) (null (cdr (last it)))))))
2143 ;; insert results based on type
2144 (cond
2145 ;; do nothing for an empty result
2146 ((null result))
2147 ;; insert a list if preferred
2148 ((member "list" result-params)
2149 (insert
2150 (org-babel-trim
2151 (org-list-to-generic
2152 (cons 'unordered
2153 (mapcar
2154 (lambda (el) (list nil (if (stringp el) el (format "%S" el))))
2155 (if (listp result) result (split-string result "\n" t))))
2156 '(:splicep nil :istart "- " :iend "\n")))
2157 "\n"))
2158 ;; assume the result is a table if it's not a string
2159 ((funcall proper-list-p result)
2160 (goto-char beg)
2161 (insert (concat (orgtbl-to-orgtbl
2162 (if (or (eq 'hline (car result))
2163 (and (listp (car result))
2164 (listp (cdr (car result)))))
2165 result (list result))
2166 '(:fmt (lambda (cell) (format "%s" cell)))) "\n"))
2167 (goto-char beg) (when (org-at-table-p) (org-table-align)))
2168 ((and (listp result) (not (funcall proper-list-p result)))
2169 (insert (format "%s\n" result)))
2170 ((member "file" result-params)
2171 (when inlinep (goto-char inlinep))
2172 (insert result))
2173 (t (goto-char beg) (insert result)))
2174 (when (funcall proper-list-p result) (goto-char (org-table-end)))
2175 (setq end (point-marker))
2176 ;; possibly wrap result
2177 (cond
2178 ((assoc :wrap (nth 2 info))
2179 (let ((name (or (cdr (assoc :wrap (nth 2 info))) "RESULTS")))
2180 (funcall wrap (concat "#+BEGIN_" name)
2181 (concat "#+END_" (car (org-split-string name))))))
2182 ((member "html" result-params)
2183 (funcall wrap "#+BEGIN_HTML" "#+END_HTML"))
2184 ((member "latex" result-params)
2185 (funcall wrap "#+BEGIN_LaTeX" "#+END_LaTeX"))
2186 ((member "org" result-params)
2187 (goto-char beg) (if (org-at-table-p) (org-cycle))
2188 (funcall wrap "#+BEGIN_SRC org" "#+END_SRC"))
2189 ((member "code" result-params)
2190 (funcall wrap (format "#+BEGIN_SRC %s%s" (or lang "none") results-switches)
2191 "#+END_SRC"))
2192 ((member "raw" result-params)
2193 (goto-char beg) (if (org-at-table-p) (org-cycle)))
2194 ((or (member "drawer" result-params)
2195 ;; Stay backward compatible with <7.9.2
2196 (member "wrap" result-params))
2197 (goto-char beg) (if (org-at-table-p) (org-cycle))
2198 (funcall wrap ":RESULTS:" ":END:" 'no-escape))
2199 ((and (not (funcall proper-list-p result))
2200 (not (member "file" result-params)))
2201 (org-babel-examplize-region beg end results-switches)
2202 (setq end (point)))))
2203 ;; possibly indent the results to match the #+results line
2204 (when (and (not inlinep) (numberp indent) indent (> indent 0)
2205 ;; in this case `table-align' does the work for us
2206 (not (and (listp result)
2207 (member "append" result-params))))
2208 (indent-rigidly beg end indent))
2209 (if (null result)
2210 (if (member "value" result-params)
2211 (message "Code block returned no value.")
2212 (message "Code block produced no output."))
2213 (message "Code block evaluation complete.")))
2214 (when outside-scope-p (narrow-to-region visible-beg visible-end))
2215 (set-marker visible-beg nil)
2216 (set-marker visible-end nil))))))
2218 (defun org-babel-remove-result (&optional info keep-keyword)
2219 "Remove the result of the current source block."
2220 (interactive)
2221 (let ((location (org-babel-where-is-src-block-result nil info)))
2222 (when location
2223 (save-excursion
2224 (goto-char location)
2225 (when (looking-at (concat org-babel-result-regexp ".*$"))
2226 (delete-region
2227 (if keep-keyword (1+ (match-end 0)) (1- (match-beginning 0)))
2228 (progn (forward-line 1) (org-babel-result-end))))))))
2230 (defun org-babel-result-end ()
2231 "Return the point at the end of the current set of results."
2232 (save-excursion
2233 (cond
2234 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
2235 ((org-at-item-p) (let* ((struct (org-list-struct))
2236 (prvs (org-list-prevs-alist struct)))
2237 (org-list-get-list-end (point-at-bol) struct prvs)))
2238 ((let ((case-fold-search t)) (looking-at "^\\([ \t]*\\):results:"))
2239 (progn (re-search-forward (concat "^" (match-string 1) ":END:"))
2240 (forward-char 1) (point)))
2242 (let ((case-fold-search t))
2243 (if (looking-at (concat "[ \t]*#\\+begin_\\([^ \t\n\r]+\\)"))
2244 (progn (re-search-forward (concat "[ \t]*#\\+end_" (match-string 1))
2245 nil t)
2246 (forward-char 1))
2247 (while (looking-at "[ \t]*\\(: \\|:$\\|\\[\\[\\)")
2248 (forward-line 1))))
2249 (point)))))
2251 (defun org-babel-result-to-file (result &optional description)
2252 "Convert RESULT into an `org-mode' link with optional DESCRIPTION.
2253 If the `default-directory' is different from the containing
2254 file's directory then expand relative links."
2255 (when (stringp result)
2256 (format "[[file:%s]%s]"
2257 (if (and default-directory
2258 buffer-file-name
2259 (not (string= (expand-file-name default-directory)
2260 (expand-file-name
2261 (file-name-directory buffer-file-name)))))
2262 (expand-file-name result default-directory)
2263 result)
2264 (if description (concat "[" description "]") ""))))
2266 (defvar org-babel-capitalize-examplize-region-markers nil
2267 "Make true to capitalize begin/end example markers inserted by code blocks.")
2269 (defun org-babel-examplize-region (beg end &optional results-switches)
2270 "Comment out region using the inline '==' or ': ' org example quote."
2271 (interactive "*r")
2272 (let ((chars-between (lambda (b e)
2273 (not (string-match "^[\\s]*$" (buffer-substring b e)))))
2274 (maybe-cap (lambda (str) (if org-babel-capitalize-examplize-region-markers
2275 (upcase str) str))))
2276 (if (or (funcall chars-between (save-excursion (goto-char beg) (point-at-bol)) beg)
2277 (funcall chars-between end (save-excursion (goto-char end) (point-at-eol))))
2278 (save-excursion
2279 (goto-char beg)
2280 (insert (format org-babel-inline-result-wrap
2281 (prog1 (buffer-substring beg end)
2282 (delete-region beg end)))))
2283 (let ((size (count-lines beg end)))
2284 (save-excursion
2285 (cond ((= size 0)) ; do nothing for an empty result
2286 ((< size org-babel-min-lines-for-block-output)
2287 (goto-char beg)
2288 (dotimes (n size)
2289 (beginning-of-line 1) (insert ": ") (forward-line 1)))
2291 (goto-char beg)
2292 (insert (if results-switches
2293 (format "%s%s\n"
2294 (funcall maybe-cap "#+begin_example")
2295 results-switches)
2296 (funcall maybe-cap "#+begin_example\n")))
2297 (if (markerp end) (goto-char end) (forward-char (- end beg)))
2298 (insert (funcall maybe-cap "#+end_example\n")))))))))
2300 (defun org-babel-update-block-body (new-body)
2301 "Update the body of the current code block to NEW-BODY."
2302 (if (not (org-babel-where-is-src-block-head))
2303 (error "Not in a source block")
2304 (save-match-data
2305 (replace-match (concat (org-babel-trim new-body) "\n") nil t nil 5))
2306 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
2308 (defun org-babel-merge-params (&rest plists)
2309 "Combine all parameter association lists in PLISTS.
2310 Later elements of PLISTS override the values of previous elements.
2311 This takes into account some special considerations for certain
2312 parameters when merging lists."
2313 (let* ((results-exclusive-groups
2314 (mapcar (lambda (group) (mapcar #'symbol-name group))
2315 (cdr (assoc 'results org-babel-common-header-args-w-values))))
2316 (exports-exclusive-groups
2317 (mapcar (lambda (group) (mapcar #'symbol-name group))
2318 (cdr (assoc 'exports org-babel-common-header-args-w-values))))
2319 (variable-index 0)
2320 (e-merge (lambda (exclusive-groups &rest result-params)
2321 ;; maintain exclusivity of mutually exclusive parameters
2322 (let (output)
2323 (mapc (lambda (new-params)
2324 (mapc (lambda (new-param)
2325 (mapc (lambda (exclusive-group)
2326 (when (member new-param exclusive-group)
2327 (mapcar (lambda (excluded-param)
2328 (setq output
2329 (delete
2330 excluded-param
2331 output)))
2332 exclusive-group)))
2333 exclusive-groups)
2334 (setq output (org-uniquify
2335 (cons new-param output))))
2336 new-params))
2337 result-params)
2338 output)))
2339 params results exports tangle noweb cache vars shebang comments padline
2340 clearnames)
2342 (mapc
2343 (lambda (plist)
2344 (mapc
2345 (lambda (pair)
2346 (case (car pair)
2347 (:var
2348 (let ((name (if (listp (cdr pair))
2349 (cadr pair)
2350 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
2351 (cdr pair))
2352 (intern (match-string 1 (cdr pair)))))))
2353 (if name
2354 (setq vars
2355 (append
2356 (if (member name (mapcar #'car vars))
2357 (progn
2358 (push name clearnames)
2359 (delq nil
2360 (mapcar
2361 (lambda (p)
2362 (unless (equal (car p) name) p))
2363 vars)))
2364 vars)
2365 (list (cons name pair))))
2366 ;; if no name is given and we already have named variables
2367 ;; then assign to named variables in order
2368 (if (and vars (nth variable-index vars))
2369 (let ((name (car (nth variable-index vars))))
2370 (push name clearnames) ; clear out colnames
2371 ; and rownames
2372 ; for replace vars
2373 (prog1 (setf (cddr (nth variable-index vars))
2374 (concat (symbol-name name) "=" (cdr pair)))
2375 (incf variable-index)))
2376 (error "Variable \"%s\" must be assigned a default value"
2377 (cdr pair))))))
2378 (:results
2379 (setq results (funcall e-merge results-exclusive-groups
2380 results
2381 (split-string
2382 (let ((r (cdr pair)))
2383 (if (stringp r) r (eval r)))))))
2384 (:file
2385 (when (cdr pair)
2386 (setq results (funcall e-merge results-exclusive-groups
2387 results '("file")))
2388 (unless (or (member "both" exports)
2389 (member "none" exports)
2390 (member "code" exports))
2391 (setq exports (funcall e-merge exports-exclusive-groups
2392 exports '("results"))))
2393 (setq params (cons pair (assq-delete-all (car pair) params)))))
2394 (:exports
2395 (setq exports (funcall e-merge exports-exclusive-groups
2396 exports (split-string (cdr pair)))))
2397 (:tangle ;; take the latest -- always overwrite
2398 (setq tangle (or (list (cdr pair)) tangle)))
2399 (:noweb
2400 (setq noweb (funcall e-merge
2401 '(("yes" "no" "tangle" "no-export"
2402 "strip-export" "eval"))
2403 noweb
2404 (split-string (or (cdr pair) "")))))
2405 (:cache
2406 (setq cache (funcall e-merge '(("yes" "no")) cache
2407 (split-string (or (cdr pair) "")))))
2408 (:padline
2409 (setq padline (funcall e-merge '(("yes" "no")) padline
2410 (split-string (or (cdr pair) "")))))
2411 (:shebang ;; take the latest -- always overwrite
2412 (setq shebang (or (list (cdr pair)) shebang)))
2413 (:comments
2414 (setq comments (funcall e-merge '(("yes" "no")) comments
2415 (split-string (or (cdr pair) "")))))
2416 (t ;; replace: this covers e.g. :session
2417 (setq params (cons pair (assq-delete-all (car pair) params))))))
2418 plist))
2419 plists)
2420 (setq vars (reverse vars))
2421 (while vars (setq params (cons (cons :var (cddr (pop vars))) params)))
2422 ;; clear out col-names and row-names for replaced variables
2423 (mapc
2424 (lambda (name)
2425 (mapc
2426 (lambda (param)
2427 (when (assoc param params)
2428 (setf (cdr (assoc param params))
2429 (org-remove-if (lambda (pair) (equal (car pair) name))
2430 (cdr (assoc param params))))
2431 (setf params (org-remove-if (lambda (pair) (and (equal (car pair) param)
2432 (null (cdr pair))))
2433 params))))
2434 (list :colname-names :rowname-names)))
2435 clearnames)
2436 (mapc
2437 (lambda (hd)
2438 (let ((key (intern (concat ":" (symbol-name hd))))
2439 (val (eval hd)))
2440 (setf params (cons (cons key (mapconcat 'identity val " ")) params))))
2441 '(results exports tangle noweb padline cache shebang comments))
2442 params))
2444 (defvar org-babel-use-quick-and-dirty-noweb-expansion nil
2445 "Set to true to use regular expressions to expand noweb references.
2446 This results in much faster noweb reference expansion but does
2447 not properly allow code blocks to inherit the \":noweb-ref\"
2448 header argument from buffer or subtree wide properties.")
2450 (defun org-babel-noweb-p (params context)
2451 "Check if PARAMS require expansion in CONTEXT.
2452 CONTEXT may be one of :tangle, :export or :eval."
2453 (let* (intersect
2454 (intersect (lambda (as bs)
2455 (when as
2456 (if (member (car as) bs)
2457 (car as)
2458 (funcall intersect (cdr as) bs))))))
2459 (funcall intersect (case context
2460 (:tangle '("yes" "tangle" "no-export" "strip-export"))
2461 (:eval '("yes" "no-export" "strip-export" "eval"))
2462 (:export '("yes")))
2463 (split-string (or (cdr (assoc :noweb params)) "")))))
2465 (defun org-babel-expand-noweb-references (&optional info parent-buffer)
2466 "Expand Noweb references in the body of the current source code block.
2468 For example the following reference would be replaced with the
2469 body of the source-code block named 'example-block'.
2471 <<example-block>>
2473 Note that any text preceding the <<foo>> construct on a line will
2474 be interposed between the lines of the replacement text. So for
2475 example if <<foo>> is placed behind a comment, then the entire
2476 replacement text will also be commented.
2478 This function must be called from inside of the buffer containing
2479 the source-code block which holds BODY.
2481 In addition the following syntax can be used to insert the
2482 results of evaluating the source-code block named 'example-block'.
2484 <<example-block()>>
2486 Any optional arguments can be passed to example-block by placing
2487 the arguments inside the parenthesis following the convention
2488 defined by `org-babel-lob'. For example
2490 <<example-block(a=9)>>
2492 would set the value of argument \"a\" equal to \"9\". Note that
2493 these arguments are not evaluated in the current source-code
2494 block but are passed literally to the \"example-block\"."
2495 (let* ((parent-buffer (or parent-buffer (current-buffer)))
2496 (info (or info (org-babel-get-src-block-info 'light)))
2497 (lang (nth 0 info))
2498 (body (nth 1 info))
2499 (ob-nww-start org-babel-noweb-wrap-start)
2500 (ob-nww-end org-babel-noweb-wrap-end)
2501 (comment (string= "noweb" (cdr (assoc :comments (nth 2 info)))))
2502 (rx-prefix (concat "\\(" org-babel-src-name-regexp "\\|"
2503 ":noweb-ref[ \t]+" "\\)"))
2504 (new-body "")
2505 (nb-add (lambda (text) (setq new-body (concat new-body text))))
2506 (c-wrap (lambda (text)
2507 (with-temp-buffer
2508 (funcall (intern (concat lang "-mode")))
2509 (comment-region (point) (progn (insert text) (point)))
2510 (org-babel-trim (buffer-string)))))
2511 index source-name evaluate prefix)
2512 (with-temp-buffer
2513 (org-set-local 'org-babel-noweb-wrap-start ob-nww-start)
2514 (org-set-local 'org-babel-noweb-wrap-end ob-nww-end)
2515 (insert body) (goto-char (point-min))
2516 (setq index (point))
2517 (while (and (re-search-forward (org-babel-noweb-wrap) nil t))
2518 (save-match-data (setf source-name (match-string 1)))
2519 (save-match-data (setq evaluate (string-match "\(.*\)" source-name)))
2520 (save-match-data
2521 (setq prefix
2522 (buffer-substring (match-beginning 0)
2523 (save-excursion
2524 (beginning-of-line 1) (point)))))
2525 ;; add interval to new-body (removing noweb reference)
2526 (goto-char (match-beginning 0))
2527 (funcall nb-add (buffer-substring index (point)))
2528 (goto-char (match-end 0))
2529 (setq index (point))
2530 (funcall
2531 nb-add
2532 (with-current-buffer parent-buffer
2533 (save-restriction
2534 (widen)
2535 (mapconcat ;; Interpose PREFIX between every line.
2536 #'identity
2537 (split-string
2538 (if evaluate
2539 (let ((raw (org-babel-ref-resolve source-name)))
2540 (if (stringp raw) raw (format "%S" raw)))
2542 ;; Retrieve from the library of babel.
2543 (nth 2 (assoc (intern source-name)
2544 org-babel-library-of-babel))
2545 ;; Return the contents of headlines literally.
2546 (save-excursion
2547 (when (org-babel-ref-goto-headline-id source-name)
2548 (org-babel-ref-headline-body)))
2549 ;; Find the expansion of reference in this buffer.
2550 (let ((rx (concat rx-prefix source-name "[ \t\n]"))
2551 expansion)
2552 (save-excursion
2553 (goto-char (point-min))
2554 (if org-babel-use-quick-and-dirty-noweb-expansion
2555 (while (re-search-forward rx nil t)
2556 (let* ((i (org-babel-get-src-block-info 'light))
2557 (body (org-babel-expand-noweb-references i))
2558 (sep (or (cdr (assoc :noweb-sep (nth 2 i)))
2559 "\n"))
2560 (full (if comment
2561 (let ((cs (org-babel-tangle-comment-links i)))
2562 (concat (funcall c-wrap (car cs)) "\n"
2563 body "\n"
2564 (funcall c-wrap (cadr cs))))
2565 body)))
2566 (setq expansion (cons sep (cons full expansion)))))
2567 (org-babel-map-src-blocks nil
2568 (let ((i (org-babel-get-src-block-info 'light)))
2569 (when (equal (or (cdr (assoc :noweb-ref (nth 2 i)))
2570 (nth 4 i))
2571 source-name)
2572 (let* ((body (org-babel-expand-noweb-references i))
2573 (sep (or (cdr (assoc :noweb-sep (nth 2 i)))
2574 "\n"))
2575 (full (if comment
2576 (let ((cs (org-babel-tangle-comment-links i)))
2577 (concat (funcall c-wrap (car cs)) "\n"
2578 body "\n"
2579 (funcall c-wrap (cadr cs))))
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 ((escaped
2599 (if (or force
2600 (and (stringp str)
2601 (> (length str) 2)
2602 (or (and (string-equal "[" (substring str 0 1))
2603 (string-equal "]" (substring str -1)))
2604 (and (string-equal "{" (substring str 0 1))
2605 (string-equal "}" (substring str -1)))
2606 (and (string-equal "(" (substring str 0 1))
2607 (string-equal ")" (substring str -1))))))
2608 (org-babel-read
2609 (concat
2611 (let (in-single in-double out)
2612 (mapc
2613 (lambda (ch)
2614 (setq
2616 (case ch
2617 (91 (if (or in-double in-single) ; [
2618 (cons 91 out)
2619 (cons 40 out)))
2620 (93 (if (or in-double in-single) ; ]
2621 (cons 93 out)
2622 (cons 41 out)))
2623 (123 (if (or in-double in-single) ; {
2624 (cons 123 out)
2625 (cons 40 out)))
2626 (125 (if (or in-double in-single) ; }
2627 (cons 125 out)
2628 (cons 41 out)))
2629 (44 (if (or in-double in-single) ; ,
2630 (cons 44 out) (cons 32 out)))
2631 (39 (if in-double ; '
2632 (cons 39 out)
2633 (setq in-single (not in-single)) (cons 34 out)))
2634 (34 (if in-single ; "
2635 (append (list 34 32) out)
2636 (setq in-double (not in-double)) (cons 34 out)))
2637 (t (cons ch out)))))
2638 (string-to-list str))
2639 (apply #'string (reverse out)))))
2640 str)))
2641 (condition-case nil (org-babel-read escaped) (error escaped))))
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 (let ((f (org-babel-local-file-name (expand-file-name name))))
2748 (if no-quote-p f (shell-quote-argument f))))
2750 (defvar org-babel-temporary-directory)
2751 (unless (or noninteractive (boundp 'org-babel-temporary-directory))
2752 (defvar org-babel-temporary-directory
2753 (or (and (boundp 'org-babel-temporary-directory)
2754 (file-exists-p org-babel-temporary-directory)
2755 org-babel-temporary-directory)
2756 (make-temp-file "babel-" t))
2757 "Directory to hold temporary files created to execute code blocks.
2758 Used by `org-babel-temp-file'. This directory will be removed on
2759 Emacs shutdown."))
2761 (defcustom org-babel-remote-temporary-directory "/tmp/"
2762 "Directory to hold temporary files on remote hosts."
2763 :group 'org-babel
2764 :type 'string)
2766 (defmacro org-babel-result-cond (result-params scalar-form &rest table-forms)
2767 "Call the code to parse raw string results according to RESULT-PARAMS."
2768 (declare (indent 1)
2769 (debug (form form &rest form)))
2770 (org-with-gensyms (params)
2771 `(let ((,params ,result-params))
2772 (unless (member "none" ,params)
2773 (if (or (member "scalar" ,params)
2774 (member "verbatim" ,params)
2775 (member "html" ,params)
2776 (member "code" ,params)
2777 (member "pp" ,params)
2778 (and (or (member "output" ,params)
2779 (member "raw" ,params)
2780 (member "org" ,params)
2781 (member "drawer" ,params))
2782 (not (member "table" ,params))))
2783 ,scalar-form
2784 ,@table-forms)))))
2785 (def-edebug-spec org-babel-result-cond (form form body))
2787 (defun org-babel-temp-file (prefix &optional suffix)
2788 "Create a temporary file in the `org-babel-temporary-directory'.
2789 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2790 value of `temporary-file-directory' temporarily set to the value
2791 of `org-babel-temporary-directory'."
2792 (if (file-remote-p default-directory)
2793 (let ((prefix
2794 (concat (file-remote-p default-directory)
2795 (expand-file-name
2796 prefix org-babel-remote-temporary-directory))))
2797 (make-temp-file prefix nil suffix))
2798 (let ((temporary-file-directory
2799 (or (and (boundp 'org-babel-temporary-directory)
2800 (file-exists-p org-babel-temporary-directory)
2801 org-babel-temporary-directory)
2802 temporary-file-directory)))
2803 (make-temp-file prefix nil suffix))))
2805 (defun org-babel-remove-temporary-directory ()
2806 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2807 (when (and (boundp 'org-babel-temporary-directory)
2808 (file-exists-p org-babel-temporary-directory))
2809 ;; taken from `delete-directory' in files.el
2810 (condition-case nil
2811 (progn
2812 (mapc (lambda (file)
2813 ;; This test is equivalent to
2814 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2815 ;; but more efficient
2816 (if (eq t (car (file-attributes file)))
2817 (delete-directory file)
2818 (delete-file file)))
2819 ;; We do not want to delete "." and "..".
2820 (directory-files org-babel-temporary-directory 'full
2821 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2822 (delete-directory org-babel-temporary-directory))
2823 (error
2824 (message "Failed to remove temporary Org-babel directory %s"
2825 (if (boundp 'org-babel-temporary-directory)
2826 org-babel-temporary-directory
2827 "[directory not defined]"))))))
2829 (add-hook 'kill-emacs-hook 'org-babel-remove-temporary-directory)
2831 (defun org-babel-one-header-arg-safe-p (pair safe-list)
2832 "Determine if the PAIR is a safe babel header arg according to SAFE-LIST.
2834 For the format of SAFE-LIST, see `org-babel-safe-header-args'."
2835 (and (consp pair)
2836 (keywordp (car pair))
2837 (stringp (cdr pair))
2839 (memq (car pair) safe-list)
2840 (let ((entry (assq (car pair) safe-list)))
2841 (and entry
2842 (consp entry)
2843 (cond ((functionp (cdr entry))
2844 (funcall (cdr entry) (cdr pair)))
2845 ((listp (cdr entry))
2846 (member (cdr pair) (cdr entry)))
2847 (t nil)))))))
2849 (provide 'ob-core)
2851 ;; Local variables:
2852 ;; generated-autoload-file: "org-loaddefs.el"
2853 ;; End:
2855 ;;; ob-core.el ends here