don't change code block body during sha1 hashing
[org-mode.git] / lisp / ob-core.el
blobc8bda5eb42e2a23dd9b73c5f84190454de56fb53
1 ;;; ob-core.el --- working with code blocks in org-mode
3 ;; Copyright (C) 2009-2013 Free Software Foundation, Inc.
5 ;; Authors: Eric Schulte
6 ;; Dan Davison
7 ;; Keywords: literate programming, reproducible research
8 ;; Homepage: http://orgmode.org
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;; Code:
26 (eval-when-compile
27 (require 'cl))
28 (require 'ob-eval)
29 (require 'org-macs)
30 (require 'org-compat)
32 (defconst org-babel-exeext
33 (if (memq system-type '(windows-nt cygwin))
34 ".exe"
35 nil))
36 ;; dynamically scoped for tramp
37 (defvar org-babel-call-process-region-original nil)
38 (defvar org-src-lang-modes)
39 (defvar org-babel-library-of-babel)
40 (declare-function show-all "outline" ())
41 (declare-function org-remove-indentation "org" (code &optional n))
42 (declare-function org-reduce "org" (CL-FUNC CL-SEQ &rest CL-KEYS))
43 (declare-function org-mark-ring-push "org" (&optional pos buffer))
44 (declare-function tramp-compat-make-temp-file "tramp-compat"
45 (filename &optional dir-flag))
46 (declare-function tramp-dissect-file-name "tramp" (name &optional nodefault))
47 (declare-function tramp-file-name-user "tramp" (vec))
48 (declare-function tramp-file-name-host "tramp" (vec))
49 (declare-function with-parsed-tramp-file-name "tramp" (filename var &rest body))
50 (declare-function org-icompleting-read "org" (&rest args))
51 (declare-function org-edit-src-code "org-src"
52 (&optional context code edit-buffer-name quietp))
53 (declare-function org-edit-src-exit "org-src" (&optional context))
54 (declare-function org-open-at-point "org" (&optional in-emacs reference-buffer))
55 (declare-function org-save-outline-visibility "org-macs" (use-markers &rest body))
56 (declare-function org-outline-overlay-data "org" (&optional use-markers))
57 (declare-function org-set-outline-overlay-data "org" (data))
58 (declare-function org-narrow-to-subtree "org" ())
59 (declare-function org-split-string "org" (string &optional separators))
60 (declare-function org-entry-get "org"
61 (pom property &optional inherit literal-nil))
62 (declare-function org-make-options-regexp "org" (kwds &optional extra))
63 (declare-function org-do-remove-indentation "org" (&optional n))
64 (declare-function org-next-block "org" (arg &optional backward block-regexp))
65 (declare-function org-previous-block "org" (arg &optional block-regexp))
66 (declare-function org-show-context "org" (&optional key))
67 (declare-function org-at-table-p "org" (&optional table-type))
68 (declare-function org-cycle "org" (&optional arg))
69 (declare-function org-uniquify "org" (list))
70 (declare-function org-current-level "org" ())
71 (declare-function org-table-import "org-table" (file arg))
72 (declare-function org-add-hook "org-compat"
73 (hook function &optional append local))
74 (declare-function org-table-align "org-table" ())
75 (declare-function org-table-end "org-table" (&optional table-type))
76 (declare-function orgtbl-to-generic "org-table" (table params))
77 (declare-function orgtbl-to-orgtbl "org-table" (table params))
78 (declare-function org-babel-tangle-comment-links "ob-tangle" (&optional info))
79 (declare-function org-babel-lob-get-info "ob-lob" nil)
80 (declare-function org-babel-ref-split-args "ob-ref" (arg-string))
81 (declare-function org-babel-ref-parse "ob-ref" (assignment))
82 (declare-function org-babel-ref-resolve "ob-ref" (ref))
83 (declare-function org-babel-ref-goto-headline-id "ob-ref" (id))
84 (declare-function org-babel-ref-headline-body "ob-ref" ())
85 (declare-function org-babel-lob-execute-maybe "ob-lob" ())
86 (declare-function org-number-sequence "org-compat" (from &optional to inc))
87 (declare-function org-at-item-p "org-list" ())
88 (declare-function org-list-parse-list "org-list" (&optional delete))
89 (declare-function org-list-to-generic "org-list" (LIST PARAMS))
90 (declare-function org-list-struct "org-list" ())
91 (declare-function org-list-prevs-alist "org-list" (struct))
92 (declare-function org-list-get-list-end "org-list" (item struct prevs))
93 (declare-function org-remove-if "org" (predicate seq))
94 (declare-function org-completing-read "org" (&rest args))
95 (declare-function org-escape-code-in-region "org-src" (beg end))
96 (declare-function org-unescape-code-in-string "org-src" (s))
97 (declare-function org-table-to-lisp "org-table" (&optional txt))
98 (declare-function org-reverse-string "org" (string))
99 (declare-function org-element-context "org-element" (&optional ELEMENT))
100 (declare-function org-every "org" (pred seq))
102 (defgroup org-babel nil
103 "Code block evaluation and management in `org-mode' documents."
104 :tag "Babel"
105 :group 'org)
107 (defcustom org-confirm-babel-evaluate t
108 "Confirm before evaluation.
109 Require confirmation before interactively evaluating code
110 blocks in Org-mode buffers. The default value of this variable
111 is t, meaning confirmation is required for any code block
112 evaluation. This variable can be set to nil to inhibit any
113 future confirmation requests. This variable can also be set to a
114 function which takes two arguments the language of the code block
115 and the body of the code block. Such a function should then
116 return a non-nil value if the user should be prompted for
117 execution or nil if no prompt is required.
119 Warning: Disabling confirmation may result in accidental
120 evaluation of potentially harmful code. It may be advisable
121 remove code block execution from C-c C-c as further protection
122 against accidental code block evaluation. The
123 `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
124 remove code block execution from the C-c C-c keybinding."
125 :group 'org-babel
126 :version "24.1"
127 :type '(choice boolean function))
128 ;; don't allow this variable to be changed through file settings
129 (put 'org-confirm-babel-evaluate 'safe-local-variable (lambda (x) (eq x t)))
131 (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
132 "Remove code block evaluation from the C-c C-c key binding."
133 :group 'org-babel
134 :version "24.1"
135 :type 'boolean)
137 (defcustom org-babel-results-keyword "RESULTS"
138 "Keyword used to name results generated by code blocks.
139 Should be either RESULTS or NAME however any capitalization may
140 be used."
141 :group 'org-babel
142 :version "24.4"
143 :package-version '(Org . "8.0")
144 :type 'string)
146 (defcustom org-babel-noweb-wrap-start "<<"
147 "String used to begin a noweb reference in a code block.
148 See also `org-babel-noweb-wrap-end'."
149 :group 'org-babel
150 :type 'string)
152 (defcustom org-babel-noweb-wrap-end ">>"
153 "String used to end a noweb reference in a code block.
154 See also `org-babel-noweb-wrap-start'."
155 :group 'org-babel
156 :type 'string)
158 (defcustom org-babel-inline-result-wrap "=%s="
159 "Format string used to wrap inline results.
160 This string must include a \"%s\" which will be replaced by the results."
161 :group 'org-babel
162 :type 'string)
163 (put 'org-babel-inline-result-wrap
164 'safe-local-variable
165 (lambda (value)
166 (and (stringp value)
167 (string-match-p "%s" value))))
169 (defun org-babel-noweb-wrap (&optional regexp)
170 (concat org-babel-noweb-wrap-start
171 (or regexp "\\([^ \t\n].+?[^ \t]\\|[^ \t\n]\\)")
172 org-babel-noweb-wrap-end))
174 (defvar org-babel-src-name-regexp
175 "^[ \t]*#\\+name:[ \t]*"
176 "Regular expression used to match a source name line.")
178 (defvar org-babel-multi-line-header-regexp
179 "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
180 "Regular expression used to match multi-line header arguments.")
182 (defvar org-babel-src-name-w-name-regexp
183 (concat org-babel-src-name-regexp
184 "\\("
185 org-babel-multi-line-header-regexp
186 "\\)*"
187 "\\([^ ()\f\t\n\r\v]+\\)")
188 "Regular expression matching source name lines with a name.")
190 (defvar org-babel-src-block-regexp
191 (concat
192 ;; (1) indentation (2) lang
193 "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
194 ;; (3) switches
195 "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
196 ;; (4) header arguments
197 "\\([^\n]*\\)\n"
198 ;; (5) body
199 "\\([^\000]*?\n\\)??[ \t]*#\\+end_src")
200 "Regexp used to identify code blocks.")
202 (defvar org-babel-inline-src-block-regexp
203 (concat
204 ;; (1) replacement target (2) lang
205 "\\(?:^\\|[^-[:alnum:]]\\)\\(src_\\([^ \f\t\n\r\v]+\\)"
206 ;; (3,4) (unused, headers)
207 "\\(\\|\\[\\(.*?\\)\\]\\)"
208 ;; (5) body
209 "{\\([^\f\n\r\v]+?\\)}\\)")
210 "Regexp used to identify inline src-blocks.")
212 (defun org-babel-get-header (params key &optional others)
213 "Select only header argument of type KEY from a list.
214 Optional argument OTHERS indicates that only the header that do
215 not match KEY should be returned."
216 (delq nil
217 (mapcar
218 (lambda (p) (when (funcall (if others #'not #'identity) (eq (car p) key)) p))
219 params)))
221 (defun org-babel-get-inline-src-block-matches ()
222 "Set match data if within body of an inline source block.
223 Returns non-nil if match-data set"
224 (let ((src-at-0-p (save-excursion
225 (beginning-of-line 1)
226 (string= "src" (thing-at-point 'word))))
227 (first-line-p (= 1 (line-number-at-pos)))
228 (orig (point)))
229 (let ((search-for (cond ((and src-at-0-p first-line-p "src_"))
230 (first-line-p "[[:punct:] \t]src_")
231 (t "[[:punct:] \f\t\n\r\v]src_")))
232 (lower-limit (if first-line-p
234 (- (point-at-bol) 1))))
235 (save-excursion
236 (when (or (and src-at-0-p (bobp))
237 (and (re-search-forward "}" (point-at-eol) t)
238 (re-search-backward search-for lower-limit t)
239 (> orig (point))))
240 (when (looking-at org-babel-inline-src-block-regexp)
241 t ))))))
243 (defvar org-babel-inline-lob-one-liner-regexp)
244 (defun org-babel-get-lob-one-liner-matches ()
245 "Set match data if on line of an lob one liner.
246 Returns non-nil if match-data set"
247 (save-excursion
248 (unless (= (point) (point-at-bol)) ;; move before inline block
249 (re-search-backward "[ \f\t\n\r\v]" nil t))
250 (if (looking-at org-babel-inline-lob-one-liner-regexp)
252 nil)))
254 (defun org-babel-get-src-block-info (&optional light)
255 "Get information on the current source block.
257 Optional argument LIGHT does not resolve remote variable
258 references; a process which could likely result in the execution
259 of other code blocks.
261 Returns a list
262 (language body header-arguments-alist switches name indent block-head)."
263 (let ((case-fold-search t) head info name indent)
264 ;; full code block
265 (if (setq head (org-babel-where-is-src-block-head))
266 (save-excursion
267 (goto-char head)
268 (setq info (org-babel-parse-src-block-match))
269 (setq indent (car (last info)))
270 (setq info (butlast info))
271 (while (and (forward-line -1)
272 (looking-at org-babel-multi-line-header-regexp))
273 (setf (nth 2 info)
274 (org-babel-merge-params
275 (nth 2 info)
276 (org-babel-parse-header-arguments (match-string 1)))))
277 (when (looking-at org-babel-src-name-w-name-regexp)
278 (setq name (org-no-properties (match-string 3)))))
279 ;; inline source block
280 (when (org-babel-get-inline-src-block-matches)
281 (setq head (match-beginning 0))
282 (setq info (org-babel-parse-inline-src-block-match))))
283 ;; resolve variable references and add summary parameters
284 (when (and info (not light))
285 (setf (nth 2 info) (org-babel-process-params (nth 2 info))))
286 (when info (append info (list name indent head)))))
288 (defvar org-current-export-file) ; dynamically bound
289 (defmacro org-babel-check-confirm-evaluate (info &rest body)
290 "Evaluate BODY with special execution confirmation variables set.
292 Specifically; NOEVAL will indicate if evaluation is allowed,
293 QUERY will indicate if a user query is required, CODE-BLOCK will
294 hold the language of the code block, and BLOCK-NAME will hold the
295 name of the code block."
296 (declare (indent defun))
297 (org-with-gensyms
298 (lang block-body headers name head eval eval-no export eval-no-export)
299 `(let* ((,lang (nth 0 ,info))
300 (,block-body (nth 1 ,info))
301 (,headers (nth 2 ,info))
302 (,name (nth 4 ,info))
303 (,head (nth 6 ,info))
304 (,eval (or (cdr (assoc :eval ,headers))
305 (when (assoc :noeval ,headers) "no")))
306 (,eval-no (or (equal ,eval "no")
307 (equal ,eval "never")))
308 (,export (org-bound-and-true-p org-current-export-file))
309 (,eval-no-export (and ,export (or (equal ,eval "no-export")
310 (equal ,eval "never-export"))))
311 (noeval (or ,eval-no ,eval-no-export))
312 (query (or (equal ,eval "query")
313 (and ,export (equal ,eval "query-export"))
314 (if (functionp org-confirm-babel-evaluate)
315 (save-excursion
316 (goto-char ,head)
317 (funcall org-confirm-babel-evaluate
318 ,lang ,block-body))
319 org-confirm-babel-evaluate)))
320 (code-block (if ,info (format " %s " ,lang) " "))
321 (block-name (if ,name (format " (%s) " ,name) " ")))
322 ,@body)))
324 (defsubst org-babel-check-evaluate (info)
325 "Check if code block INFO should be evaluated.
326 Do not query the user."
327 (org-babel-check-confirm-evaluate info
328 (not (when noeval
329 (message (format "Evaluation of this%scode-block%sis disabled."
330 code-block block-name))))))
332 ;; dynamically scoped for asynchronous export
333 (defvar org-babel-confirm-evaluate-answer-no)
335 (defsubst org-babel-confirm-evaluate (info)
336 "Confirm evaluation of the code block INFO.
338 If the variable `org-babel-confirm-evaluate-answer-no' is bound
339 to a non-nil value, auto-answer with \"no\".
341 This query can also be suppressed by setting the value of
342 `org-confirm-babel-evaluate' to nil, in which case all future
343 interactive code block evaluations will proceed without any
344 confirmation from the user.
346 Note disabling confirmation may result in accidental evaluation
347 of potentially harmful code."
348 (org-babel-check-confirm-evaluate info
349 (not (when query
350 (unless
351 (and (not (org-bound-and-true-p
352 org-babel-confirm-evaluate-answer-no))
353 (yes-or-no-p
354 (format "Evaluate this%scode block%son your system? "
355 code-block block-name)))
356 (message (format "Evaluation of this%scode-block%sis aborted."
357 code-block block-name)))))))
359 ;;;###autoload
360 (defun org-babel-execute-safely-maybe ()
361 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
362 (org-babel-execute-maybe)))
364 (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-execute-safely-maybe)
366 ;;;###autoload
367 (defun org-babel-execute-maybe ()
368 (interactive)
369 (or (org-babel-execute-src-block-maybe)
370 (org-babel-lob-execute-maybe)))
372 (defmacro org-babel-when-in-src-block (&rest body)
373 "Execute BODY if point is in a source block and return t.
375 Otherwise do nothing and return nil."
376 `(if (or (org-babel-where-is-src-block-head)
377 (org-babel-get-inline-src-block-matches))
378 (progn
379 ,@body
381 nil))
383 (defun org-babel-execute-src-block-maybe ()
384 "Conditionally execute a source block.
385 Detect if this is context for a Babel src-block and if so
386 then run `org-babel-execute-src-block'."
387 (interactive)
388 (org-babel-when-in-src-block
389 (org-babel-eval-wipe-error-buffer)
390 (org-babel-execute-src-block current-prefix-arg)))
392 ;;;###autoload
393 (defun org-babel-view-src-block-info ()
394 "Display information on the current source block.
395 This includes header arguments, language and name, and is largely
396 a window into the `org-babel-get-src-block-info' function."
397 (interactive)
398 (let ((info (org-babel-get-src-block-info 'light))
399 (full (lambda (it) (> (length it) 0)))
400 (printf (lambda (fmt &rest args) (princ (apply #'format fmt args)))))
401 (when info
402 (with-help-window (help-buffer)
403 (let ((name (nth 4 info))
404 (lang (nth 0 info))
405 (switches (nth 3 info))
406 (header-args (nth 2 info)))
407 (when name (funcall printf "Name: %s\n" name))
408 (when lang (funcall printf "Lang: %s\n" lang))
409 (when (funcall full switches) (funcall printf "Switches: %s\n" switches))
410 (funcall printf "Header Arguments:\n")
411 (dolist (pair (sort header-args
412 (lambda (a b) (string< (symbol-name (car a))
413 (symbol-name (car b))))))
414 (when (funcall full (cdr pair))
415 (funcall printf "\t%S%s\t%s\n"
416 (car pair)
417 (if (> (length (format "%S" (car pair))) 7) "" "\t")
418 (cdr pair)))))))))
420 ;;;###autoload
421 (defun org-babel-expand-src-block-maybe ()
422 "Conditionally expand a source block.
423 Detect if this is context for a org-babel src-block and if so
424 then run `org-babel-expand-src-block'."
425 (interactive)
426 (org-babel-when-in-src-block
427 (org-babel-expand-src-block current-prefix-arg)))
429 ;;;###autoload
430 (defun org-babel-load-in-session-maybe ()
431 "Conditionally load a source block in a session.
432 Detect if this is context for a org-babel src-block and if so
433 then run `org-babel-load-in-session'."
434 (interactive)
435 (org-babel-when-in-src-block
436 (org-babel-load-in-session current-prefix-arg)))
438 (add-hook 'org-metaup-hook 'org-babel-load-in-session-maybe)
440 ;;;###autoload
441 (defun org-babel-pop-to-session-maybe ()
442 "Conditionally pop to a session.
443 Detect if this is context for a org-babel src-block and if so
444 then run `org-babel-switch-to-session'."
445 (interactive)
446 (org-babel-when-in-src-block
447 (org-babel-switch-to-session current-prefix-arg)))
449 (add-hook 'org-metadown-hook 'org-babel-pop-to-session-maybe)
451 (defconst org-babel-common-header-args-w-values
452 '((cache . ((no yes)))
453 (cmdline . :any)
454 (colnames . ((nil no yes)))
455 (comments . ((no link yes org both noweb)))
456 (dir . :any)
457 (eval . ((never query)))
458 (exports . ((code results both none)))
459 (epilogue . :any)
460 (file . :any)
461 (file-desc . :any)
462 (hlines . ((no yes)))
463 (mkdirp . ((yes no)))
464 (no-expand)
465 (noeval)
466 (noweb . ((yes no tangle no-export strip-export)))
467 (noweb-ref . :any)
468 (noweb-sep . :any)
469 (padline . ((yes no)))
470 (post . :any)
471 (prologue . :any)
472 (results . ((file list vector table scalar verbatim)
473 (raw html latex org code pp drawer)
474 (replace silent none append prepend)
475 (output value)))
476 (rownames . ((no yes)))
477 (sep . :any)
478 (session . :any)
479 (shebang . :any)
480 (tangle . ((tangle yes no :any)))
481 (tangle-mode . ((#o755 #o555 #o444 :any)))
482 (var . :any)
483 (wrap . :any)))
485 (defconst org-babel-header-arg-names
486 (mapcar #'car org-babel-common-header-args-w-values)
487 "Common header arguments used by org-babel.
488 Note that individual languages may define their own language
489 specific header arguments as well.")
491 (defconst org-babel-safe-header-args
492 '(:cache :colnames :comments :exports :epilogue :hlines :noeval
493 :noweb :noweb-ref :noweb-sep :padline :prologue :rownames
494 :sep :session :tangle :wrap
495 (:eval . ("never" "query"))
496 (:results . (lambda (str) (not (string-match "file" str)))))
497 "A list of safe header arguments for babel source blocks.
499 The list can have entries of the following forms:
500 - :ARG -> :ARG is always a safe header arg
501 - (:ARG . (VAL1 VAL2 ...)) -> :ARG is safe as a header arg if it is
502 `equal' to one of the VALs.
503 - (:ARG . FN) -> :ARG is safe as a header arg if the function FN
504 returns non-nil. FN is passed one
505 argument, the value of the header arg
506 (as a string).")
508 (defmacro org-babel-header-args-safe-fn (safe-list)
509 "Return a function that determines whether a list of header args are safe.
511 Intended usage is:
512 \(put 'org-babel-default-header-args 'safe-local-variable
513 (org-babel-header-args-safe-p org-babel-safe-header-args)
515 This allows org-babel languages to extend the list of safe values for
516 their `org-babel-default-header-args:foo' variable.
518 For the format of SAFE-LIST, see `org-babel-safe-header-args'."
519 `(lambda (value)
520 (and (listp value)
521 (org-every
522 (lambda (pair)
523 (and (consp pair)
524 (org-babel-one-header-arg-safe-p pair ,safe-list)))
525 value))))
527 (defvar org-babel-default-header-args
528 '((:session . "none") (:results . "replace") (:exports . "code")
529 (:cache . "no") (:noweb . "no") (:hlines . "no") (:tangle . "no"))
530 "Default arguments to use when evaluating a source block.")
531 (put 'org-babel-default-header-args 'safe-local-variable
532 (org-babel-header-args-safe-fn org-babel-safe-header-args))
534 (defvar org-babel-default-inline-header-args
535 '((:session . "none") (:results . "replace")
536 (:exports . "results") (:hlines . "yes"))
537 "Default arguments to use when evaluating an inline source block.")
538 (put 'org-babel-default-inline-header-args 'safe-local-variable
539 (org-babel-header-args-safe-fn org-babel-safe-header-args))
541 (defvar org-babel-data-names '("tblname" "results" "name"))
543 (defvar org-babel-result-regexp
544 (concat "^[ \t]*#\\+"
545 (regexp-opt org-babel-data-names t)
546 "\\(\\[\\("
547 ;; FIXME The string below is `org-ts-regexp'
548 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
549 " \\)?\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*")
550 "Regular expression used to match result lines.
551 If the results are associated with a hash key then the hash will
552 be saved in the second match data.")
554 (defvar org-babel-result-w-name-regexp
555 (concat org-babel-result-regexp
556 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
558 (defvar org-babel-min-lines-for-block-output 10
559 "The minimum number of lines for block output.
560 If number of lines of output is equal to or exceeds this
561 value, the output is placed in a #+begin_example...#+end_example
562 block. Otherwise the output is marked as literal by inserting
563 colons at the starts of the lines. This variable only takes
564 effect if the :results output option is in effect.")
566 (defvar org-babel-noweb-error-langs nil
567 "Languages for which Babel will raise literate programming errors.
568 List of languages for which errors should be raised when the
569 source code block satisfying a noweb reference in this language
570 can not be resolved.")
572 (defvar org-babel-hash-show 4
573 "Number of initial characters to show of a hidden results hash.")
575 (defvar org-babel-hash-show-time nil
576 "Non-nil means show the time the code block was evaluated in the result hash.")
578 (defvar org-babel-after-execute-hook nil
579 "Hook for functions to be called after `org-babel-execute-src-block'")
581 (defun org-babel-named-src-block-regexp-for-name (name)
582 "This generates a regexp used to match a src block named NAME."
583 (concat org-babel-src-name-regexp (regexp-quote name)
584 "[ \t(]*[\r\n]\\(?:^#.*[\r\n]\\)*"
585 (substring org-babel-src-block-regexp 1)))
587 (defun org-babel-named-data-regexp-for-name (name)
588 "This generates a regexp used to match data named NAME."
589 (concat org-babel-result-regexp (regexp-quote name) "\\([ \t]\\|$\\)"))
591 ;;; functions
592 (defvar call-process-region)
593 (defvar org-babel-current-src-block-location nil
594 "Marker pointing to the src block currently being executed.
595 This may also point to a call line or an inline code block. If
596 multiple blocks are being executed (e.g., in chained execution
597 through use of the :var header argument) this marker points to
598 the outer-most code block.")
600 ;;;###autoload
601 (defun org-babel-execute-src-block (&optional arg info params)
602 "Execute the current source code block.
603 Insert the results of execution into the buffer. Source code
604 execution and the collection and formatting of results can be
605 controlled through a variety of header arguments.
607 With prefix argument ARG, force re-execution even if an existing
608 result cached in the buffer would otherwise have been returned.
610 Optionally supply a value for INFO in the form returned by
611 `org-babel-get-src-block-info'.
613 Optionally supply a value for PARAMS which will be merged with
614 the header arguments specified at the front of the source code
615 block."
616 (interactive)
617 (let* ((org-babel-current-src-block-location
618 (or org-babel-current-src-block-location
619 (nth 6 info)
620 (org-babel-where-is-src-block-head)
621 ;; inline src block
622 (and (org-babel-get-inline-src-block-matches)
623 (match-beginning 0))))
624 (info (if info
625 (copy-tree info)
626 (org-babel-get-src-block-info)))
627 (merged-params (org-babel-merge-params (nth 2 info) params)))
628 (when (org-babel-check-evaluate
629 (let ((i info)) (setf (nth 2 i) merged-params) i))
630 (let* ((params (if params
631 (org-babel-process-params merged-params)
632 (nth 2 info)))
633 (cachep (and (not arg) (cdr (assoc :cache params))
634 (string= "yes" (cdr (assoc :cache params)))))
635 (new-hash (when cachep (org-babel-sha1-hash info)))
636 (old-hash (when cachep (org-babel-current-result-hash)))
637 (cache-current-p (and (not arg) new-hash
638 (equal new-hash old-hash))))
639 (cond
640 (cache-current-p
641 (save-excursion ;; return cached result
642 (goto-char (org-babel-where-is-src-block-result nil info))
643 (end-of-line 1) (forward-char 1)
644 (let ((result (org-babel-read-result)))
645 (message (replace-regexp-in-string
646 "%" "%%" (format "%S" result))) result)))
647 ((org-babel-confirm-evaluate
648 (let ((i info)) (setf (nth 2 i) merged-params) i))
649 (let* ((lang (nth 0 info))
650 (result-params (cdr (assoc :result-params params)))
651 (body (setf (nth 1 info)
652 (if (org-babel-noweb-p params :eval)
653 (org-babel-expand-noweb-references info)
654 (nth 1 info))))
655 (dir (cdr (assoc :dir params)))
656 (default-directory
657 (or (and dir (file-name-as-directory (expand-file-name dir)))
658 default-directory))
659 (org-babel-call-process-region-original ;; for tramp handler
660 (or (org-bound-and-true-p
661 org-babel-call-process-region-original)
662 (symbol-function 'call-process-region)))
663 (indent (nth 5 info))
664 result cmd)
665 (unwind-protect
666 (let ((call-process-region
667 (lambda (&rest args)
668 (apply 'org-babel-tramp-handle-call-process-region
669 args))))
670 (let ((lang-check
671 (lambda (f)
672 (let ((f (intern (concat "org-babel-execute:" f))))
673 (when (fboundp f) f)))))
674 (setq cmd
675 (or (funcall lang-check lang)
676 (funcall lang-check
677 (symbol-name
678 (cdr (assoc lang org-src-lang-modes))))
679 (error "No org-babel-execute function for %s!"
680 lang))))
681 (message "executing %s code block%s..."
682 (capitalize lang)
683 (if (nth 4 info) (format " (%s)" (nth 4 info)) ""))
684 (if (member "none" result-params)
685 (progn
686 (funcall cmd body params)
687 (message "result silenced")
688 (setq result nil))
689 (setq result
690 (let ((result (funcall cmd body params)))
691 (if (and (eq (cdr (assoc :result-type params))
692 'value)
693 (or (member "vector" result-params)
694 (member "table" result-params))
695 (not (listp result)))
696 (list (list result)) result)))
697 ;; If non-empty result and :file then write to :file.
698 (when (cdr (assoc :file params))
699 (when result
700 (with-temp-file (cdr (assoc :file params))
701 (insert
702 (org-babel-format-result
703 result (cdr (assoc :sep (nth 2 info)))))))
704 (setq result (cdr (assoc :file params))))
705 ;; Possibly perform post process provided its appropriate.
706 (when (cdr (assoc :post params))
707 (let ((*this* (if (cdr (assoc :file params))
708 (org-babel-result-to-file
709 (cdr (assoc :file params))
710 (when (assoc :file-desc params)
711 (or (cdr (assoc :file-desc params))
712 result)))
713 result)))
714 (setq result (org-babel-ref-resolve
715 (cdr (assoc :post params))))
716 (when (cdr (assoc :file params))
717 (setq result-params
718 (remove "file" result-params)))))
719 (org-babel-insert-result
720 result result-params info new-hash indent lang))
721 (run-hooks 'org-babel-after-execute-hook)
722 result)
723 (setq call-process-region
724 'org-babel-call-process-region-original)))))))))
726 (defun org-babel-expand-body:generic (body params &optional var-lines)
727 "Expand BODY with PARAMS.
728 Expand a block of code with org-babel according to its header
729 arguments. This generic implementation of body expansion is
730 called for languages which have not defined their own specific
731 org-babel-expand-body:lang function."
732 (let ((pro (cdr (assoc :prologue params)))
733 (epi (cdr (assoc :epilogue params))))
734 (mapconcat #'identity
735 (append (when pro (list pro))
736 var-lines
737 (list body)
738 (when epi (list epi)))
739 "\n")))
741 ;;;###autoload
742 (defun org-babel-expand-src-block (&optional arg info params)
743 "Expand the current source code block.
744 Expand according to the source code block's header
745 arguments and pop open the results in a preview buffer."
746 (interactive)
747 (let* ((info (or info (org-babel-get-src-block-info)))
748 (lang (nth 0 info))
749 (params (setf (nth 2 info)
750 (sort (org-babel-merge-params (nth 2 info) params)
751 (lambda (el1 el2) (string< (symbol-name (car el1))
752 (symbol-name (car el2)))))))
753 (body (setf (nth 1 info)
754 (if (org-babel-noweb-p params :eval)
755 (org-babel-expand-noweb-references info) (nth 1 info))))
756 (expand-cmd (intern (concat "org-babel-expand-body:" lang)))
757 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
758 lang)))
759 (expanded
760 (if (fboundp expand-cmd) (funcall expand-cmd body params)
761 (org-babel-expand-body:generic
762 body params (and (fboundp assignments-cmd)
763 (funcall assignments-cmd params))))))
764 (if (org-called-interactively-p 'any)
765 (org-edit-src-code
766 nil expanded
767 (concat "*Org-Babel Preview " (buffer-name) "[ " lang " ]*"))
768 expanded)))
770 (defun org-babel-edit-distance (s1 s2)
771 "Return the edit (levenshtein) distance between strings S1 S2."
772 (let* ((l1 (length s1))
773 (l2 (length s2))
774 (dist (vconcat (mapcar (lambda (_) (make-vector (1+ l2) nil))
775 (number-sequence 1 (1+ l1)))))
776 (in (lambda (i j) (aref (aref dist i) j))))
777 (setf (aref (aref dist 0) 0) 0)
778 (dolist (j (number-sequence 1 l2))
779 (setf (aref (aref dist 0) j) j))
780 (dolist (i (number-sequence 1 l1))
781 (setf (aref (aref dist i) 0) i)
782 (dolist (j (number-sequence 1 l2))
783 (setf (aref (aref dist i) j)
784 (min
785 (1+ (funcall in (1- i) j))
786 (1+ (funcall in i (1- j)))
787 (+ (if (equal (aref s1 (1- i)) (aref s2 (1- j))) 0 1)
788 (funcall in (1- i) (1- j)))))))
789 (funcall in l1 l2)))
791 (defun org-babel-combine-header-arg-lists (original &rest others)
792 "Combine a number of lists of header argument names and arguments."
793 (let ((results (copy-sequence original)))
794 (dolist (new-list others)
795 (dolist (arg-pair new-list)
796 (let ((header (car arg-pair))
797 (args (cdr arg-pair)))
798 (setq results
799 (cons arg-pair (org-remove-if
800 (lambda (pair) (equal header (car pair)))
801 results))))))
802 results))
804 ;;;###autoload
805 (defun org-babel-check-src-block ()
806 "Check for misspelled header arguments in the current code block."
807 (interactive)
808 ;; TODO: report malformed code block
809 ;; TODO: report incompatible combinations of header arguments
810 ;; TODO: report uninitialized variables
811 (let ((too-close 2) ;; <- control closeness to report potential match
812 (names (mapcar #'symbol-name org-babel-header-arg-names)))
813 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg)) 1))
814 (and (org-babel-where-is-src-block-head)
815 (org-babel-parse-header-arguments
816 (org-no-properties
817 (match-string 4))))))
818 (dolist (name names)
819 (when (and (not (string= header name))
820 (<= (org-babel-edit-distance header name) too-close)
821 (not (member header names)))
822 (error "Supplied header \"%S\" is suspiciously close to \"%S\""
823 header name))))
824 (message "No suspicious header arguments found.")))
826 ;;;###autoload
827 (defun org-babel-insert-header-arg (&optional header-arg value)
828 "Insert a header argument selecting from lists of common args and values."
829 (interactive)
830 (let* ((info (org-babel-get-src-block-info 'light))
831 (lang (car info))
832 (begin (nth 6 info))
833 (lang-headers (intern (concat "org-babel-header-args:" lang)))
834 (headers (org-babel-combine-header-arg-lists
835 org-babel-common-header-args-w-values
836 (when (boundp lang-headers) (eval lang-headers))))
837 (header-arg (or header-arg
838 (org-icompleting-read
839 "Header Arg: "
840 (mapcar
841 (lambda (header-spec) (symbol-name (car header-spec)))
842 headers))))
843 (vals (cdr (assoc (intern header-arg) headers)))
844 (value (or value
845 (cond
846 ((eq vals :any)
847 (read-from-minibuffer "value: "))
848 ((listp vals)
849 (mapconcat
850 (lambda (group)
851 (let ((arg (org-icompleting-read
852 "value: "
853 (cons "default"
854 (mapcar #'symbol-name group)))))
855 (if (and arg (not (string= "default" arg)))
856 (concat arg " ")
857 "")))
858 vals ""))))))
859 (save-excursion
860 (goto-char begin)
861 (goto-char (point-at-eol))
862 (unless (= (char-before (point)) ?\ ) (insert " "))
863 (insert ":" header-arg) (when value (insert " " value)))))
865 ;; Add support for completing-read insertion of header arguments after ":"
866 (defun org-babel-header-arg-expand ()
867 "Call `org-babel-enter-header-arg-w-completion' in appropriate contexts."
868 (when (and (equal (char-before) ?\:) (org-babel-where-is-src-block-head))
869 (org-babel-enter-header-arg-w-completion (match-string 2))))
871 (defun org-babel-enter-header-arg-w-completion (&optional lang)
872 "Insert header argument appropriate for LANG with completion."
873 (let* ((lang-headers-var (intern (concat "org-babel-header-args:" lang)))
874 (lang-headers (when (boundp lang-headers-var) (eval lang-headers-var)))
875 (headers-w-values (org-babel-combine-header-arg-lists
876 org-babel-common-header-args-w-values lang-headers))
877 (headers (mapcar #'symbol-name (mapcar #'car headers-w-values)))
878 (header (org-completing-read "Header Arg: " headers))
879 (args (cdr (assoc (intern header) headers-w-values)))
880 (arg (when (and args (listp args))
881 (org-completing-read
882 (format "%s: " header)
883 (mapcar #'symbol-name (apply #'append args))))))
884 (insert (concat header " " (or arg "")))
885 (cons header arg)))
887 (add-hook 'org-tab-first-hook 'org-babel-header-arg-expand)
889 ;;;###autoload
890 (defun org-babel-load-in-session (&optional arg info)
891 "Load the body of the current source-code block.
892 Evaluate the header arguments for the source block before
893 entering the session. After loading the body this pops open the
894 session."
895 (interactive)
896 (let* ((info (or info (org-babel-get-src-block-info)))
897 (lang (nth 0 info))
898 (params (nth 2 info))
899 (body (if (not info)
900 (user-error "No src code block at point")
901 (setf (nth 1 info)
902 (if (org-babel-noweb-p params :eval)
903 (org-babel-expand-noweb-references info)
904 (nth 1 info)))))
905 (session (cdr (assoc :session params)))
906 (dir (cdr (assoc :dir params)))
907 (default-directory
908 (or (and dir (file-name-as-directory dir)) default-directory))
909 (cmd (intern (concat "org-babel-load-session:" lang))))
910 (unless (fboundp cmd)
911 (error "No org-babel-load-session function for %s!" lang))
912 (pop-to-buffer (funcall cmd session body params))
913 (end-of-line 1)))
915 ;;;###autoload
916 (defun org-babel-initiate-session (&optional arg info)
917 "Initiate session for current code block.
918 If called with a prefix argument then resolve any variable
919 references in the header arguments and assign these variables in
920 the session. Copy the body of the code block to the kill ring."
921 (interactive "P")
922 (let* ((info (or info (org-babel-get-src-block-info (not arg))))
923 (lang (nth 0 info))
924 (body (nth 1 info))
925 (params (nth 2 info))
926 (session (cdr (assoc :session params)))
927 (dir (cdr (assoc :dir params)))
928 (default-directory
929 (or (and dir (file-name-as-directory dir)) default-directory))
930 (init-cmd (intern (format "org-babel-%s-initiate-session" lang)))
931 (prep-cmd (intern (concat "org-babel-prep-session:" lang))))
932 (if (and (stringp session) (string= session "none"))
933 (error "This block is not using a session!"))
934 (unless (fboundp init-cmd)
935 (error "No org-babel-initiate-session function for %s!" lang))
936 (with-temp-buffer (insert (org-babel-trim body))
937 (copy-region-as-kill (point-min) (point-max)))
938 (when arg
939 (unless (fboundp prep-cmd)
940 (error "No org-babel-prep-session function for %s!" lang))
941 (funcall prep-cmd session params))
942 (funcall init-cmd session params)))
944 ;;;###autoload
945 (defun org-babel-switch-to-session (&optional arg info)
946 "Switch to the session of the current code block.
947 Uses `org-babel-initiate-session' to start the session. If called
948 with a prefix argument then this is passed on to
949 `org-babel-initiate-session'."
950 (interactive "P")
951 (pop-to-buffer (org-babel-initiate-session arg info))
952 (end-of-line 1))
954 (defalias 'org-babel-pop-to-session 'org-babel-switch-to-session)
956 (defvar org-src-window-setup)
958 ;;;###autoload
959 (defun org-babel-switch-to-session-with-code (&optional arg info)
960 "Switch to code buffer and display session."
961 (interactive "P")
962 (let ((swap-windows
963 (lambda ()
964 (let ((other-window-buffer (window-buffer (next-window))))
965 (set-window-buffer (next-window) (current-buffer))
966 (set-window-buffer (selected-window) other-window-buffer))
967 (other-window 1)))
968 (info (org-babel-get-src-block-info))
969 (org-src-window-setup 'reorganize-frame))
970 (save-excursion
971 (org-babel-switch-to-session arg info))
972 (org-edit-src-code)
973 (funcall swap-windows)))
975 ;;;###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 ()
1250 "Return the current in-buffer hash."
1251 (org-babel-where-is-src-block-result)
1252 (org-no-properties (match-string 5)))
1254 (defun org-babel-set-current-result-hash (hash)
1255 "Set the current in-buffer hash to HASH."
1256 (org-babel-where-is-src-block-result)
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 (or (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 (prog1 nil
1962 (forward-line 1)
1963 (delete-region
1964 end (org-babel-result-end)))
1965 (setq end nil)))))))))))
1966 (if (not (and insert end)) found
1967 (goto-char end)
1968 (unless beg
1969 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1970 (insert (concat
1971 (when (wholenump indent) (make-string indent ? ))
1972 "#+" org-babel-results-keyword
1973 (when hash
1974 (if org-babel-hash-show-time
1975 (concat
1976 "["(format-time-string "<%Y-%m-%d %H:%M:%S>")" "hash"]")
1977 (concat "["hash"]")))
1979 (when name (concat " " name)) "\n"))
1980 (unless beg (insert "\n") (backward-char))
1981 (beginning-of-line 0)
1982 (if hash (org-babel-hide-hash))
1983 (point)))))
1985 (defvar org-block-regexp)
1986 (defun org-babel-read-result ()
1987 "Read the result at `point' into emacs-lisp."
1988 (let ((case-fold-search t) result-string)
1989 (cond
1990 ((org-at-table-p) (org-babel-read-table))
1991 ((org-at-item-p) (org-babel-read-list))
1992 ((looking-at org-bracket-link-regexp) (org-babel-read-link))
1993 ((looking-at org-block-regexp) (org-remove-indentation (match-string 4)))
1994 ((or (looking-at "^[ \t]*: ") (looking-at "^[ \t]*:$"))
1995 (setq result-string
1996 (org-babel-trim
1997 (mapconcat (lambda (line)
1998 (or (and (> (length line) 1)
1999 (string-match "^[ \t]*: ?\\(.+\\)" line)
2000 (match-string 1 line))
2001 ""))
2002 (split-string
2003 (buffer-substring
2004 (point) (org-babel-result-end)) "[\r\n]+")
2005 "\n")))
2006 (or (org-babel-number-p result-string) result-string))
2007 ((looking-at org-babel-result-regexp)
2008 (save-excursion (forward-line 1) (org-babel-read-result))))))
2010 (defun org-babel-read-table ()
2011 "Read the table at `point' into emacs-lisp."
2012 (mapcar (lambda (row)
2013 (if (and (symbolp row) (equal row 'hline)) row
2014 (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval)) row)))
2015 (org-table-to-lisp)))
2017 (defun org-babel-read-list ()
2018 "Read the list at `point' into emacs-lisp."
2019 (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval))
2020 (mapcar #'cadr (cdr (org-list-parse-list)))))
2022 (defvar org-link-types-re)
2023 (defun org-babel-read-link ()
2024 "Read the link at `point' into emacs-lisp.
2025 If the path of the link is a file path it is expanded using
2026 `expand-file-name'."
2027 (let* ((case-fold-search t)
2028 (raw (and (looking-at org-bracket-link-regexp)
2029 (org-no-properties (match-string 1))))
2030 (type (and (string-match org-link-types-re raw)
2031 (match-string 1 raw))))
2032 (cond
2033 ((not type) (expand-file-name raw))
2034 ((string= type "file")
2035 (and (string-match "file\\(.*\\):\\(.+\\)" raw)
2036 (expand-file-name (match-string 2 raw))))
2037 (t raw))))
2039 (defun org-babel-format-result (result &optional sep)
2040 "Format RESULT for writing to file."
2041 (let ((echo-res (lambda (r) (if (stringp r) r (format "%S" r)))))
2042 (if (listp result)
2043 ;; table result
2044 (orgtbl-to-generic
2045 result (list :sep (or sep "\t") :fmt echo-res))
2046 ;; scalar result
2047 (funcall echo-res result))))
2049 (defun org-babel-insert-result
2050 (result &optional result-params info hash indent lang)
2051 "Insert RESULT into the current buffer.
2052 By default RESULT is inserted after the end of the
2053 current source block. With optional argument RESULT-PARAMS
2054 controls insertion of results in the org-mode file.
2055 RESULT-PARAMS can take the following values:
2057 replace - (default option) insert results after the source block
2058 replacing any previously inserted results
2060 silent -- no results are inserted into the Org-mode buffer but
2061 the results are echoed to the minibuffer and are
2062 ingested by Emacs (a potentially time consuming
2063 process)
2065 file ---- the results are interpreted as a file path, and are
2066 inserted into the buffer using the Org-mode file syntax
2068 list ---- the results are interpreted as an Org-mode list.
2070 raw ----- results are added directly to the Org-mode file. This
2071 is a good option if you code block will output org-mode
2072 formatted text.
2074 drawer -- results are added directly to the Org-mode file as with
2075 \"raw\", but are wrapped in a RESULTS drawer, allowing
2076 them to later be replaced or removed automatically.
2078 org ----- results are added inside of a \"#+BEGIN_SRC org\" block.
2079 They are not comma-escaped when inserted, but Org syntax
2080 here will be discarded when exporting the file.
2082 html ---- results are added inside of a #+BEGIN_HTML block. This
2083 is a good option if you code block will output html
2084 formatted text.
2086 latex --- results are added inside of a #+BEGIN_LATEX block.
2087 This is a good option if you code block will output
2088 latex formatted text.
2090 code ---- the results are extracted in the syntax of the source
2091 code of the language being evaluated and are added
2092 inside of a #+BEGIN_SRC block with the source-code
2093 language set appropriately. Note this relies on the
2094 optional LANG argument."
2095 (if (stringp result)
2096 (progn
2097 (setq result (org-no-properties result))
2098 (when (member "file" result-params)
2099 (setq result (org-babel-result-to-file
2100 result (when (assoc :file-desc (nth 2 info))
2101 (or (cdr (assoc :file-desc (nth 2 info)))
2102 result))))))
2103 (unless (listp result) (setq result (format "%S" result))))
2104 (if (and result-params (member "silent" result-params))
2105 (progn
2106 (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
2107 result)
2108 (save-excursion
2109 (let* ((inlinep
2110 (save-excursion
2111 (when (or (org-babel-get-inline-src-block-matches)
2112 (org-babel-get-lob-one-liner-matches))
2113 (goto-char (match-end 0))
2114 (insert (if (listp result) "\n" " "))
2115 (point))))
2116 (existing-result (unless inlinep
2117 (org-babel-where-is-src-block-result
2118 t info hash indent)))
2119 (results-switches
2120 (cdr (assoc :results_switches (nth 2 info))))
2121 (visible-beg (copy-marker (point-min)))
2122 (visible-end (copy-marker (point-max)))
2123 ;; When results exist outside of the current visible
2124 ;; region of the buffer, be sure to widen buffer to
2125 ;; update them.
2126 (outside-scope-p (and existing-result
2127 (or (> visible-beg existing-result)
2128 (<= visible-end existing-result))))
2129 beg end)
2130 (when (and (stringp result) ; ensure results end in a newline
2131 (not inlinep)
2132 (> (length result) 0)
2133 (not (or (string-equal (substring result -1) "\n")
2134 (string-equal (substring result -1) "\r"))))
2135 (setq result (concat result "\n")))
2136 (unwind-protect
2137 (progn
2138 (when outside-scope-p (widen))
2139 (if (not existing-result)
2140 (setq beg (or inlinep (point)))
2141 (goto-char existing-result)
2142 (save-excursion
2143 (re-search-forward "#" nil t)
2144 (setq indent (- (current-column) 1)))
2145 (forward-line 1)
2146 (setq beg (point))
2147 (cond
2148 ((member "replace" result-params)
2149 (delete-region (point) (org-babel-result-end)))
2150 ((member "append" result-params)
2151 (goto-char (org-babel-result-end)) (setq beg (point-marker)))
2152 ((member "prepend" result-params)))) ; already there
2153 (setq results-switches
2154 (if results-switches (concat " " results-switches) ""))
2155 (let ((wrap (lambda (start finish &optional no-escape)
2156 (goto-char end) (insert (concat finish "\n"))
2157 (goto-char beg) (insert (concat start "\n"))
2158 (unless no-escape
2159 (org-escape-code-in-region (min (point) end) end))
2160 (goto-char end) (goto-char (point-at-eol))
2161 (setq end (point-marker))))
2162 (proper-list-p (lambda (it) (and (listp it) (null (cdr (last it)))))))
2163 ;; insert results based on type
2164 (cond
2165 ;; do nothing for an empty result
2166 ((null result))
2167 ;; insert a list if preferred
2168 ((member "list" result-params)
2169 (insert
2170 (org-babel-trim
2171 (org-list-to-generic
2172 (cons 'unordered
2173 (mapcar
2174 (lambda (el) (list nil (if (stringp el) el (format "%S" el))))
2175 (if (listp result) result (split-string result "\n" t))))
2176 '(:splicep nil :istart "- " :iend "\n")))
2177 "\n"))
2178 ;; assume the result is a table if it's not a string
2179 ((funcall proper-list-p result)
2180 (goto-char beg)
2181 (insert (concat (orgtbl-to-orgtbl
2182 (if (or (eq 'hline (car result))
2183 (and (listp (car result))
2184 (listp (cdr (car result)))))
2185 result (list result))
2186 '(:fmt (lambda (cell) (format "%s" cell)))) "\n"))
2187 (goto-char beg) (when (org-at-table-p) (org-table-align)))
2188 ((and (listp result) (not (funcall proper-list-p result)))
2189 (insert (format "%s\n" result)))
2190 ((member "file" result-params)
2191 (when inlinep (goto-char inlinep))
2192 (insert result))
2193 (t (goto-char beg) (insert result)))
2194 (when (funcall proper-list-p result) (goto-char (org-table-end)))
2195 (setq end (point-marker))
2196 ;; possibly wrap result
2197 (cond
2198 ((assoc :wrap (nth 2 info))
2199 (let ((name (or (cdr (assoc :wrap (nth 2 info))) "RESULTS")))
2200 (funcall wrap (concat "#+BEGIN_" name)
2201 (concat "#+END_" (car (org-split-string name))))))
2202 ((member "html" result-params)
2203 (funcall wrap "#+BEGIN_HTML" "#+END_HTML"))
2204 ((member "latex" result-params)
2205 (funcall wrap "#+BEGIN_LaTeX" "#+END_LaTeX"))
2206 ((member "org" result-params)
2207 (goto-char beg) (if (org-at-table-p) (org-cycle))
2208 (funcall wrap "#+BEGIN_SRC org" "#+END_SRC"))
2209 ((member "code" result-params)
2210 (funcall wrap (format "#+BEGIN_SRC %s%s" (or lang "none") results-switches)
2211 "#+END_SRC"))
2212 ((member "raw" result-params)
2213 (goto-char beg) (if (org-at-table-p) (org-cycle)))
2214 ((or (member "drawer" result-params)
2215 ;; Stay backward compatible with <7.9.2
2216 (member "wrap" result-params))
2217 (goto-char beg) (if (org-at-table-p) (org-cycle))
2218 (funcall wrap ":RESULTS:" ":END:" 'no-escape))
2219 ((and (not (funcall proper-list-p result))
2220 (not (member "file" result-params)))
2221 (org-babel-examplize-region beg end results-switches)
2222 (setq end (point)))))
2223 ;; possibly indent the results to match the #+results line
2224 (when (and (not inlinep) (numberp indent) indent (> indent 0)
2225 ;; in this case `table-align' does the work for us
2226 (not (and (listp result)
2227 (member "append" result-params))))
2228 (indent-rigidly beg end indent))
2229 (if (null result)
2230 (if (member "value" result-params)
2231 (message "Code block returned no value.")
2232 (message "Code block produced no output."))
2233 (message "Code block evaluation complete.")))
2234 (when outside-scope-p (narrow-to-region visible-beg visible-end))
2235 (set-marker visible-beg nil)
2236 (set-marker visible-end nil))))))
2238 (defun org-babel-remove-result (&optional info keep-keyword)
2239 "Remove the result of the current source block."
2240 (interactive)
2241 (let ((location (org-babel-where-is-src-block-result nil info)))
2242 (when location
2243 (save-excursion
2244 (goto-char location)
2245 (when (looking-at (concat org-babel-result-regexp ".*$"))
2246 (delete-region
2247 (if keep-keyword (1+ (match-end 0)) (1- (match-beginning 0)))
2248 (progn (forward-line 1) (org-babel-result-end))))))))
2250 (defun org-babel-result-end ()
2251 "Return the point at the end of the current set of results."
2252 (save-excursion
2253 (cond
2254 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
2255 ((org-at-item-p) (let* ((struct (org-list-struct))
2256 (prvs (org-list-prevs-alist struct)))
2257 (org-list-get-list-end (point-at-bol) struct prvs)))
2258 ((let ((case-fold-search t)) (looking-at "^\\([ \t]*\\):results:"))
2259 (progn (re-search-forward (concat "^" (match-string 1) ":END:"))
2260 (forward-char 1) (point)))
2262 (let ((case-fold-search t))
2263 (if (looking-at (concat "[ \t]*#\\+begin_\\([^ \t\n\r]+\\)"))
2264 (progn (re-search-forward (concat "[ \t]*#\\+end_" (match-string 1))
2265 nil t)
2266 (forward-char 1))
2267 (while (looking-at "[ \t]*\\(: \\|:$\\|\\[\\[\\)")
2268 (forward-line 1))))
2269 (point)))))
2271 (defun org-babel-result-to-file (result &optional description)
2272 "Convert RESULT into an `org-mode' link with optional DESCRIPTION.
2273 If the `default-directory' is different from the containing
2274 file's directory then expand relative links."
2275 (when (stringp result)
2276 (format "[[file:%s]%s]"
2277 (if (and default-directory
2278 buffer-file-name
2279 (not (string= (expand-file-name default-directory)
2280 (expand-file-name
2281 (file-name-directory buffer-file-name)))))
2282 (expand-file-name result default-directory)
2283 result)
2284 (if description (concat "[" description "]") ""))))
2286 (defvar org-babel-capitalize-examplize-region-markers nil
2287 "Make true to capitalize begin/end example markers inserted by code blocks.")
2289 (defun org-babel-examplize-region (beg end &optional results-switches)
2290 "Comment out region using the inline '==' or ': ' org example quote."
2291 (interactive "*r")
2292 (let ((chars-between (lambda (b e)
2293 (not (string-match "^[\\s]*$" (buffer-substring b e)))))
2294 (maybe-cap (lambda (str) (if org-babel-capitalize-examplize-region-markers
2295 (upcase str) str))))
2296 (if (or (funcall chars-between (save-excursion (goto-char beg) (point-at-bol)) beg)
2297 (funcall chars-between end (save-excursion (goto-char end) (point-at-eol))))
2298 (save-excursion
2299 (goto-char beg)
2300 (insert (format org-babel-inline-result-wrap
2301 (prog1 (buffer-substring beg end)
2302 (delete-region beg end)))))
2303 (let ((size (count-lines beg end)))
2304 (save-excursion
2305 (cond ((= size 0)) ; do nothing for an empty result
2306 ((< size org-babel-min-lines-for-block-output)
2307 (goto-char beg)
2308 (dotimes (n size)
2309 (beginning-of-line 1) (insert ": ") (forward-line 1)))
2311 (goto-char beg)
2312 (insert (if results-switches
2313 (format "%s%s\n"
2314 (funcall maybe-cap "#+begin_example")
2315 results-switches)
2316 (funcall maybe-cap "#+begin_example\n")))
2317 (if (markerp end) (goto-char end) (forward-char (- end beg)))
2318 (insert (funcall maybe-cap "#+end_example\n")))))))))
2320 (defun org-babel-update-block-body (new-body)
2321 "Update the body of the current code block to NEW-BODY."
2322 (if (not (org-babel-where-is-src-block-head))
2323 (error "Not in a source block")
2324 (save-match-data
2325 (replace-match (concat (org-babel-trim (org-remove-indentation new-body))
2326 "\n") nil t nil 5))
2327 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
2329 (defun org-babel-merge-params (&rest plists)
2330 "Combine all parameter association lists in PLISTS.
2331 Later elements of PLISTS override the values of previous elements.
2332 This takes into account some special considerations for certain
2333 parameters when merging lists."
2334 (let* ((results-exclusive-groups
2335 (mapcar (lambda (group) (mapcar #'symbol-name group))
2336 (cdr (assoc 'results org-babel-common-header-args-w-values))))
2337 (exports-exclusive-groups
2338 (mapcar (lambda (group) (mapcar #'symbol-name group))
2339 (cdr (assoc 'exports org-babel-common-header-args-w-values))))
2340 (variable-index 0)
2341 (e-merge (lambda (exclusive-groups &rest result-params)
2342 ;; maintain exclusivity of mutually exclusive parameters
2343 (let (output)
2344 (mapc (lambda (new-params)
2345 (mapc (lambda (new-param)
2346 (mapc (lambda (exclusive-group)
2347 (when (member new-param exclusive-group)
2348 (mapcar (lambda (excluded-param)
2349 (setq output
2350 (delete
2351 excluded-param
2352 output)))
2353 exclusive-group)))
2354 exclusive-groups)
2355 (setq output (org-uniquify
2356 (cons new-param output))))
2357 new-params))
2358 result-params)
2359 output)))
2360 params results exports tangle noweb cache vars shebang comments padline
2361 clearnames)
2363 (mapc
2364 (lambda (plist)
2365 (mapc
2366 (lambda (pair)
2367 (case (car pair)
2368 (:var
2369 (let ((name (if (listp (cdr pair))
2370 (cadr pair)
2371 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
2372 (cdr pair))
2373 (intern (match-string 1 (cdr pair)))))))
2374 (if name
2375 (setq vars
2376 (append
2377 (if (member name (mapcar #'car vars))
2378 (progn
2379 (push name clearnames)
2380 (delq nil
2381 (mapcar
2382 (lambda (p)
2383 (unless (equal (car p) name) p))
2384 vars)))
2385 vars)
2386 (list (cons name pair))))
2387 ;; if no name is given and we already have named variables
2388 ;; then assign to named variables in order
2389 (if (and vars (nth variable-index vars))
2390 (let ((name (car (nth variable-index vars))))
2391 (push name clearnames) ; clear out colnames
2392 ; and rownames
2393 ; for replace vars
2394 (prog1 (setf (cddr (nth variable-index vars))
2395 (concat (symbol-name name) "=" (cdr pair)))
2396 (incf variable-index)))
2397 (error "Variable \"%s\" must be assigned a default value"
2398 (cdr pair))))))
2399 (:results
2400 (setq results (funcall e-merge results-exclusive-groups
2401 results
2402 (split-string
2403 (let ((r (cdr pair)))
2404 (if (stringp r) r (eval r)))))))
2405 (:file
2406 (when (cdr pair)
2407 (setq results (funcall e-merge results-exclusive-groups
2408 results '("file")))
2409 (unless (or (member "both" exports)
2410 (member "none" exports)
2411 (member "code" exports))
2412 (setq exports (funcall e-merge exports-exclusive-groups
2413 exports '("results"))))
2414 (setq params (cons pair (assq-delete-all (car pair) params)))))
2415 (:exports
2416 (setq exports (funcall e-merge exports-exclusive-groups
2417 exports (split-string (cdr pair)))))
2418 (:tangle ;; take the latest -- always overwrite
2419 (setq tangle (or (list (cdr pair)) tangle)))
2420 (:noweb
2421 (setq noweb (funcall e-merge
2422 '(("yes" "no" "tangle" "no-export"
2423 "strip-export" "eval"))
2424 noweb
2425 (split-string (or (cdr pair) "")))))
2426 (:cache
2427 (setq cache (funcall e-merge '(("yes" "no")) cache
2428 (split-string (or (cdr pair) "")))))
2429 (:padline
2430 (setq padline (funcall e-merge '(("yes" "no")) padline
2431 (split-string (or (cdr pair) "")))))
2432 (:shebang ;; take the latest -- always overwrite
2433 (setq shebang (or (list (cdr pair)) shebang)))
2434 (:comments
2435 (setq comments (funcall e-merge '(("yes" "no")) comments
2436 (split-string (or (cdr pair) "")))))
2437 (t ;; replace: this covers e.g. :session
2438 (setq params (cons pair (assq-delete-all (car pair) params))))))
2439 plist))
2440 plists)
2441 (setq vars (reverse vars))
2442 (while vars (setq params (cons (cons :var (cddr (pop vars))) params)))
2443 ;; clear out col-names and row-names for replaced variables
2444 (mapc
2445 (lambda (name)
2446 (mapc
2447 (lambda (param)
2448 (when (assoc param params)
2449 (setf (cdr (assoc param params))
2450 (org-remove-if (lambda (pair) (equal (car pair) name))
2451 (cdr (assoc param params))))
2452 (setf params (org-remove-if (lambda (pair) (and (equal (car pair) param)
2453 (null (cdr pair))))
2454 params))))
2455 (list :colname-names :rowname-names)))
2456 clearnames)
2457 (mapc
2458 (lambda (hd)
2459 (let ((key (intern (concat ":" (symbol-name hd))))
2460 (val (eval hd)))
2461 (setf params (cons (cons key (mapconcat 'identity val " ")) params))))
2462 '(results exports tangle noweb padline cache shebang comments))
2463 params))
2465 (defvar org-babel-use-quick-and-dirty-noweb-expansion nil
2466 "Set to true to use regular expressions to expand noweb references.
2467 This results in much faster noweb reference expansion but does
2468 not properly allow code blocks to inherit the \":noweb-ref\"
2469 header argument from buffer or subtree wide properties.")
2471 (defun org-babel-noweb-p (params context)
2472 "Check if PARAMS require expansion in CONTEXT.
2473 CONTEXT may be one of :tangle, :export or :eval."
2474 (let* (intersect
2475 (intersect (lambda (as bs)
2476 (when as
2477 (if (member (car as) bs)
2478 (car as)
2479 (funcall intersect (cdr as) bs))))))
2480 (funcall intersect (case context
2481 (:tangle '("yes" "tangle" "no-export" "strip-export"))
2482 (:eval '("yes" "no-export" "strip-export" "eval"))
2483 (:export '("yes")))
2484 (split-string (or (cdr (assoc :noweb params)) "")))))
2486 (defun org-babel-expand-noweb-references (&optional info parent-buffer)
2487 "Expand Noweb references in the body of the current source code block.
2489 For example the following reference would be replaced with the
2490 body of the source-code block named 'example-block'.
2492 <<example-block>>
2494 Note that any text preceding the <<foo>> construct on a line will
2495 be interposed between the lines of the replacement text. So for
2496 example if <<foo>> is placed behind a comment, then the entire
2497 replacement text will also be commented.
2499 This function must be called from inside of the buffer containing
2500 the source-code block which holds BODY.
2502 In addition the following syntax can be used to insert the
2503 results of evaluating the source-code block named 'example-block'.
2505 <<example-block()>>
2507 Any optional arguments can be passed to example-block by placing
2508 the arguments inside the parenthesis following the convention
2509 defined by `org-babel-lob'. For example
2511 <<example-block(a=9)>>
2513 would set the value of argument \"a\" equal to \"9\". Note that
2514 these arguments are not evaluated in the current source-code
2515 block but are passed literally to the \"example-block\"."
2516 (let* ((parent-buffer (or parent-buffer (current-buffer)))
2517 (info (or info (org-babel-get-src-block-info 'light)))
2518 (lang (nth 0 info))
2519 (body (nth 1 info))
2520 (ob-nww-start org-babel-noweb-wrap-start)
2521 (ob-nww-end org-babel-noweb-wrap-end)
2522 (comment (string= "noweb" (cdr (assoc :comments (nth 2 info)))))
2523 (rx-prefix (concat "\\(" org-babel-src-name-regexp "\\|"
2524 ":noweb-ref[ \t]+" "\\)"))
2525 (new-body "")
2526 (nb-add (lambda (text) (setq new-body (concat new-body text))))
2527 (c-wrap (lambda (text)
2528 (with-temp-buffer
2529 (funcall (intern (concat lang "-mode")))
2530 (comment-region (point) (progn (insert text) (point)))
2531 (org-babel-trim (buffer-string)))))
2532 index source-name evaluate prefix)
2533 (with-temp-buffer
2534 (org-set-local 'org-babel-noweb-wrap-start ob-nww-start)
2535 (org-set-local 'org-babel-noweb-wrap-end ob-nww-end)
2536 (insert body) (goto-char (point-min))
2537 (setq index (point))
2538 (while (and (re-search-forward (org-babel-noweb-wrap) nil t))
2539 (save-match-data (setf source-name (match-string 1)))
2540 (save-match-data (setq evaluate (string-match "\(.*\)" source-name)))
2541 (save-match-data
2542 (setq prefix
2543 (buffer-substring (match-beginning 0)
2544 (save-excursion
2545 (beginning-of-line 1) (point)))))
2546 ;; add interval to new-body (removing noweb reference)
2547 (goto-char (match-beginning 0))
2548 (funcall nb-add (buffer-substring index (point)))
2549 (goto-char (match-end 0))
2550 (setq index (point))
2551 (funcall
2552 nb-add
2553 (with-current-buffer parent-buffer
2554 (save-restriction
2555 (widen)
2556 (mapconcat ;; Interpose PREFIX between every line.
2557 #'identity
2558 (split-string
2559 (if evaluate
2560 (let ((raw (org-babel-ref-resolve source-name)))
2561 (if (stringp raw) raw (format "%S" raw)))
2563 ;; Retrieve from the library of babel.
2564 (nth 2 (assoc (intern source-name)
2565 org-babel-library-of-babel))
2566 ;; Return the contents of headlines literally.
2567 (save-excursion
2568 (when (org-babel-ref-goto-headline-id source-name)
2569 (org-babel-ref-headline-body)))
2570 ;; Find the expansion of reference in this buffer.
2571 (let ((rx (concat rx-prefix source-name "[ \t\n]"))
2572 expansion)
2573 (save-excursion
2574 (goto-char (point-min))
2575 (if org-babel-use-quick-and-dirty-noweb-expansion
2576 (while (re-search-forward rx nil t)
2577 (let* ((i (org-babel-get-src-block-info 'light))
2578 (body (org-babel-expand-noweb-references i))
2579 (sep (or (cdr (assoc :noweb-sep (nth 2 i)))
2580 "\n"))
2581 (full (if comment
2582 (let ((cs (org-babel-tangle-comment-links i)))
2583 (concat (funcall c-wrap (car cs)) "\n"
2584 body "\n"
2585 (funcall c-wrap (cadr cs))))
2586 body)))
2587 (setq expansion (cons sep (cons full expansion)))))
2588 (org-babel-map-src-blocks nil
2589 (let ((i (org-babel-get-src-block-info 'light)))
2590 (when (equal (or (cdr (assoc :noweb-ref (nth 2 i)))
2591 (nth 4 i))
2592 source-name)
2593 (let* ((body (org-babel-expand-noweb-references i))
2594 (sep (or (cdr (assoc :noweb-sep (nth 2 i)))
2595 "\n"))
2596 (full (if comment
2597 (let ((cs (org-babel-tangle-comment-links i)))
2598 (concat (funcall c-wrap (car cs)) "\n"
2599 body "\n"
2600 (funcall c-wrap (cadr cs))))
2601 body)))
2602 (setq expansion
2603 (cons sep (cons full expansion)))))))))
2604 (and expansion
2605 (mapconcat #'identity (nreverse (cdr expansion)) "")))
2606 ;; Possibly raise an error if named block doesn't exist.
2607 (if (member lang org-babel-noweb-error-langs)
2608 (error "%s" (concat
2609 (org-babel-noweb-wrap source-name)
2610 "could not be resolved (see "
2611 "`org-babel-noweb-error-langs')"))
2612 "")))
2613 "[\n\r]") (concat "\n" prefix))))))
2614 (funcall nb-add (buffer-substring index (point-max))))
2615 new-body))
2617 (defun org-babel-script-escape (str &optional force)
2618 "Safely convert tables into elisp lists."
2619 (let ((escaped
2620 (if (or force
2621 (and (stringp str)
2622 (> (length str) 2)
2623 (or (and (string-equal "[" (substring str 0 1))
2624 (string-equal "]" (substring str -1)))
2625 (and (string-equal "{" (substring str 0 1))
2626 (string-equal "}" (substring str -1)))
2627 (and (string-equal "(" (substring str 0 1))
2628 (string-equal ")" (substring str -1))))))
2629 (org-babel-read
2630 (concat
2632 (let (in-single in-double out)
2633 (mapc
2634 (lambda (ch)
2635 (setq
2637 (case ch
2638 (91 (if (or in-double in-single) ; [
2639 (cons 91 out)
2640 (cons 40 out)))
2641 (93 (if (or in-double in-single) ; ]
2642 (cons 93 out)
2643 (cons 41 out)))
2644 (123 (if (or in-double in-single) ; {
2645 (cons 123 out)
2646 (cons 40 out)))
2647 (125 (if (or in-double in-single) ; }
2648 (cons 125 out)
2649 (cons 41 out)))
2650 (44 (if (or in-double in-single) ; ,
2651 (cons 44 out) (cons 32 out)))
2652 (39 (if in-double ; '
2653 (cons 39 out)
2654 (setq in-single (not in-single)) (cons 34 out)))
2655 (34 (if in-single ; "
2656 (append (list 34 32) out)
2657 (setq in-double (not in-double)) (cons 34 out)))
2658 (t (cons ch out)))))
2659 (string-to-list str))
2660 (apply #'string (reverse out)))))
2661 str)))
2662 (condition-case nil (org-babel-read escaped) (error escaped))))
2664 (defun org-babel-read (cell &optional inhibit-lisp-eval)
2665 "Convert the string value of CELL to a number if appropriate.
2666 Otherwise if cell looks like lisp (meaning it starts with a
2667 \"(\", \"'\", \"`\" or a \"[\") then read it as lisp,
2668 otherwise return it unmodified as a string. Optional argument
2669 NO-LISP-EVAL inhibits lisp evaluation for situations in which is
2670 it not appropriate."
2671 (if (and (stringp cell) (not (equal cell "")))
2672 (or (org-babel-number-p cell)
2673 (if (and (not inhibit-lisp-eval)
2674 (or (member (substring cell 0 1) '("(" "'" "`" "["))
2675 (string= cell "*this*")))
2676 (eval (read cell))
2677 (if (string= (substring cell 0 1) "\"")
2678 (read cell)
2679 (progn (set-text-properties 0 (length cell) nil cell) cell))))
2680 cell))
2682 (defun org-babel-number-p (string)
2683 "If STRING represents a number return its value."
2684 (if (and (string-match "[0-9]+" string)
2685 (string-match "^-?[0-9]*\\.?[0-9]*$" string)
2686 (= (length (substring string (match-beginning 0)
2687 (match-end 0)))
2688 (length string)))
2689 (string-to-number string)))
2691 (defun org-babel-import-elisp-from-file (file-name &optional separator)
2692 "Read the results located at FILE-NAME into an elisp table.
2693 If the table is trivial, then return it as a scalar."
2694 (let (result)
2695 (save-window-excursion
2696 (with-temp-buffer
2697 (condition-case err
2698 (progn
2699 (org-table-import file-name separator)
2700 (delete-file file-name)
2701 (setq result (mapcar (lambda (row)
2702 (mapcar #'org-babel-string-read row))
2703 (org-table-to-lisp))))
2704 (error (message "Error reading results: %s" err) nil)))
2705 (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
2706 (if (consp (car result))
2707 (if (null (cdr (car result)))
2708 (caar result)
2709 result)
2710 (car result))
2711 result))))
2713 (defun org-babel-string-read (cell)
2714 "Strip nested \"s from around strings."
2715 (org-babel-read (or (and (stringp cell)
2716 (string-match "\\\"\\(.+\\)\\\"" cell)
2717 (match-string 1 cell))
2718 cell) t))
2720 (defun org-babel-chomp (string &optional regexp)
2721 "Strip trailing spaces and carriage returns from STRING.
2722 Default regexp used is \"[ \f\t\n\r\v]\" but can be
2723 overwritten by specifying a regexp as a second argument."
2724 (let ((regexp (or regexp "[ \f\t\n\r\v]")))
2725 (while (and (> (length string) 0)
2726 (string-match regexp (substring string -1)))
2727 (setq string (substring string 0 -1)))
2728 string))
2730 (defun org-babel-trim (string &optional regexp)
2731 "Strip leading and trailing spaces and carriage returns from STRING.
2732 Like `org-babel-chomp' only it runs on both the front and back
2733 of the string."
2734 (org-babel-chomp (org-reverse-string
2735 (org-babel-chomp (org-reverse-string string) regexp))
2736 regexp))
2738 (defun org-babel-tramp-handle-call-process-region
2739 (start end program &optional delete buffer display &rest args)
2740 "Use Tramp to handle `call-process-region'.
2741 Fixes a bug in `tramp-handle-call-process-region'."
2742 (if (and (featurep 'tramp) (file-remote-p default-directory))
2743 (let ((tmpfile (tramp-compat-make-temp-file "")))
2744 (write-region start end tmpfile)
2745 (when delete (delete-region start end))
2746 (unwind-protect
2747 ;; (apply 'call-process program tmpfile buffer display args)
2748 ;; bug in tramp
2749 (apply 'process-file program tmpfile buffer display args)
2750 (delete-file tmpfile)))
2751 ;; org-babel-call-process-region-original is the original emacs
2752 ;; definition. It is in scope from the let binding in
2753 ;; org-babel-execute-src-block
2754 (apply org-babel-call-process-region-original
2755 start end program delete buffer display args)))
2757 (defun org-babel-local-file-name (file)
2758 "Return the local name component of FILE."
2759 (or (file-remote-p file 'localname) file))
2761 (defun org-babel-process-file-name (name &optional no-quote-p)
2762 "Prepare NAME to be used in an external process.
2763 If NAME specifies a remote location, the remote portion of the
2764 name is removed, since in that case the process will be executing
2765 remotely. The file name is then processed by `expand-file-name'.
2766 Unless second argument NO-QUOTE-P is non-nil, the file name is
2767 additionally processed by `shell-quote-argument'"
2768 (let ((f (org-babel-local-file-name (expand-file-name name))))
2769 (if no-quote-p f (shell-quote-argument f))))
2771 (defvar org-babel-temporary-directory)
2772 (unless (or noninteractive (boundp 'org-babel-temporary-directory))
2773 (defvar org-babel-temporary-directory
2774 (or (and (boundp 'org-babel-temporary-directory)
2775 (file-exists-p org-babel-temporary-directory)
2776 org-babel-temporary-directory)
2777 (make-temp-file "babel-" t))
2778 "Directory to hold temporary files created to execute code blocks.
2779 Used by `org-babel-temp-file'. This directory will be removed on
2780 Emacs shutdown."))
2782 (defcustom org-babel-remote-temporary-directory "/tmp/"
2783 "Directory to hold temporary files on remote hosts."
2784 :group 'org-babel
2785 :type 'string)
2787 (defmacro org-babel-result-cond (result-params scalar-form &rest table-forms)
2788 "Call the code to parse raw string results according to RESULT-PARAMS."
2789 (declare (indent 1)
2790 (debug (form form &rest form)))
2791 (org-with-gensyms (params)
2792 `(let ((,params ,result-params))
2793 (unless (member "none" ,params)
2794 (if (or (member "scalar" ,params)
2795 (member "verbatim" ,params)
2796 (member "html" ,params)
2797 (member "code" ,params)
2798 (member "pp" ,params)
2799 (and (or (member "output" ,params)
2800 (member "raw" ,params)
2801 (member "org" ,params)
2802 (member "drawer" ,params))
2803 (not (member "table" ,params))))
2804 ,scalar-form
2805 ,@table-forms)))))
2806 (def-edebug-spec org-babel-result-cond (form form body))
2808 (defun org-babel-temp-file (prefix &optional suffix)
2809 "Create a temporary file in the `org-babel-temporary-directory'.
2810 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2811 value of `temporary-file-directory' temporarily set to the value
2812 of `org-babel-temporary-directory'."
2813 (if (file-remote-p default-directory)
2814 (let ((prefix
2815 (concat (file-remote-p default-directory)
2816 (expand-file-name
2817 prefix org-babel-remote-temporary-directory))))
2818 (make-temp-file prefix nil suffix))
2819 (let ((temporary-file-directory
2820 (or (and (boundp 'org-babel-temporary-directory)
2821 (file-exists-p org-babel-temporary-directory)
2822 org-babel-temporary-directory)
2823 temporary-file-directory)))
2824 (make-temp-file prefix nil suffix))))
2826 (defun org-babel-remove-temporary-directory ()
2827 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2828 (when (and (boundp 'org-babel-temporary-directory)
2829 (file-exists-p org-babel-temporary-directory))
2830 ;; taken from `delete-directory' in files.el
2831 (condition-case nil
2832 (progn
2833 (mapc (lambda (file)
2834 ;; This test is equivalent to
2835 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2836 ;; but more efficient
2837 (if (eq t (car (file-attributes file)))
2838 (delete-directory file)
2839 (delete-file file)))
2840 ;; We do not want to delete "." and "..".
2841 (directory-files org-babel-temporary-directory 'full
2842 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2843 (delete-directory org-babel-temporary-directory))
2844 (error
2845 (message "Failed to remove temporary Org-babel directory %s"
2846 (if (boundp 'org-babel-temporary-directory)
2847 org-babel-temporary-directory
2848 "[directory not defined]"))))))
2850 (add-hook 'kill-emacs-hook 'org-babel-remove-temporary-directory)
2852 (defun org-babel-one-header-arg-safe-p (pair safe-list)
2853 "Determine if the PAIR is a safe babel header arg according to SAFE-LIST.
2855 For the format of SAFE-LIST, see `org-babel-safe-header-args'."
2856 (and (consp pair)
2857 (keywordp (car pair))
2858 (stringp (cdr pair))
2860 (memq (car pair) safe-list)
2861 (let ((entry (assq (car pair) safe-list)))
2862 (and entry
2863 (consp entry)
2864 (cond ((functionp (cdr entry))
2865 (funcall (cdr entry) (cdr pair)))
2866 ((listp (cdr entry))
2867 (member (cdr pair) (cdr entry)))
2868 (t nil)))))))
2870 (provide 'ob-core)
2872 ;; Local variables:
2873 ;; generated-autoload-file: "org-loaddefs.el"
2874 ;; End:
2876 ;;; ob-core.el ends here