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