Don't wrap org-entry-get into condition-case.
[org-mode.git] / lisp / ob.el
blob44808faabf1f3846a8a7c26161c85a45e088ece3
1 ;;; ob.el --- working with code blocks in org-mode
3 ;; Copyright (C) 2009, 2010 Free Software Foundation, Inc.
5 ;; Author: Eric Schulte, Dan Davison
6 ;; Keywords: literate programming, reproducible research
7 ;; Homepage: http://orgmode.org
8 ;; Version: 7.4
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 ;;; Commentary:
27 ;; See the online documentation for more information
29 ;; http://orgmode.org/worg/org-contrib/babel/
31 ;;; Code:
32 (eval-when-compile
33 (require 'cl))
34 (require 'ob-eval)
35 (require 'org-macs)
37 (defvar org-babel-call-process-region-original)
38 (declare-function show-all "outline" ())
39 (declare-function tramp-compat-make-temp-file "tramp-compat"
40 (filename &optional dir-flag))
41 (declare-function tramp-dissect-file-name "tramp" (name &optional nodefault))
42 (declare-function tramp-file-name-user "tramp" (vec))
43 (declare-function tramp-file-name-host "tramp" (vec))
44 (declare-function with-parsed-tramp-file-name "tramp" (filename var &rest body))
45 (declare-function org-icompleting-read "org" (&rest args))
46 (declare-function org-edit-src-code "org-src"
47 (&optional context code edit-buffer-name quietp))
48 (declare-function org-edit-src-exit "org-src" (&optional context))
49 (declare-function org-open-at-point "org" (&optional in-emacs reference-buffer))
50 (declare-function org-save-outline-visibility "org" (use-markers &rest body))
51 (declare-function org-outline-overlay-data "org" (&optional use-markers))
52 (declare-function org-set-outline-overlay-data "org" (data))
53 (declare-function org-narrow-to-subtree "org" ())
54 (declare-function org-entry-get "org"
55 (pom property &optional inherit literal-nil))
56 (declare-function org-make-options-regexp "org" (kwds &optional extra))
57 (declare-function org-do-remove-indentation "org" (&optional n))
58 (declare-function org-show-context "org" (&optional key))
59 (declare-function org-at-table-p "org" (&optional table-type))
60 (declare-function org-cycle "org" (&optional arg))
61 (declare-function org-uniquify "org" (list))
62 (declare-function org-current-level "org" ())
63 (declare-function org-table-import "org-table" (file arg))
64 (declare-function org-add-hook "org-compat"
65 (hook function &optional append local))
66 (declare-function org-table-align "org-table" ())
67 (declare-function org-table-end "org-table" (&optional table-type))
68 (declare-function orgtbl-to-generic "org-table" (table params))
69 (declare-function orgtbl-to-orgtbl "org-table" (table params))
70 (declare-function org-babel-lob-get-info "ob-lob" nil)
71 (declare-function org-babel-ref-split-args "ob-ref" (arg-string))
72 (declare-function org-babel-ref-parse "ob-ref" (assignment))
73 (declare-function org-babel-ref-resolve "ob-ref" (ref))
74 (declare-function org-babel-lob-execute-maybe "ob-lob" ())
75 (declare-function org-number-sequence "org-compat" (from &optional to inc))
76 (declare-function org-in-item-p "org-list" ())
77 (declare-function org-list-parse-list "org-list" (&optional delete))
78 (declare-function org-list-to-generic "org-list" (LIST PARAMS))
79 (declare-function org-list-bottom-point "org-list" ())
81 (defgroup org-babel nil
82 "Code block evaluation and management in `org-mode' documents."
83 :tag "Babel"
84 :group 'org)
86 (defcustom org-confirm-babel-evaluate t
87 "Confirm before evaluation.
88 Require confirmation before interactively evaluating code
89 blocks in Org-mode buffers. The default value of this variable
90 is t, meaning confirmation is required for any code block
91 evaluation. This variable can be set to nil to inhibit any
92 future confirmation requests. This variable can also be set to a
93 function which takes two arguments the language of the code block
94 and the body of the code block. Such a function should then
95 return a non-nil value if the user should be prompted for
96 execution or nil if no prompt is required.
98 Warning: Disabling confirmation may result in accidental
99 evaluation of potentially harmful code. It may be advisable
100 remove code block execution from C-c C-c as further protection
101 against accidental code block evaluation. The
102 `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
103 remove code block execution from the C-c C-c keybinding."
104 :group 'org-babel
105 :type '(choice boolean function))
106 ;; don't allow this variable to be changed through file settings
107 (put 'org-confirm-babel-evaluate 'safe-local-variable (lambda (x) (eq x t)))
109 (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
110 "Remove code block evaluation from the C-c C-c key binding."
111 :group 'org-babel
112 :type 'boolean)
114 (defvar org-babel-src-name-regexp
115 "^[ \t]*#\\+\\(srcname\\|source\\|function\\):[ \t]*"
116 "Regular expression used to match a source name line.")
118 (defvar org-babel-multi-line-header-regexp
119 "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
120 "Regular expression used to match multi-line header arguments.")
122 (defvar org-babel-src-name-w-name-regexp
123 (concat org-babel-src-name-regexp
124 "\\("
125 org-babel-multi-line-header-regexp
126 "\\)*"
127 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)")
128 "Regular expression matching source name lines with a name.")
130 (defvar org-babel-src-block-regexp
131 (concat
132 ;; (1) indentation (2) lang
133 "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
134 ;; (3) switches
135 "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
136 ;; (4) header arguments
137 "\\([^\n]*\\)\n"
138 ;; (5) body
139 "\\([^\000]+?\n\\)[ \t]*#\\+end_src")
140 "Regexp used to identify code blocks.")
142 (defvar org-babel-inline-src-block-regexp
143 (concat
144 ;; (1) replacement target (2) lang
145 "[^-[:alnum:]]\\(src_\\([^ \f\t\n\r\v]+\\)"
146 ;; (3,4) (unused, headers)
147 "\\(\\|\\[\\(.*?\\)\\]\\)"
148 ;; (5) body
149 "{\\([^\f\n\r\v]+?\\)}\\)")
150 "Regexp used to identify inline src-blocks.")
152 (defun org-babel-get-header (params key &optional others)
153 "Select only header argument of type KEY from a list.
154 Optional argument OTHERS indicates that only the header that do
155 not match KEY should be returned."
156 (delq nil
157 (mapcar
158 (lambda (p) (when (funcall (if others #'not #'identity) (eq (car p) key)) p))
159 params)))
161 (defun org-babel-get-src-block-info (&optional light)
162 "Get information on the current source block.
164 Optional argument LIGHT does not resolve remote variable
165 references; a process which could likely result in the execution
166 of other code blocks.
168 Returns a list
169 (language body header-arguments-alist switches name indent)."
170 (let ((case-fold-search t) head info name indent)
171 ;; full code block
172 (if (setq head (org-babel-where-is-src-block-head))
173 (save-excursion
174 (goto-char head)
175 (setq info (org-babel-parse-src-block-match))
176 (setq indent (car (last info)))
177 (setq info (butlast info))
178 (while (and (forward-line -1)
179 (looking-at org-babel-multi-line-header-regexp))
180 (setf (nth 2 info)
181 (org-babel-merge-params
182 (nth 2 info)
183 (org-babel-parse-header-arguments (match-string 1)))))
184 (when (looking-at org-babel-src-name-w-name-regexp)
185 (setq name (org-babel-clean-text-properties (match-string 4)))
186 (when (match-string 6)
187 (setf (nth 2 info) ;; merge functional-syntax vars and header-args
188 (org-babel-merge-params
189 (mapcar (lambda (ref) (cons :var ref))
190 (org-babel-ref-split-args (match-string 6)))
191 (nth 2 info))))))
192 ;; inline source block
193 (when (save-excursion (re-search-backward "[ \f\t\n\r\v]" nil t)
194 (looking-at org-babel-inline-src-block-regexp))
195 (setq info (org-babel-parse-inline-src-block-match))))
196 ;; resolve variable references and add summary parameters
197 (when (and info (not light))
198 (setf (nth 2 info) (org-babel-process-params (nth 2 info))))
199 (when info (append info (list name indent)))))
201 (defun org-babel-confirm-evaluate (info)
202 "Confirm evaluation of the code block INFO.
203 This behavior can be suppressed by setting the value of
204 `org-confirm-babel-evaluate' to nil, in which case all future
205 interactive code block evaluations will proceed without any
206 confirmation from the user.
208 Note disabling confirmation may result in accidental evaluation
209 of potentially harmful code."
210 (let* ((eval (or (cdr (assoc :eval (nth 2 info)))
211 (when (assoc :noeval (nth 2 info)) "no")))
212 (query (cond ((equal eval "query") t)
213 ((functionp org-confirm-babel-evaluate)
214 (funcall org-confirm-babel-evaluate
215 (nth 0 info) (nth 1 info)))
216 (t org-confirm-babel-evaluate))))
217 (if (or (equal eval "never") (equal eval "no")
218 (and query
219 (not (yes-or-no-p
220 (format "Evaluate this%scode block%son your system? "
221 (if info (format " %s " (nth 0 info)) " ")
222 (if (nth 4 info)
223 (format " (%s) " (nth 4 info)) " "))))))
224 (prog1 nil (message "Evaluation %s"
225 (if (or (equal eval "never") (equal eval "no"))
226 "Disabled" "Aborted")))
227 t)))
229 ;;;###autoload
230 (defun org-babel-execute-safely-maybe ()
231 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
232 (org-babel-execute-maybe)))
234 (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-execute-safely-maybe)
236 ;;;###autoload
237 (defun org-babel-execute-maybe ()
238 (interactive)
239 (or (org-babel-execute-src-block-maybe)
240 (org-babel-lob-execute-maybe)))
242 (defun org-babel-execute-src-block-maybe ()
243 "Conditionally execute a source block.
244 Detect if this is context for a Babel src-block and if so
245 then run `org-babel-execute-src-block'."
246 (interactive)
247 (let ((info (org-babel-get-src-block-info)))
248 (if info
249 (progn (org-babel-eval-wipe-error-buffer)
250 (org-babel-execute-src-block current-prefix-arg info) t) nil)))
252 ;;;###autoload
253 (defun org-babel-expand-src-block-maybe ()
254 "Conditionally expand a source block.
255 Detect if this is context for a org-babel src-block and if so
256 then run `org-babel-expand-src-block'."
257 (interactive)
258 (let ((info (org-babel-get-src-block-info)))
259 (if info
260 (progn (org-babel-expand-src-block current-prefix-arg info) t)
261 nil)))
263 ;;;###autoload
264 (defun org-babel-load-in-session-maybe ()
265 "Conditionally load a source block in a session.
266 Detect if this is context for a org-babel src-block and if so
267 then run `org-babel-load-in-session'."
268 (interactive)
269 (let ((info (org-babel-get-src-block-info)))
270 (if info
271 (progn (org-babel-load-in-session current-prefix-arg info) t)
272 nil)))
274 (add-hook 'org-metaup-hook 'org-babel-load-in-session-maybe)
276 ;;;###autoload
277 (defun org-babel-pop-to-session-maybe ()
278 "Conditionally pop to a session.
279 Detect if this is context for a org-babel src-block and if so
280 then run `org-babel-pop-to-session'."
281 (interactive)
282 (let ((info (org-babel-get-src-block-info)))
283 (if info (progn (org-babel-pop-to-session current-prefix-arg info) t) nil)))
285 (add-hook 'org-metadown-hook 'org-babel-pop-to-session-maybe)
287 (defconst org-babel-header-arg-names
288 '(cache cmdline colnames dir exports file noweb results
289 session tangle var eval noeval comments no-expand)
290 "Common header arguments used by org-babel.
291 Note that individual languages may define their own language
292 specific header arguments as well.")
294 (defvar org-babel-default-header-args
295 '((:session . "none") (:results . "replace") (:exports . "code")
296 (:cache . "no") (:noweb . "no") (:hlines . "no") (:tangle . "no"))
297 "Default arguments to use when evaluating a source block.")
299 (defvar org-babel-default-inline-header-args
300 '((:session . "none") (:results . "replace") (:exports . "results"))
301 "Default arguments to use when evaluating an inline source block.")
303 (defvar org-babel-current-buffer-properties nil
304 "Local cache for buffer properties.")
305 (make-variable-buffer-local 'org-babel-current-buffer-properties)
307 (defvar org-babel-result-regexp
308 "^[ \t]*#\\+res\\(ults\\|name\\)\\(\\[\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*"
309 "Regular expression used to match result lines.
310 If the results are associated with a hash key then the hash will
311 be saved in the second match data.")
313 (defvar org-babel-result-w-name-regexp
314 (concat org-babel-result-regexp
315 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
317 (defvar org-babel-min-lines-for-block-output 10
318 "The minimum number of lines for block output.
319 If number of lines of output is equal to or exceeds this
320 value, the output is placed in a #+begin_example...#+end_example
321 block. Otherwise the output is marked as literal by inserting
322 colons at the starts of the lines. This variable only takes
323 effect if the :results output option is in effect.")
325 (defvar org-babel-noweb-error-langs nil
326 "Languages for which Babel will raise literate programming errors.
327 List of languages for which errors should be raised when the
328 source code block satisfying a noweb reference in this language
329 can not be resolved.")
331 (defvar org-babel-hash-show 4
332 "Number of initial characters to show of a hidden results hash.")
334 (defvar org-babel-after-execute-hook nil
335 "Hook for functions to be called after `org-babel-execute-src-block'")
336 (defun org-babel-named-src-block-regexp-for-name (name)
337 "This generates a regexp used to match a src block named NAME."
338 (concat org-babel-src-name-regexp (regexp-quote name) "[ \t\n]*"
339 (substring org-babel-src-block-regexp 1)))
341 ;;; functions
342 (defvar call-process-region)
343 ;;;###autoload
345 (defun org-babel-execute-src-block (&optional arg info params)
346 "Execute the current source code block.
347 Insert the results of execution into the buffer. Source code
348 execution and the collection and formatting of results can be
349 controlled through a variety of header arguments.
351 With prefix argument ARG, force re-execution even if a an
352 existing result cached in the buffer would otherwise have been
353 returned.
355 Optionally supply a value for INFO in the form returned by
356 `org-babel-get-src-block-info'.
358 Optionally supply a value for PARAMS which will be merged with
359 the header arguments specified at the front of the source code
360 block."
361 (interactive)
362 (let ((info (or info (org-babel-get-src-block-info))))
363 (when (org-babel-confirm-evaluate info)
364 (let* ((lang (nth 0 info))
365 (params (if params
366 (org-babel-process-params
367 (org-babel-merge-params (nth 2 info) params))
368 (nth 2 info)))
369 (cache? (and (not arg) (cdr (assoc :cache params))
370 (string= "yes" (cdr (assoc :cache params)))))
371 (result-params (cdr (assoc :result-params params)))
372 (new-hash (when cache? (org-babel-sha1-hash info)))
373 (old-hash (when cache? (org-babel-result-hash info)))
374 (body (setf (nth 1 info)
375 (let ((noweb (cdr (assoc :noweb params))))
376 (if (and noweb
377 (or (string= "yes" noweb)
378 (string= "tangle" noweb)))
379 (org-babel-expand-noweb-references info)
380 (nth 1 info)))))
381 (dir (cdr (assoc :dir params)))
382 (default-directory
383 (or (and dir (file-name-as-directory dir)) default-directory))
384 (org-babel-call-process-region-original
385 (if (boundp 'org-babel-call-process-region-original)
386 org-babel-call-process-region-original
387 (symbol-function 'call-process-region)))
388 (indent (car (last info)))
389 result cmd)
390 (unwind-protect
391 (flet ((call-process-region (&rest args)
392 (apply 'org-babel-tramp-handle-call-process-region args)))
393 (flet ((lang-check (f)
394 (let ((f (intern (concat "org-babel-execute:" f))))
395 (when (fboundp f) f))))
396 (setq cmd
397 (or (lang-check lang)
398 (lang-check (symbol-name
399 (cdr (assoc lang org-src-lang-modes))))
400 (error "No org-babel-execute function for %s!" lang))))
401 (if (and (not arg) new-hash (equal new-hash old-hash))
402 (save-excursion ;; return cached result
403 (goto-char (org-babel-where-is-src-block-result nil info))
404 (end-of-line 1) (forward-char 1)
405 (setq result (org-babel-read-result))
406 (message (replace-regexp-in-string
407 "%" "%%" (format "%S" result))) result)
408 (message "executing %s code block%s..."
409 (capitalize lang)
410 (if (nth 4 info) (format " (%s)" (nth 4 info)) ""))
411 (setq result
412 ((lambda (result)
413 (if (and (eq (cdr (assoc :result-type params)) 'value)
414 (or (member "vector" result-params)
415 (member "table" result-params))
416 (not (listp result)))
417 (list (list result)) result))
418 (funcall cmd body params)))
419 ;; if non-empty result and :file then write to :file
420 (when (cdr (assoc :file params))
421 (when result
422 (with-temp-file (cdr (assoc :file params))
423 (insert
424 (org-babel-format-result
425 result (cdr (assoc :sep (nth 2 info)))))))
426 (setq result (cdr (assoc :file params))))
427 (org-babel-insert-result
428 result result-params info new-hash indent lang)
429 (run-hooks 'org-babel-after-execute-hook)
430 result))
431 (setq call-process-region 'org-babel-call-process-region-original))))))
433 (defun org-babel-expand-body:generic (body params &optional var-lines)
434 "Expand BODY with PARAMS.
435 Expand a block of code with org-babel according to it's header
436 arguments. This generic implementation of body expansion is
437 called for languages which have not defined their own specific
438 org-babel-expand-body:lang function."
439 (mapconcat #'identity (append var-lines (list body)) "\n"))
441 ;;;###autoload
442 (defun org-babel-expand-src-block (&optional arg info params)
443 "Expand the current source code block.
444 Expand according to the source code block's header
445 arguments and pop open the results in a preview buffer."
446 (interactive)
447 (let* ((info (or info (org-babel-get-src-block-info)))
448 (lang (nth 0 info))
449 (params (setf (nth 2 info)
450 (sort (org-babel-merge-params (nth 2 info) params)
451 (lambda (el1 el2) (string< (symbol-name (car el1))
452 (symbol-name (car el2)))))))
453 (body (setf (nth 1 info)
454 (if (and (cdr (assoc :noweb params))
455 (string= "yes" (cdr (assoc :noweb params))))
456 (org-babel-expand-noweb-references info) (nth 1 info))))
457 (expand-cmd (intern (concat "org-babel-expand-body:" lang)))
458 (assignments-cmd (intern (concat "org-babel-variable-assignments:" lang)))
459 (expanded
460 (if (fboundp expand-cmd) (funcall expand-cmd body params)
461 (org-babel-expand-body:generic
462 body params (and (fboundp assignments-cmd) (funcall assignments-cmd params))))))
463 (org-edit-src-code
464 nil expanded (concat "*Org-Babel Preview " (buffer-name) "[ " lang " ]*"))))
466 ;;;###autoload
467 (defun org-babel-load-in-session (&optional arg info)
468 "Load the body of the current source-code block.
469 Evaluate the header arguments for the source block before
470 entering the session. After loading the body this pops open the
471 session."
472 (interactive)
473 (let* ((info (or info (org-babel-get-src-block-info)))
474 (lang (nth 0 info))
475 (params (nth 2 info))
476 (body (setf (nth 1 info)
477 (if (and (cdr (assoc :noweb params))
478 (string= "yes" (cdr (assoc :noweb params))))
479 (org-babel-expand-noweb-references info)
480 (nth 1 info))))
481 (session (cdr (assoc :session params)))
482 (dir (cdr (assoc :dir params)))
483 (default-directory
484 (or (and dir (file-name-as-directory dir)) default-directory))
485 (cmd (intern (concat "org-babel-load-session:" lang))))
486 (unless (fboundp cmd)
487 (error "No org-babel-load-session function for %s!" lang))
488 (pop-to-buffer (funcall cmd session body params))
489 (end-of-line 1)))
491 ;;;###autoload
492 (defun org-babel-initiate-session (&optional arg info)
493 "Initiate session for current code block.
494 If called with a prefix argument then resolve any variable
495 references in the header arguments and assign these variables in
496 the session. Copy the body of the code block to the kill ring."
497 (interactive "P")
498 (let* ((info (or info (org-babel-get-src-block-info (not arg))))
499 (lang (nth 0 info))
500 (body (nth 1 info))
501 (params (nth 2 info))
502 (session (cdr (assoc :session params)))
503 (dir (cdr (assoc :dir params)))
504 (default-directory
505 (or (and dir (file-name-as-directory dir)) default-directory))
506 (init-cmd (intern (format "org-babel-%s-initiate-session" lang)))
507 (prep-cmd (intern (concat "org-babel-prep-session:" lang))))
508 (if (and (stringp session) (string= session "none"))
509 (error "This block is not using a session!"))
510 (unless (fboundp init-cmd)
511 (error "No org-babel-initiate-session function for %s!" lang))
512 (with-temp-buffer (insert (org-babel-trim body))
513 (copy-region-as-kill (point-min) (point-max)))
514 (when arg
515 (unless (fboundp prep-cmd)
516 (error "No org-babel-prep-session function for %s!" lang))
517 (funcall prep-cmd session params))
518 (funcall init-cmd session params)))
520 ;;;###autoload
521 (defun org-babel-switch-to-session (&optional arg info)
522 "Switch to the session of the current code block.
523 Uses `org-babel-initiate-session' to start the session. If called
524 with a prefix argument then this is passed on to
525 `org-babel-initiate-session'."
526 (interactive "P")
527 (pop-to-buffer (org-babel-initiate-session arg info))
528 (end-of-line 1))
530 (defalias 'org-babel-pop-to-session 'org-babel-switch-to-session)
532 ;;;###autoload
533 (defun org-babel-switch-to-session-with-code (&optional arg info)
534 "Switch to code buffer and display session."
535 (interactive "P")
536 (flet ((swap-windows
538 (let ((other-window-buffer (window-buffer (next-window))))
539 (set-window-buffer (next-window) (current-buffer))
540 (set-window-buffer (selected-window) other-window-buffer))
541 (other-window 1)))
542 (let ((info (org-babel-get-src-block-info))
543 (org-src-window-setup 'reorganize-frame))
544 (save-excursion
545 (org-babel-switch-to-session arg info))
546 (org-edit-src-code))
547 (swap-windows)))
549 (defmacro org-babel-do-in-edit-buffer (&rest body)
550 "Evaluate BODY in edit buffer if there is a code block at point.
551 Return t if a code block was found at point, nil otherwise."
552 `(let ((org-src-window-setup 'switch-invisibly))
553 (when (and (org-babel-where-is-src-block-head)
554 (org-edit-src-code nil nil nil))
555 (unwind-protect (progn ,@body)
556 (if (org-bound-and-true-p org-edit-src-from-org-mode)
557 (org-edit-src-exit)))
558 t)))
560 (defun org-babel-do-key-sequence-in-edit-buffer (key)
561 "Read key sequence and execute the command in edit buffer.
562 Enter a key sequence to be executed in the language major-mode
563 edit buffer. For example, TAB will alter the contents of the
564 Org-mode code block according to the effect of TAB in the
565 language major-mode buffer. For languages that support
566 interactive sessions, this can be used to send code from the Org
567 buffer to the session for evaluation using the native major-mode
568 evaluation mechanisms."
569 (interactive "kEnter key-sequence to execute in edit buffer: ")
570 (org-babel-do-in-edit-buffer
571 (call-interactively
572 (key-binding (or key (read-key-sequence nil))))))
574 (defvar org-bracket-link-regexp)
575 ;;;###autoload
576 (defun org-babel-open-src-block-result (&optional re-run)
577 "If `point' is on a src block then open the results of the
578 source code block, otherwise return nil. With optional prefix
579 argument RE-RUN the source-code block is evaluated even if
580 results already exist."
581 (interactive "P")
582 (let ((info (org-babel-get-src-block-info)))
583 (when info
584 (save-excursion
585 ;; go to the results, if there aren't any then run the block
586 (goto-char (or (and (not re-run) (org-babel-where-is-src-block-result))
587 (progn (org-babel-execute-src-block)
588 (org-babel-where-is-src-block-result))))
589 (end-of-line 1)
590 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
591 ;; open the results
592 (if (looking-at org-bracket-link-regexp)
593 ;; file results
594 (org-open-at-point)
595 (let ((r (org-babel-format-result
596 (org-babel-read-result) (cdr (assoc :sep (nth 2 info))))))
597 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
598 (delete-region (point-min) (point-max))
599 (insert r)))
600 t))))
602 ;;;###autoload
603 (defmacro org-babel-map-src-blocks (file &rest body)
604 "Evaluate BODY forms on each source-block in FILE.
605 If FILE is nil evaluate BODY forms on source blocks in current
606 buffer. During evaluation of BODY the following local variables
607 are set relative to the currently matched code block.
609 full-block ------- string holding the entirety of the code block
610 beg-block -------- point at the beginning of the code block
611 end-block -------- point at the end of the matched code block
612 lang ------------- string holding the language of the code block
613 beg-lang --------- point at the beginning of the lang
614 end-lang --------- point at the end of the lang
615 switches --------- string holding the switches
616 beg-switches ----- point at the beginning of the switches
617 end-switches ----- point at the end of the switches
618 header-args ------ string holding the header-args
619 beg-header-args -- point at the beginning of the header-args
620 end-header-args -- point at the end of the header-args
621 body ------------- string holding the body of the code block
622 beg-body --------- point at the beginning of the body
623 end-body --------- point at the end of the body"
624 (declare (indent 1))
625 (let ((tempvar (make-symbol "file")))
626 `(let* ((,tempvar ,file)
627 (visited-p (or (null ,tempvar)
628 (get-file-buffer (expand-file-name ,tempvar))))
629 (point (point)) to-be-removed)
630 (save-window-excursion
631 (when ,tempvar (find-file ,tempvar))
632 (setq to-be-removed (current-buffer))
633 (goto-char (point-min))
634 (while (re-search-forward org-babel-src-block-regexp nil t)
635 (goto-char (match-beginning 0))
636 (let ((full-block (match-string 0))
637 (beg-block (match-beginning 0))
638 (end-block (match-end 0))
639 (lang (match-string 2))
640 (beg-lang (match-beginning 2))
641 (end-lang (match-end 2))
642 (switches (match-string 3))
643 (beg-switches (match-beginning 3))
644 (end-switches (match-end 3))
645 (header-args (match-string 4))
646 (beg-header-args (match-beginning 4))
647 (end-header-args (match-end 4))
648 (body (match-string 5))
649 (beg-body (match-beginning 5))
650 (end-body (match-end 5)))
651 ,@body
652 (goto-char end-block))))
653 (unless visited-p (kill-buffer to-be-removed))
654 (goto-char point))))
656 ;;;###autoload
657 (defmacro org-babel-map-inline-src-blocks (file &rest body)
658 "Evaluate BODY forms on each inline source-block in FILE.
659 If FILE is nil evaluate BODY forms on source blocks in current
660 buffer."
661 (declare (indent 1))
662 (let ((tempvar (make-symbol "file")))
663 `(let* ((,tempvar ,file)
664 (visited-p (or (null ,tempvar)
665 (get-file-buffer (expand-file-name ,tempvar))))
666 (point (point)) to-be-removed)
667 (save-window-excursion
668 (when ,tempvar (find-file ,tempvar))
669 (setq to-be-removed (current-buffer))
670 (goto-char (point-min))
671 (while (re-search-forward org-babel-inline-src-block-regexp nil t)
672 (goto-char (match-beginning 1))
673 (save-match-data ,@body)
674 (goto-char (match-end 0))))
675 (unless visited-p (kill-buffer to-be-removed))
676 (goto-char point))))
678 ;;;###autoload
679 (defun org-babel-execute-buffer (&optional arg)
680 "Execute source code blocks in a buffer.
681 Call `org-babel-execute-src-block' on every source block in
682 the current buffer."
683 (interactive "P")
684 (org-babel-eval-wipe-error-buffer)
685 (org-save-outline-visibility t
686 (org-babel-map-src-blocks nil
687 (org-babel-execute-src-block arg))
688 (org-babel-map-inline-src-blocks nil
689 (org-babel-execute-src-block arg))))
691 ;;;###autoload
692 (defun org-babel-execute-subtree (&optional arg)
693 "Execute source code blocks in a subtree.
694 Call `org-babel-execute-src-block' on every source block in
695 the current subtree."
696 (interactive "P")
697 (save-restriction
698 (save-excursion
699 (org-narrow-to-subtree)
700 (org-babel-execute-buffer arg)
701 (widen))))
703 ;;;###autoload
704 (defun org-babel-sha1-hash (&optional info)
705 "Generate an sha1 hash based on the value of info."
706 (interactive)
707 (let ((print-level nil)
708 (info (or info (org-babel-get-src-block-info))))
709 (setf (nth 2 info)
710 (sort (copy-sequence (nth 2 info))
711 (lambda (a b) (string< (car a) (car b)))))
712 (let ((hash (sha1
713 (format "%s-%s"
714 (mapconcat
715 #'identity
716 (delq nil
717 (mapcar
718 (lambda (arg)
719 (let ((v (cdr arg)))
720 (when (and v (not (and (sequencep v)
721 (not (consp v))
722 (= (length v) 0))))
723 (format "%S" v))))
724 (nth 2 info))) ":")
725 (nth 1 info)))))
726 (when (interactive-p) (message hash))
727 hash)))
729 (defun org-babel-result-hash (&optional info)
730 "Return the in-buffer hash associated with INFO."
731 (org-babel-where-is-src-block-result nil info)
732 (org-babel-clean-text-properties (match-string 3)))
734 (defun org-babel-hide-hash ()
735 "Hide the hash in the current results line.
736 Only the initial `org-babel-hash-show' characters of the hash
737 will remain visible."
738 (add-to-invisibility-spec '(org-babel-hide-hash . t))
739 (save-excursion
740 (when (and (re-search-forward org-babel-result-regexp nil t)
741 (match-string 3))
742 (let* ((start (match-beginning 3))
743 (hide-start (+ org-babel-hash-show start))
744 (end (match-end 3))
745 (hash (match-string 3))
746 ov1 ov2)
747 (setq ov1 (make-overlay start hide-start))
748 (setq ov2 (make-overlay hide-start end))
749 (overlay-put ov2 'invisible 'org-babel-hide-hash)
750 (overlay-put ov1 'babel-hash hash)))))
752 (defun org-babel-hide-all-hashes ()
753 "Hide the hash in the current buffer.
754 Only the initial `org-babel-hash-show' characters of each hash
755 will remain visible. This function should be called as part of
756 the `org-mode-hook'."
757 (save-excursion
758 (while (re-search-forward org-babel-result-regexp nil t)
759 (goto-char (match-beginning 0))
760 (org-babel-hide-hash)
761 (goto-char (match-end 0)))))
762 (add-hook 'org-mode-hook 'org-babel-hide-all-hashes)
764 (defun org-babel-hash-at-point (&optional point)
765 "Return the value of the hash at POINT.
766 The hash is also added as the last element of the kill ring.
767 This can be called with C-c C-c."
768 (interactive)
769 (let ((hash (car (delq nil (mapcar
770 (lambda (ol) (overlay-get ol 'babel-hash))
771 (overlays-at (or point (point))))))))
772 (when hash (kill-new hash) (message hash))))
773 (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-hash-at-point)
775 (defun org-babel-result-hide-spec ()
776 "Hide portions of results lines.
777 Add `org-babel-hide-result' as an invisibility spec for hiding
778 portions of results lines."
779 (add-to-invisibility-spec '(org-babel-hide-result . t)))
780 (add-hook 'org-mode-hook 'org-babel-result-hide-spec)
782 (defvar org-babel-hide-result-overlays nil
783 "Overlays hiding results.")
785 (defun org-babel-result-hide-all ()
786 "Fold all results in the current buffer."
787 (interactive)
788 (org-babel-show-result-all)
789 (save-excursion
790 (while (re-search-forward org-babel-result-regexp nil t)
791 (save-excursion (goto-char (match-beginning 0))
792 (org-babel-hide-result-toggle-maybe)))))
794 (defun org-babel-show-result-all ()
795 "Unfold all results in the current buffer."
796 (mapc 'delete-overlay org-babel-hide-result-overlays)
797 (setq org-babel-hide-result-overlays nil))
799 ;;;###autoload
800 (defun org-babel-hide-result-toggle-maybe ()
801 "Toggle visibility of result at point."
802 (interactive)
803 (let ((case-fold-search t))
804 (if (save-excursion
805 (beginning-of-line 1)
806 (looking-at org-babel-result-regexp))
807 (progn (org-babel-hide-result-toggle)
808 t) ;; to signal that we took action
809 nil))) ;; to signal that we did not
811 (defun org-babel-hide-result-toggle (&optional force)
812 "Toggle the visibility of the current result."
813 (interactive)
814 (save-excursion
815 (beginning-of-line)
816 (if (re-search-forward org-babel-result-regexp nil t)
817 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
818 (end (progn (goto-char (- (org-babel-result-end) 1)) (point)))
820 (if (memq t (mapcar (lambda (overlay)
821 (eq (overlay-get overlay 'invisible)
822 'org-babel-hide-result))
823 (overlays-at start)))
824 (if (or (not force) (eq force 'off))
825 (mapc (lambda (ov)
826 (when (member ov org-babel-hide-result-overlays)
827 (setq org-babel-hide-result-overlays
828 (delq ov org-babel-hide-result-overlays)))
829 (when (eq (overlay-get ov 'invisible)
830 'org-babel-hide-result)
831 (delete-overlay ov)))
832 (overlays-at start)))
833 (setq ov (make-overlay start end))
834 (overlay-put ov 'invisible 'org-babel-hide-result)
835 ;; make the block accessible to isearch
836 (overlay-put
837 ov 'isearch-open-invisible
838 (lambda (ov)
839 (when (member ov org-babel-hide-result-overlays)
840 (setq org-babel-hide-result-overlays
841 (delq ov org-babel-hide-result-overlays)))
842 (when (eq (overlay-get ov 'invisible)
843 'org-babel-hide-result)
844 (delete-overlay ov))))
845 (push ov org-babel-hide-result-overlays)))
846 (error "Not looking at a result line"))))
848 ;; org-tab-after-check-for-cycling-hook
849 (add-hook 'org-tab-first-hook 'org-babel-hide-result-toggle-maybe)
850 ;; Remove overlays when changing major mode
851 (add-hook 'org-mode-hook
852 (lambda () (org-add-hook 'change-major-mode-hook
853 'org-babel-show-result-all 'append 'local)))
855 (defvar org-file-properties)
856 (defun org-babel-params-from-properties (&optional lang)
857 "Retrieve parameters specified as properties.
858 Return an association list of any source block params which
859 may be specified in the properties of the current outline entry."
860 (save-match-data
861 (let (val sym)
862 (delq nil
863 (mapcar
864 (lambda (header-arg)
865 (and (setq val
866 (or (org-entry-get (point) header-arg t)
867 (cdr (assoc header-arg org-file-properties))))
868 (cons (intern (concat ":" header-arg))
869 (org-babel-read val))))
870 (mapcar
871 'symbol-name
872 (append
873 org-babel-header-arg-names
874 (progn
875 (setq sym (intern (concat "org-babel-header-arg-names:" lang)))
876 (and (boundp sym) (eval sym))))))))))
878 (defun org-babel-params-from-buffer ()
879 "Retrieve per-buffer parameters.
880 Return an association list of any source block params which
881 may be specified in the current buffer."
882 (or org-babel-current-buffer-properties
883 (save-match-data
884 (save-excursion
885 (save-restriction
886 (widen)
887 (goto-char (point-min))
888 (while (re-search-forward
889 (org-make-options-regexp (list "BABEL")) nil t)
890 (setq org-babel-current-buffer-properties
891 (org-babel-merge-params
892 org-babel-current-buffer-properties
893 (org-babel-parse-header-arguments
894 (org-match-string-no-properties 2)))))
895 org-babel-current-buffer-properties)))))
897 (defvar org-src-preserve-indentation)
898 (defun org-babel-parse-src-block-match ()
899 "Parse the results from a match of the `org-babel-src-block-regexp'."
900 (let* ((block-indentation (length (match-string 1)))
901 (lang (org-babel-clean-text-properties (match-string 2)))
902 (lang-headers (intern (concat "org-babel-default-header-args:" lang)))
903 (switches (match-string 3))
904 (body (org-babel-clean-text-properties (match-string 5)))
905 (preserve-indentation (or org-src-preserve-indentation
906 (string-match "-i\\>" switches))))
907 (list lang
908 ;; get block body less properties, protective commas, and indentation
909 (with-temp-buffer
910 (save-match-data
911 (insert (org-babel-strip-protective-commas body))
912 (unless preserve-indentation (org-do-remove-indentation))
913 (buffer-string)))
914 (org-babel-merge-params
915 org-babel-default-header-args
916 (org-babel-params-from-buffer)
917 (org-babel-params-from-properties lang)
918 (if (boundp lang-headers) (eval lang-headers) nil)
919 (org-babel-parse-header-arguments
920 (org-babel-clean-text-properties (or (match-string 4) ""))))
921 switches
922 block-indentation)))
924 (defun org-babel-parse-inline-src-block-match ()
925 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
926 (let* ((lang (org-babel-clean-text-properties (match-string 2)))
927 (lang-headers (intern (concat "org-babel-default-header-args:" lang))))
928 (list lang
929 (org-babel-strip-protective-commas
930 (org-babel-clean-text-properties (match-string 5)))
931 (org-babel-merge-params
932 org-babel-default-inline-header-args
933 (org-babel-params-from-buffer)
934 (org-babel-params-from-properties lang)
935 (if (boundp lang-headers) (eval lang-headers) nil)
936 (org-babel-parse-header-arguments
937 (org-babel-clean-text-properties (or (match-string 4) "")))))))
939 (defun org-babel-parse-header-arguments (arg-string)
940 "Parse a string of header arguments returning an alist."
941 (when (> (length arg-string) 0)
942 (delq nil
943 (mapcar
944 (lambda (arg)
945 (if (string-match
946 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
947 arg)
948 (cons (intern (match-string 1 arg))
949 (org-babel-read (org-babel-chomp (match-string 2 arg))))
950 (cons (intern (org-babel-chomp arg)) nil)))
951 (let ((balance 0) (partial nil) (lst nil) (last 0))
952 (mapc (lambda (ch) ; split on [] balanced instances of [ \t]:
953 (setq balance (+ balance
954 (cond ((equal 91 ch) 1)
955 ((equal 93 ch) -1)
956 (t 0))))
957 (setq partial (cons ch partial))
958 (when (and (= ch 58) (= balance 0)
959 (or (= last 32) (= last 9)))
960 (setq lst (cons (apply #'string (nreverse (cddr partial)))
961 lst))
962 (setq partial (list ch)))
963 (setq last ch))
964 (string-to-list arg-string))
965 (nreverse (cons (apply #'string (nreverse partial)) lst)))))))
967 (defun org-babel-process-params (params)
968 "Expand variables in PARAMS and add summary parameters."
969 (let* ((vars-and-names (org-babel-disassemble-tables
970 (mapcar (lambda (el)
971 (if (consp (cdr el))
972 (cdr el) (org-babel-ref-parse (cdr el))))
973 (org-babel-get-header params :var))
974 (cdr (assoc :hlines params))
975 (cdr (assoc :colnames params))
976 (cdr (assoc :rownames params))))
977 (result-params (append
978 (split-string (or (cdr (assoc :results params)) ""))
979 (cdr (assoc :result-params params)))))
980 (append
981 (mapcar (lambda (var) (cons :var var)) (car vars-and-names))
982 (list
983 (cons :colname-names (cadr vars-and-names))
984 (cons :rowname-names (caddr vars-and-names))
985 (cons :result-params result-params)
986 (cons :result-type (cond ((member "output" result-params) 'output)
987 ((member "value" result-params) 'value)
988 (t 'value))))
989 (org-babel-get-header params :var 'other))))
991 ;; row and column names
992 (defun org-babel-del-hlines (table)
993 "Remove all 'hlines from TABLE."
994 (remove 'hline table))
996 (defun org-babel-get-colnames (table)
997 "Return the column names of TABLE.
998 Return a cons cell, the `car' of which contains the TABLE less
999 colnames, and the `cdr' of which contains a list of the column
1000 names."
1001 (if (equal 'hline (nth 1 table))
1002 (cons (cddr table) (car table))
1003 (cons (cdr table) (car table))))
1005 (defun org-babel-get-rownames (table)
1006 "Return the row names of TABLE.
1007 Return a cons cell, the `car' of which contains the TABLE less
1008 colnames, and the `cdr' of which contains a list of the column
1009 names. Note: this function removes any hlines in TABLE."
1010 (flet ((trans (table) (apply #'mapcar* #'list table)))
1011 (let* ((width (apply 'max
1012 (mapcar (lambda (el) (if (listp el) (length el) 0)) table)))
1013 (table (trans (mapcar (lambda (row)
1014 (if (not (equal row 'hline))
1016 (setq row '())
1017 (dotimes (n width)
1018 (setq row (cons 'hline row)))
1019 row))
1020 table))))
1021 (cons (mapcar (lambda (row) (if (equal (car row) 'hline) 'hline row))
1022 (trans (cdr table)))
1023 (remove 'hline (car table))))))
1025 (defun org-babel-put-colnames (table colnames)
1026 "Add COLNAMES to TABLE if they exist."
1027 (if colnames (apply 'list colnames 'hline table) table))
1029 (defun org-babel-put-rownames (table rownames)
1030 "Add ROWNAMES to TABLE if they exist."
1031 (if rownames
1032 (mapcar (lambda (row)
1033 (if (listp row)
1034 (cons (or (pop rownames) "") row)
1035 row)) table)
1036 table))
1038 (defun org-babel-pick-name (names selector)
1039 "Select one out of an alist of row or column names.
1040 SELECTOR can be either a list of names in which case those names
1041 will be returned directly, or an index into the list NAMES in
1042 which case the indexed names will be return."
1043 (if (listp selector)
1044 selector
1045 (when names
1046 (if (and selector (symbolp selector) (not (equal t selector)))
1047 (cdr (assoc selector names))
1048 (if (integerp selector)
1049 (nth (- selector 1) names)
1050 (cdr (car (last names))))))))
1052 (defun org-babel-disassemble-tables (vars hlines colnames rownames)
1053 "Parse tables for further processing.
1054 Process the variables in VARS according to the HLINES,
1055 ROWNAMES and COLNAMES header arguments. Return a list consisting
1056 of the vars, cnames and rnames."
1057 (let (cnames rnames)
1058 (list
1059 (mapcar
1060 (lambda (var)
1061 (when (listp (cdr var))
1062 (when (and (not (equal colnames "no"))
1063 (or colnames (and (equal (nth 1 (cdr var)) 'hline)
1064 (not (member 'hline (cddr (cdr var)))))))
1065 (let ((both (org-babel-get-colnames (cdr var))))
1066 (setq cnames (cons (cons (car var) (cdr both))
1067 cnames))
1068 (setq var (cons (car var) (car both)))))
1069 (when (and rownames (not (equal rownames "no")))
1070 (let ((both (org-babel-get-rownames (cdr var))))
1071 (setq rnames (cons (cons (car var) (cdr both))
1072 rnames))
1073 (setq var (cons (car var) (car both)))))
1074 (when (and hlines (not (equal hlines "yes")))
1075 (setq var (cons (car var) (org-babel-del-hlines (cdr var))))))
1076 var)
1077 vars)
1078 cnames rnames)))
1080 (defun org-babel-reassemble-table (table colnames rownames)
1081 "Add column and row names to a table.
1082 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1083 to the table for reinsertion to org-mode."
1084 (if (listp table)
1085 ((lambda (table)
1086 (if (and colnames (listp (car table)) (= (length (car table))
1087 (length colnames)))
1088 (org-babel-put-colnames table colnames) table))
1089 (if (and rownames (= (length table) (length rownames)))
1090 (org-babel-put-rownames table rownames) table))
1091 table))
1093 (defun org-babel-where-is-src-block-head ()
1094 "Find where the current source block begins.
1095 Return the point at the beginning of the current source
1096 block. Specifically at the beginning of the #+BEGIN_SRC line.
1097 If the point is not on a source block then return nil."
1098 (let ((initial (point)) top bottom)
1100 (save-excursion ;; on a source name line or a #+header line
1101 (beginning-of-line 1)
1102 (and (or (looking-at org-babel-src-name-regexp)
1103 (looking-at org-babel-multi-line-header-regexp))
1104 (progn
1105 (while (and (forward-line 1)
1106 (looking-at org-babel-multi-line-header-regexp)))
1107 (looking-at org-babel-src-block-regexp))
1108 (point)))
1109 (save-excursion ;; on a #+begin_src line
1110 (beginning-of-line 1)
1111 (and (looking-at org-babel-src-block-regexp)
1112 (point)))
1113 (save-excursion ;; inside a src block
1114 (and
1115 (re-search-backward "^[ \t]*#\\+begin_src" nil t) (setq top (point))
1116 (re-search-forward "^[ \t]*#\\+end_src" nil t) (setq bottom (point))
1117 (< top initial) (< initial bottom)
1118 (progn (goto-char top) (beginning-of-line 1)
1119 (looking-at org-babel-src-block-regexp))
1120 (point))))))
1122 ;;;###autoload
1123 (defun org-babel-goto-src-block-head ()
1124 "Go to the beginning of the current code block."
1125 (interactive)
1126 ((lambda (head)
1127 (if head (goto-char head) (error "not currently in a code block")))
1128 (org-babel-where-is-src-block-head)))
1130 ;;;###autoload
1131 (defun org-babel-goto-named-src-block (name)
1132 "Go to a named source-code block."
1133 (interactive
1134 (let ((completion-ignore-case t))
1135 (list (org-icompleting-read "source-block name: "
1136 (org-babel-src-block-names) nil t))))
1137 (let ((point (org-babel-find-named-block name)))
1138 (if point
1139 ;; taken from `org-open-at-point'
1140 (progn (goto-char point) (org-show-context))
1141 (message "source-code block '%s' not found in this buffer" name))))
1143 (defun org-babel-find-named-block (name)
1144 "Find a named source-code block.
1145 Return the location of the source block identified by source
1146 NAME, or nil if no such block exists. Set match data according to
1147 org-babel-named-src-block-regexp."
1148 (save-excursion
1149 (let ((case-fold-search t)
1150 (regexp (org-babel-named-src-block-regexp-for-name name)) msg)
1151 (goto-char (point-min))
1152 (when (or (re-search-forward regexp nil t)
1153 (re-search-backward regexp nil t))
1154 (match-beginning 0)))))
1156 (defun org-babel-src-block-names (&optional file)
1157 "Returns the names of source blocks in FILE or the current buffer."
1158 (save-excursion
1159 (when file (find-file file)) (goto-char (point-min))
1160 (let (names)
1161 (while (re-search-forward org-babel-src-name-w-name-regexp nil t)
1162 (setq names (cons (org-babel-clean-text-properties (match-string 4))
1163 names)))
1164 names)))
1166 ;;;###autoload
1167 (defun org-babel-goto-named-result (name)
1168 "Go to a named result."
1169 (interactive
1170 (let ((completion-ignore-case t))
1171 (list (org-icompleting-read "source-block name: "
1172 (org-babel-result-names) nil t))))
1173 (let ((point (org-babel-find-named-result name)))
1174 (if point
1175 ;; taken from `org-open-at-point'
1176 (progn (goto-char point) (org-show-context))
1177 (message "result '%s' not found in this buffer" name))))
1179 (defun org-babel-find-named-result (name)
1180 "Find a named result.
1181 Return the location of the result named NAME in the current
1182 buffer or nil if no such result exists."
1183 (save-excursion
1184 (goto-char (point-min))
1185 (when (re-search-forward
1186 (concat org-babel-result-regexp
1187 "[ \t]" (regexp-quote name) "[ \t\n\f\v\r]") nil t)
1188 (beginning-of-line 0) (point))))
1190 (defun org-babel-result-names (&optional file)
1191 "Returns the names of results in FILE or the current buffer."
1192 (save-excursion
1193 (when file (find-file file)) (goto-char (point-min))
1194 (let (names)
1195 (while (re-search-forward org-babel-result-w-name-regexp nil t)
1196 (setq names (cons (org-babel-clean-text-properties (match-string 4))
1197 names)))
1198 names)))
1200 ;;;###autoload
1201 (defun org-babel-next-src-block (&optional arg)
1202 "Jump to the next source block.
1203 With optional prefix argument ARG, jump forward ARG many source blocks."
1204 (interactive "P")
1205 (when (looking-at org-babel-src-block-regexp) (forward-char 1))
1206 (condition-case nil
1207 (re-search-forward org-babel-src-block-regexp nil nil (or arg 1))
1208 (error (error "No further code blocks")))
1209 (goto-char (match-beginning 0)) (org-show-context))
1211 ;;;###autoload
1212 (defun org-babel-previous-src-block (&optional arg)
1213 "Jump to the previous source block.
1214 With optional prefix argument ARG, jump backward ARG many source blocks."
1215 (interactive "P")
1216 (condition-case nil
1217 (re-search-backward org-babel-src-block-regexp nil nil (or arg 1))
1218 (error (error "No previous code blocks")))
1219 (goto-char (match-beginning 0)) (org-show-context))
1221 (defvar org-babel-load-languages)
1223 ;;;###autoload
1224 (defun org-babel-mark-block ()
1225 "Mark current src block"
1226 (interactive)
1227 ((lambda (head)
1228 (when head
1229 (save-excursion
1230 (goto-char head)
1231 (looking-at org-babel-src-block-regexp))
1232 (push-mark (match-end 5) nil t)
1233 (goto-char (match-beginning 5))))
1234 (org-babel-where-is-src-block-head)))
1236 (defun org-babel-demarcate-block (&optional arg)
1237 "Wrap or split the code in the region or on the point.
1238 When called from inside of a code block the current block is
1239 split. When called from outside of a code block a new code block
1240 is created. In both cases if the region is demarcated and if the
1241 region is not active then the point is demarcated."
1242 (interactive "P")
1243 (let ((info (org-babel-get-src-block-info 'light))
1244 (stars (concat (make-string (or (org-current-level) 1) ?*) " ")))
1245 (if info
1246 (mapc
1247 (lambda (place)
1248 (save-excursion
1249 (goto-char place)
1250 (let ((lang (nth 0 info))
1251 (indent (make-string (nth 5 info) ? )))
1252 (when (string-match "^[[:space:]]*$"
1253 (buffer-substring (point-at-bol)
1254 (point-at-eol)))
1255 (delete-region (point-at-bol) (point-at-eol)))
1256 (insert (concat (if (looking-at "^") "" "\n")
1257 indent "#+end_src\n"
1258 (if arg stars indent) "\n"
1259 indent "#+begin_src " lang
1260 (if (looking-at "[\n\r]") "" "\n")))))
1261 (move-end-of-line 2))
1262 (sort (if (region-active-p) (list (mark) (point)) (list (point))) #'>))
1263 (let ((start (point))
1264 (lang (org-icompleting-read "Lang: "
1265 (mapcar (lambda (el) (symbol-name (car el)))
1266 org-babel-load-languages)))
1267 (body (delete-and-extract-region
1268 (if (region-active-p) (mark) (point)) (point))))
1269 (insert (concat (if (looking-at "^") "" "\n")
1270 (if arg (concat stars "\n") "")
1271 "#+begin_src " lang "\n"
1272 body
1273 (if (or (= (length body) 0)
1274 (string-match "[\r\n]$" body)) "" "\n")
1275 "#+end_src\n"))
1276 (goto-char start) (move-end-of-line 1)))))
1278 (defvar org-babel-lob-one-liner-regexp)
1279 (defun org-babel-where-is-src-block-result (&optional insert info hash indent)
1280 "Find where the current source block results begin.
1281 Return the point at the beginning of the result of the current
1282 source block. Specifically at the beginning of the results line.
1283 If no result exists for this block then create a results line
1284 following the source block."
1285 (save-excursion
1286 (let* ((on-lob-line (save-excursion
1287 (beginning-of-line 1)
1288 (looking-at org-babel-lob-one-liner-regexp)))
1289 (inlinep (save-excursion
1290 (re-search-backward "[ \f\t\n\r\v]" nil t)
1291 (when (looking-at org-babel-inline-src-block-regexp)
1292 (match-end 0))))
1293 (name (if on-lob-line
1294 (nth 0 (org-babel-lob-get-info))
1295 (nth 4 (or info (org-babel-get-src-block-info)))))
1296 (head (unless on-lob-line (org-babel-where-is-src-block-head)))
1297 found beg end)
1298 (when head (goto-char head))
1299 (setq
1300 found ;; was there a result (before we potentially insert one)
1302 inlinep
1303 (and
1304 ;; named results:
1305 ;; - return t if it is found, else return nil
1306 ;; - if it does not need to be rebuilt, then don't set end
1307 ;; - if it does need to be rebuilt then do set end
1308 name (setq beg (org-babel-find-named-result name))
1309 (prog1 beg
1310 (when (and hash (not (string= hash (match-string 3))))
1311 (goto-char beg) (setq end beg) ;; beginning of result
1312 (forward-line 1)
1313 (delete-region end (org-babel-result-end)) nil)))
1314 (and
1315 ;; unnamed results:
1316 ;; - return t if it is found, else return nil
1317 ;; - if it is found, and the hash doesn't match, delete and set end
1318 (or on-lob-line (re-search-forward "^[ \t]*#\\+end_src" nil t))
1319 (progn (end-of-line 1)
1320 (if (eobp) (insert "\n") (forward-char 1))
1321 (setq end (point))
1322 (or (and (not name)
1323 (progn ;; unnamed results line already exists
1324 (re-search-forward "[^ \f\t\n\r\v]" nil t)
1325 (beginning-of-line 1)
1326 (looking-at
1327 (concat org-babel-result-regexp "\n")))
1328 (prog1 (point)
1329 ;; must remove and rebuild if hash!=old-hash
1330 (if (and hash (not (string= hash (match-string 3))))
1331 (prog1 nil
1332 (forward-line 1)
1333 (delete-region
1334 end (org-babel-result-end)))
1335 (setq end nil)))))))))
1336 (if (and insert end)
1337 (progn
1338 (goto-char end)
1339 (unless beg
1340 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1341 (insert (concat
1342 (if indent
1343 (mapconcat
1344 (lambda (el) " ")
1345 (org-number-sequence 1 indent) "")
1347 "#+results"
1348 (when hash (concat "["hash"]"))
1350 (when name (concat " " name)) "\n"))
1351 (unless beg (insert "\n") (backward-char))
1352 (beginning-of-line 0)
1353 (if hash (org-babel-hide-hash))
1354 (point))
1355 found))))
1357 (defvar org-block-regexp)
1358 (defun org-babel-read-result ()
1359 "Read the result at `point' into emacs-lisp."
1360 (let ((case-fold-search t) result-string)
1361 (cond
1362 ((org-at-table-p) (org-babel-read-table))
1363 ((org-in-item-p) (org-babel-read-list))
1364 ((looking-at org-bracket-link-regexp) (org-babel-read-link))
1365 ((looking-at org-block-regexp) (org-babel-trim (match-string 4)))
1366 ((looking-at "^[ \t]*: ")
1367 (setq result-string
1368 (org-babel-trim
1369 (mapconcat (lambda (line)
1370 (if (and (> (length line) 1)
1371 (string-match "^[ \t]*: \\(.+\\)" line))
1372 (match-string 1 line)
1373 line))
1374 (split-string
1375 (buffer-substring
1376 (point) (org-babel-result-end)) "[\r\n]+")
1377 "\n")))
1378 (or (org-babel-number-p result-string) result-string))
1379 ((looking-at org-babel-result-regexp)
1380 (save-excursion (forward-line 1) (org-babel-read-result))))))
1382 (defun org-babel-read-table ()
1383 "Read the table at `point' into emacs-lisp."
1384 (mapcar (lambda (row)
1385 (if (and (symbolp row) (equal row 'hline)) row
1386 (mapcar #'org-babel-read row)))
1387 (org-table-to-lisp)))
1389 (defun org-babel-read-list ()
1390 "Read the list at `point' into emacs-lisp."
1391 (mapcar #'org-babel-read (cdr (org-list-parse-list))))
1393 (defvar org-link-types-re)
1394 (defun org-babel-read-link ()
1395 "Read the link at `point' into emacs-lisp.
1396 If the path of the link is a file path it is expanded using
1397 `expand-file-name'."
1398 (let* ((case-fold-search t)
1399 (raw (and (looking-at org-bracket-link-regexp)
1400 (org-babel-clean-text-properties (match-string 1))))
1401 (type (and (string-match org-link-types-re raw)
1402 (match-string 1 raw))))
1403 (cond
1404 ((not type) (expand-file-name raw))
1405 ((string= type "file")
1406 (and (string-match "file\\(.*\\):\\(.+\\)" raw)
1407 (expand-file-name (match-string 2 raw))))
1408 (t raw))))
1410 (defun org-babel-format-result (result &optional sep)
1411 "Format RESULT for writing to file."
1412 (flet ((echo-res (result)
1413 (if (stringp result) result (format "%S" result))))
1414 (if (listp result)
1415 ;; table result
1416 (orgtbl-to-generic
1417 result
1418 (list
1419 :sep (or sep "\t")
1420 :fmt 'echo-res))
1421 ;; scalar result
1422 (echo-res result))))
1424 (defun org-babel-insert-result
1425 (result &optional result-params info hash indent lang)
1426 "Insert RESULT into the current buffer.
1427 By default RESULT is inserted after the end of the
1428 current source block. With optional argument RESULT-PARAMS
1429 controls insertion of results in the org-mode file.
1430 RESULT-PARAMS can take the following values...
1432 replace - (default option) insert results after the source block
1433 replacing any previously inserted results
1435 silent -- no results are inserted
1437 file ---- the results are interpreted as a file path, and are
1438 inserted into the buffer using the Org-mode file syntax
1440 list ---- the results are interpreted as an Org-mode list.
1442 raw ----- results are added directly to the Org-mode file. This
1443 is a good option if you code block will output org-mode
1444 formatted text.
1446 org ----- similar in effect to raw, only the results are wrapped
1447 in an org code block. Similar to the raw option, on
1448 export the results will be interpreted as org-formatted
1449 text, however by wrapping the results in an org code
1450 block they can be replaced upon re-execution of the
1451 code block.
1453 html ---- results are added inside of a #+BEGIN_HTML block. This
1454 is a good option if you code block will output html
1455 formatted text.
1457 latex --- results are added inside of a #+BEGIN_LATEX block.
1458 This is a good option if you code block will output
1459 latex formatted text.
1461 code ---- the results are extracted in the syntax of the source
1462 code of the language being evaluated and are added
1463 inside of a #+BEGIN_SRC block with the source-code
1464 language set appropriately. Note this relies on the
1465 optional LANG argument."
1466 (if (stringp result)
1467 (progn
1468 (setq result (org-babel-clean-text-properties result))
1469 (when (member "file" result-params)
1470 (setq result (org-babel-result-to-file result))))
1471 (unless (listp result) (setq result (format "%S" result))))
1472 (if (and result-params (member "silent" result-params))
1473 (progn
1474 (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
1475 result)
1476 (save-excursion
1477 (let* ((inlinep (save-excursion
1478 (re-search-backward "[ \f\t\n\r\v]" nil t)
1479 (when (looking-at org-babel-inline-src-block-regexp)
1480 (goto-char (match-end 0))
1481 (insert (if (listp result) "\n" " "))
1482 (point))))
1483 (existing-result (unless inlinep
1484 (org-babel-where-is-src-block-result
1485 t info hash indent)))
1486 (results-switches
1487 (cdr (assoc :results_switches (nth 2 info))))
1488 beg end)
1489 (when (and (stringp result) ; ensure results end in a newline
1490 (not inlinep)
1491 (> (length result) 0)
1492 (not (or (string-equal (substring result -1) "\n")
1493 (string-equal (substring result -1) "\r"))))
1494 (setq result (concat result "\n")))
1495 (if (not existing-result)
1496 (setq beg (or inlinep (point)))
1497 (goto-char existing-result)
1498 (save-excursion
1499 (re-search-forward "#" nil t)
1500 (setq indent (- (current-column) 1)))
1501 (forward-line 1)
1502 (setq beg (point))
1503 (cond
1504 ((member "replace" result-params)
1505 (delete-region (point) (org-babel-result-end)))
1506 ((member "append" result-params)
1507 (goto-char (org-babel-result-end)) (setq beg (point-marker)))
1508 ((member "prepend" result-params)))) ; already there
1509 (setq results-switches
1510 (if results-switches (concat " " results-switches) ""))
1511 ;; insert results based on type
1512 (cond
1513 ;; do nothing for an empty result
1514 ((= (length result) 0))
1515 ;; insert a list if preferred
1516 ((member "list" result-params)
1517 (insert
1518 (org-babel-trim
1519 (org-list-to-generic (cons 'unordered
1520 (if (listp result) result (list result)))
1521 '(:splicep nil :istart "- " :iend "\n")))))
1522 ;; assume the result is a table if it's not a string
1523 ((not (stringp result))
1524 (goto-char beg)
1525 (insert (concat (orgtbl-to-orgtbl
1526 (if (or (eq 'hline (car result))
1527 (and (listp (car result))
1528 (listp (cdr (car result)))))
1529 result (list result))
1530 '(:fmt (lambda (cell) (format "%s" cell)))) "\n"))
1531 (goto-char beg) (when (org-at-table-p) (org-table-align)))
1532 ((member "file" result-params)
1533 (insert result))
1534 (t (goto-char beg) (insert result)))
1535 (when (listp result) (goto-char (org-table-end)))
1536 (setq end (point-marker))
1537 ;; possibly wrap result
1538 (flet ((wrap (start finish)
1539 (goto-char beg) (insert (concat start "\n"))
1540 (goto-char end) (insert (concat finish "\n"))
1541 (setq end (point-marker))))
1542 (cond
1543 ((member "html" result-params)
1544 (wrap "#+BEGIN_HTML" "#+END_HTML"))
1545 ((member "latex" result-params)
1546 (wrap "#+BEGIN_LaTeX" "#+END_LaTeX"))
1547 ((member "code" result-params)
1548 (wrap (format "#+BEGIN_SRC %s%s" (or lang "none") results-switches)
1549 "#+END_SRC"))
1550 ((member "org" result-params)
1551 (wrap "#+BEGIN_ORG" "#+END_ORG"))
1552 ((member "raw" result-params)
1553 (goto-char beg) (if (org-at-table-p) (org-cycle)))
1554 ((member "wrap" result-params)
1555 (when (and (stringp result) (not (member "file" result-params)))
1556 (org-babel-examplize-region beg end results-switches))
1557 (wrap "#+BEGIN_RESULT" "#+END_RESULT"))
1558 ((and (stringp result) (not (member "file" result-params)))
1559 (org-babel-examplize-region beg end results-switches)
1560 (setq end (point)))))
1561 ;; possibly indent the results to match the #+results line
1562 (when (and (not inlinep) indent (> indent 0)
1563 ;; in this case `table-align' does the work for us
1564 (not (and (listp result)
1565 (member "append" result-params))))
1566 (indent-rigidly beg end indent))))
1567 (if (= (length result) 0)
1568 (if (member "value" result-params)
1569 (message "Code block returned no value.")
1570 (message "Code block produced no output."))
1571 (message "Code block evaluation complete."))))
1573 (defun org-babel-remove-result (&optional info)
1574 "Remove the result of the current source block."
1575 (interactive)
1576 (let ((location (org-babel-where-is-src-block-result nil info)) start)
1577 (when location
1578 (save-excursion
1579 (goto-char location) (setq start (point)) (forward-line 1)
1580 (delete-region start (org-babel-result-end))))))
1582 (defun org-babel-result-end ()
1583 "Return the point at the end of the current set of results"
1584 (save-excursion
1585 (cond
1586 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
1587 ((org-at-item-p) (- (org-list-bottom-point) 1))
1589 (let ((case-fold-search t)
1590 (blocks-re (regexp-opt
1591 (list "latex" "html" "example" "src" "result" "org"))))
1592 (if (looking-at (concat "[ \t]*#\\+begin_" blocks-re))
1593 (progn (re-search-forward (concat "[ \t]*#\\+end_" blocks-re) nil t)
1594 (forward-char 1))
1595 (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
1596 (forward-line 1))))
1597 (point)))))
1599 (defun org-babel-result-to-file (result)
1600 "Convert RESULT into an `org-mode' link.
1601 If the `default-directory' is different from the containing
1602 file's directory then expand relative links."
1603 (flet ((cond-exp (file)
1604 (if (and default-directory
1605 buffer-file-name
1606 (not (string= (expand-file-name default-directory)
1607 (expand-file-name
1608 (file-name-directory buffer-file-name)))))
1609 (expand-file-name file default-directory)
1610 file)))
1611 (if (stringp result)
1612 (format "[[file:%s]]" (cond-exp result))
1613 (when (and (listp result) (= 2 (length result))
1614 (stringp (car result)) (stringp (cadr result)))
1615 (format "[[file:%s][%s]]" (car result) (cadr result))))))
1617 (defun org-babel-examplize-region (beg end &optional results-switches)
1618 "Comment out region using the inline '==' or ': ' org example quote."
1619 (interactive "*r")
1620 (flet ((chars-between (b e) (string-match "[\\S]" (buffer-substring b e))))
1621 (if (or (chars-between (save-excursion (goto-char beg) (point-at-bol)) beg)
1622 (chars-between end (save-excursion (goto-char end) (point-at-eol))))
1623 (save-excursion
1624 (goto-char beg)
1625 (insert (format "=%s=" (prog1 (buffer-substring beg end)
1626 (delete-region beg end)))))
1627 (let ((size (count-lines beg end)))
1628 (save-excursion
1629 (cond ((= size 0)) ; do nothing for an empty result
1630 ((< size org-babel-min-lines-for-block-output)
1631 (goto-char beg)
1632 (dotimes (n size)
1633 (beginning-of-line 1) (insert ": ") (forward-line 1)))
1635 (goto-char beg)
1636 (insert (if results-switches
1637 (format "#+begin_example%s\n" results-switches)
1638 "#+begin_example\n"))
1639 (if (markerp end) (goto-char end) (forward-char (- end beg)))
1640 (insert "#+end_example\n"))))))))
1642 (defun org-babel-update-block-body (new-body)
1643 "Update the body of the current code block to NEW-BODY."
1644 (if (not (org-babel-where-is-src-block-head))
1645 (error "not in source block")
1646 (save-match-data
1647 (replace-match (concat (org-babel-trim new-body) "\n") nil t nil 5))
1648 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
1650 (defun org-babel-merge-params (&rest plists)
1651 "Combine all parameter association lists in PLISTS.
1652 Later elements of PLISTS override the values of previous elements.
1653 This takes into account some special considerations for certain
1654 parameters when merging lists."
1655 (let ((results-exclusive-groups
1656 '(("file" "list" "vector" "table" "scalar" "raw" "org"
1657 "html" "latex" "code" "pp" "wrap")
1658 ("replace" "silent" "append" "prepend")
1659 ("output" "value")))
1660 (exports-exclusive-groups
1661 '(("code" "results" "both" "none")))
1662 params results exports tangle noweb cache vars shebang comments)
1663 (flet ((e-merge (exclusive-groups &rest result-params)
1664 ;; maintain exclusivity of mutually exclusive parameters
1665 (let (output)
1666 (mapc (lambda (new-params)
1667 (mapc (lambda (new-param)
1668 (mapc (lambda (exclusive-group)
1669 (when (member new-param exclusive-group)
1670 (mapcar (lambda (excluded-param)
1671 (setq output
1672 (delete
1673 excluded-param
1674 output)))
1675 exclusive-group)))
1676 exclusive-groups)
1677 (setq output (org-uniquify
1678 (cons new-param output))))
1679 new-params))
1680 result-params)
1681 output)))
1682 (mapc
1683 (lambda (plist)
1684 (mapc
1685 (lambda (pair)
1686 (case (car pair)
1687 (:var
1688 (let ((name (if (listp (cdr pair))
1689 (cadr pair)
1690 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
1691 (cdr pair))
1692 (intern (match-string 1 (cdr pair)))))))
1693 (when name
1694 (setq vars
1695 (cons (cons name pair)
1696 (if (member name (mapcar #'car vars))
1697 (delq nil
1698 (mapcar
1699 (lambda (p) (unless (equal (car p) name) p))
1700 vars))
1701 vars))))))
1702 (:results
1703 (setq results (e-merge results-exclusive-groups
1704 results (split-string (cdr pair)))))
1705 (:file
1706 (when (cdr pair)
1707 (setq results (e-merge results-exclusive-groups
1708 results '("file")))
1709 (unless (or (member "both" exports)
1710 (member "none" exports)
1711 (member "code" exports))
1712 (setq exports (e-merge exports-exclusive-groups
1713 exports '("results"))))
1714 (setq params (cons pair (assq-delete-all (car pair) params)))))
1715 (:exports
1716 (setq exports (e-merge exports-exclusive-groups
1717 exports (split-string (cdr pair)))))
1718 (:tangle ;; take the latest -- always overwrite
1719 (setq tangle (or (list (cdr pair)) tangle)))
1720 (:noweb
1721 (setq noweb (e-merge '(("yes" "no" "tangle")) noweb
1722 (split-string (or (cdr pair) "")))))
1723 (:cache
1724 (setq cache (e-merge '(("yes" "no")) cache
1725 (split-string (or (cdr pair) "")))))
1726 (:shebang ;; take the latest -- always overwrite
1727 (setq shebang (or (list (cdr pair)) shebang)))
1728 (:comments
1729 (setq comments (e-merge '(("yes" "no")) comments
1730 (split-string (or (cdr pair) "")))))
1731 (t ;; replace: this covers e.g. :session
1732 (setq params (cons pair (assq-delete-all (car pair) params))))))
1733 plist))
1734 plists))
1735 (while vars (setq params (cons (cons :var (cddr (pop vars))) params)))
1736 (cons (cons :comments (mapconcat 'identity comments " "))
1737 (cons (cons :shebang (mapconcat 'identity shebang " "))
1738 (cons (cons :cache (mapconcat 'identity cache " "))
1739 (cons (cons :noweb (mapconcat 'identity noweb " "))
1740 (cons (cons :tangle (mapconcat 'identity tangle " "))
1741 (cons (cons :exports
1742 (mapconcat 'identity exports " "))
1743 (cons
1744 (cons :results
1745 (mapconcat 'identity results " "))
1746 params)))))))))
1748 (defun org-babel-expand-noweb-references (&optional info parent-buffer)
1749 "Expand Noweb references in the body of the current source code block.
1751 For example the following reference would be replaced with the
1752 body of the source-code block named 'example-block'.
1754 <<example-block>>
1756 Note that any text preceding the <<foo>> construct on a line will
1757 be interposed between the lines of the replacement text. So for
1758 example if <<foo>> is placed behind a comment, then the entire
1759 replacement text will also be commented.
1761 This function must be called from inside of the buffer containing
1762 the source-code block which holds BODY.
1764 In addition the following syntax can be used to insert the
1765 results of evaluating the source-code block named 'example-block'.
1767 <<example-block()>>
1769 Any optional arguments can be passed to example-block by placing
1770 the arguments inside the parenthesis following the convention
1771 defined by `org-babel-lob'. For example
1773 <<example-block(a=9)>>
1775 would set the value of argument \"a\" equal to \"9\". Note that
1776 these arguments are not evaluated in the current source-code
1777 block but are passed literally to the \"example-block\"."
1778 (let* ((parent-buffer (or parent-buffer (current-buffer)))
1779 (info (or info (org-babel-get-src-block-info)))
1780 (lang (nth 0 info))
1781 (body (nth 1 info))
1782 (comment (string= "noweb" (cdr (assoc :comments (nth 2 info)))))
1783 (new-body "") index source-name evaluate prefix)
1784 (flet ((nb-add (text) (setq new-body (concat new-body text)))
1785 (c-wrap (text)
1786 (with-temp-buffer
1787 (funcall (intern (concat lang "-mode")))
1788 (comment-region (point) (progn (insert text) (point)))
1789 (org-babel-trim (buffer-string)))))
1790 (with-temp-buffer
1791 (insert body) (goto-char (point-min))
1792 (setq index (point))
1793 (while (and (re-search-forward "<<\\(.+?\\)>>" nil t))
1794 (save-match-data (setf source-name (match-string 1)))
1795 (save-match-data (setq evaluate (string-match "\(.*\)" source-name)))
1796 (save-match-data
1797 (setq prefix
1798 (buffer-substring (match-beginning 0)
1799 (save-excursion
1800 (beginning-of-line 1) (point)))))
1801 ;; add interval to new-body (removing noweb reference)
1802 (goto-char (match-beginning 0))
1803 (nb-add (buffer-substring index (point)))
1804 (goto-char (match-end 0))
1805 (setq index (point))
1806 (nb-add
1807 (with-current-buffer parent-buffer
1808 (mapconcat ;; interpose PREFIX between every line
1809 #'identity
1810 (split-string
1811 (if evaluate
1812 (let ((raw (org-babel-ref-resolve source-name)))
1813 (if (stringp raw) raw (format "%S" raw)))
1814 (or (nth 2 (assoc (intern source-name)
1815 org-babel-library-of-babel))
1816 (save-restriction
1817 (widen)
1818 (let ((point (org-babel-find-named-block
1819 source-name)))
1820 (if point
1821 (save-excursion
1822 (goto-char point)
1823 ;; possibly wrap body in comments
1824 (let* ((i (org-babel-get-src-block-info 'light))
1825 (body (org-babel-trim
1826 (org-babel-expand-noweb-references
1827 i))))
1828 (if comment
1829 ((lambda (cs) (concat (c-wrap (car cs)) "\n"
1830 body
1831 "\n" (c-wrap (cadr cs))))
1832 (org-babel-tangle-comment-links i))
1833 body)))
1834 ;; optionally raise an error if named
1835 ;; source-block doesn't exist
1836 (if (member lang org-babel-noweb-error-langs)
1837 (error "%s"
1838 (concat
1839 "<<" source-name ">> "
1840 "could not be resolved (see "
1841 "`org-babel-noweb-error-langs')"))
1842 ""))))))
1843 "[\n\r]") (concat "\n" prefix)))))
1844 (nb-add (buffer-substring index (point-max)))))
1845 new-body))
1847 (defun org-babel-clean-text-properties (text)
1848 "Strip all properties from text return."
1849 (when text
1850 (set-text-properties 0 (length text) nil text) text))
1852 (defun org-babel-strip-protective-commas (body)
1853 "Strip protective commas from bodies of source blocks."
1854 (replace-regexp-in-string "^,#" "#" body))
1856 (defun org-babel-script-escape (str)
1857 "Safely convert tables into elisp lists."
1858 (let (in-single in-double out)
1859 (org-babel-read
1860 (if (and (stringp str) (string-match "^\\[.+\\]$" str))
1861 (org-babel-read
1862 (concat
1864 (progn
1865 (mapc
1866 (lambda (ch)
1867 (setq
1869 (case ch
1870 (91 (if (or in-double in-single) ; [
1871 (cons 91 out)
1872 (cons 40 out)))
1873 (93 (if (or in-double in-single) ; ]
1874 (cons 93 out)
1875 (cons 41 out)))
1876 (44 (if (or in-double in-single) ; ,
1877 (cons 44 out) (cons 32 out)))
1878 (39 (if in-double ; '
1879 (cons 39 out)
1880 (setq in-single (not in-single)) (cons 34 out)))
1881 (34 (if in-single ; "
1882 (append (list 34 32) out)
1883 (setq in-double (not in-double)) (cons 34 out)))
1884 (t (cons ch out)))))
1885 (string-to-list str))
1886 (apply #'string (reverse out)))))
1887 str))))
1889 (defun org-babel-read (cell)
1890 "Convert the string value of CELL to a number if appropriate.
1891 Otherwise if cell looks like lisp (meaning it starts with a
1892 \"(\" or a \"'\") then read it as lisp, otherwise return it
1893 unmodified as a string.
1895 This is taken almost directly from `org-read-prop'."
1896 (if (and (stringp cell) (not (equal cell "")))
1897 (or (org-babel-number-p cell)
1898 (if (or (equal "(" (substring cell 0 1))
1899 (equal "'" (substring cell 0 1))
1900 (equal "`" (substring cell 0 1)))
1901 (eval (read cell))
1902 (progn (set-text-properties 0 (length cell) nil cell) cell)))
1903 cell))
1905 (defun org-babel-number-p (string)
1906 "If STRING represents a number return it's value."
1907 (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string)
1908 (= (length (substring string (match-beginning 0)
1909 (match-end 0)))
1910 (length string)))
1911 (string-to-number string)))
1913 (defun org-babel-import-elisp-from-file (file-name &optional separator)
1914 "Read the results located at FILE-NAME into an elisp table.
1915 If the table is trivial, then return it as a scalar."
1916 (let (result)
1917 (save-window-excursion
1918 (with-temp-buffer
1919 (condition-case nil
1920 (progn
1921 (org-table-import file-name separator)
1922 (delete-file file-name)
1923 (setq result (mapcar (lambda (row)
1924 (mapcar #'org-babel-string-read row))
1925 (org-table-to-lisp))))
1926 (error nil)))
1927 (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
1928 (if (consp (car result))
1929 (if (null (cdr (car result)))
1930 (caar result)
1931 result)
1932 (car result))
1933 result))))
1935 (defun org-babel-string-read (cell)
1936 "Strip nested \"s from around strings."
1937 (org-babel-read (or (and (stringp cell)
1938 (string-match "\\\"\\(.+\\)\\\"" cell)
1939 (match-string 1 cell))
1940 cell)))
1942 (defun org-babel-reverse-string (string)
1943 "Return the reverse of STRING."
1944 (apply 'string (reverse (string-to-list string))))
1946 (defun org-babel-chomp (string &optional regexp)
1947 "Strip trailing spaces and carriage returns from STRING.
1948 Default regexp used is \"[ \f\t\n\r\v]\" but can be
1949 overwritten by specifying a regexp as a second argument."
1950 (let ((regexp (or regexp "[ \f\t\n\r\v]")))
1951 (while (and (> (length string) 0)
1952 (string-match regexp (substring string -1)))
1953 (setq string (substring string 0 -1)))
1954 string))
1956 (defun org-babel-trim (string &optional regexp)
1957 "Strip leading and trailing spaces and carriage returns from STRING.
1958 Like `org-babel-chomp' only it runs on both the front and back
1959 of the string."
1960 (org-babel-chomp (org-babel-reverse-string
1961 (org-babel-chomp (org-babel-reverse-string string) regexp))
1962 regexp))
1964 (defvar org-babel-org-babel-call-process-region-original nil)
1965 (defun org-babel-tramp-handle-call-process-region
1966 (start end program &optional delete buffer display &rest args)
1967 "Use tramp to handle call-process-region.
1968 Fixes a bug in `tramp-handle-call-process-region'."
1969 (if (and (featurep 'tramp) (file-remote-p default-directory))
1970 (let ((tmpfile (tramp-compat-make-temp-file "")))
1971 (write-region start end tmpfile)
1972 (when delete (delete-region start end))
1973 (unwind-protect
1974 ;; (apply 'call-process program tmpfile buffer display args)
1975 ;; bug in tramp
1976 (apply 'process-file program tmpfile buffer display args)
1977 (delete-file tmpfile)))
1978 ;; org-babel-call-process-region-original is the original emacs
1979 ;; definition. It is in scope from the let binding in
1980 ;; org-babel-execute-src-block
1981 (apply org-babel-call-process-region-original
1982 start end program delete buffer display args)))
1984 (defun org-babel-local-file-name (file)
1985 "Return the local name component of FILE."
1986 (if (file-remote-p file)
1987 (let (localname)
1988 (with-parsed-tramp-file-name file nil
1989 localname))
1990 file))
1992 (defun org-babel-process-file-name (name &optional no-quote-p)
1993 "Prepare NAME to be used in an external process.
1994 If NAME specifies a remote location, the remote portion of the
1995 name is removed, since in that case the process will be executing
1996 remotely. The file name is then processed by
1997 `expand-file-name'. Unless second argument NO-QUOTE-P is non-nil,
1998 the file name is additionally processed by
1999 `shell-quote-argument'"
2000 ((lambda (f) (if no-quote-p f (shell-quote-argument f)))
2001 (expand-file-name (org-babel-local-file-name name))))
2003 (defvar org-babel-temporary-directory)
2004 (unless (or noninteractive (boundp 'org-babel-temporary-directory))
2005 (defvar org-babel-temporary-directory
2006 (or (and (boundp 'org-babel-temporary-directory)
2007 (file-exists-p org-babel-temporary-directory)
2008 org-babel-temporary-directory)
2009 (make-temp-file "babel-" t))
2010 "Directory to hold temporary files created to execute code blocks.
2011 Used by `org-babel-temp-file'. This directory will be removed on
2012 Emacs shutdown."))
2014 (defun org-babel-temp-file (prefix &optional suffix)
2015 "Create a temporary file in the `org-babel-temporary-directory'.
2016 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2017 value of `temporary-file-directory' temporarily set to the value
2018 of `org-babel-temporary-directory'."
2019 (if (file-remote-p default-directory)
2020 (make-temp-file
2021 (concat (file-remote-p default-directory)
2022 (expand-file-name
2023 prefix temporary-file-directory)
2024 nil suffix))
2025 (let ((temporary-file-directory
2026 (or (and (boundp 'org-babel-temporary-directory)
2027 (file-exists-p org-babel-temporary-directory)
2028 org-babel-temporary-directory)
2029 temporary-file-directory)))
2030 (make-temp-file prefix nil suffix))))
2032 (defun org-babel-remove-temporary-directory ()
2033 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2034 (when (and (boundp 'org-babel-temporary-directory)
2035 (file-exists-p org-babel-temporary-directory))
2036 ;; taken from `delete-directory' in files.el
2037 (condition-case nil
2038 (progn
2039 (mapc (lambda (file)
2040 ;; This test is equivalent to
2041 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2042 ;; but more efficient
2043 (if (eq t (car (file-attributes file)))
2044 (delete-directory file)
2045 (delete-file file)))
2046 ;; We do not want to delete "." and "..".
2047 (directory-files org-babel-temporary-directory 'full
2048 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2049 (delete-directory org-babel-temporary-directory))
2050 (error
2051 (message "Failed to remove temporary Org-babel directory %s"
2052 (if (boundp 'org-babel-temporary-directory)
2053 org-babel-temporary-directory
2054 "[directory not defined]"))))))
2056 (add-hook 'kill-emacs-hook 'org-babel-remove-temporary-directory)
2058 (provide 'ob)
2060 ;; arch-tag: 01a7ebee-06c5-4ee4-a709-e660d28c0af1
2062 ;;; ob.el ends here