New function: Strip text properties
[org-mode.git] / lisp / ob.el
bloba10c8fb2e3e7b77e335b2baa60005f6a0c2bc5c9
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)
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 . "silent") (: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 'quietly))
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 (condition-case nil
867 (org-entry-get (point) header-arg t)
868 (error nil))
869 (cdr (assoc header-arg org-file-properties))))
870 (cons (intern (concat ":" header-arg))
871 (org-babel-read val))))
872 (mapcar
873 'symbol-name
874 (append
875 org-babel-header-arg-names
876 (progn
877 (setq sym (intern (concat "org-babel-header-arg-names:" lang)))
878 (and (boundp sym) (eval sym))))))))))
880 (defun org-babel-params-from-buffer ()
881 "Retrieve per-buffer parameters.
882 Return an association list of any source block params which
883 may be specified in the current buffer."
884 (or org-babel-current-buffer-properties
885 (save-match-data
886 (save-excursion
887 (save-restriction
888 (widen)
889 (goto-char (point-min))
890 (while (re-search-forward
891 (org-make-options-regexp (list "BABEL")) nil t)
892 (setq org-babel-current-buffer-properties
893 (org-babel-merge-params
894 org-babel-current-buffer-properties
895 (org-babel-parse-header-arguments
896 (org-match-string-no-properties 2))))))))))
898 (defvar org-src-preserve-indentation)
899 (defun org-babel-parse-src-block-match ()
900 "Parse the results from a match of the `org-babel-src-block-regexp'."
901 (let* ((block-indentation (length (match-string 1)))
902 (lang (org-babel-clean-text-properties (match-string 2)))
903 (lang-headers (intern (concat "org-babel-default-header-args:" lang)))
904 (switches (match-string 3))
905 (body (org-babel-clean-text-properties (match-string 5)))
906 (preserve-indentation (or org-src-preserve-indentation
907 (string-match "-i\\>" switches))))
908 (list lang
909 ;; get block body less properties, protective commas, and indentation
910 (with-temp-buffer
911 (save-match-data
912 (insert (org-babel-strip-protective-commas body))
913 (unless preserve-indentation (org-do-remove-indentation))
914 (buffer-string)))
915 (org-babel-merge-params
916 org-babel-default-header-args
917 (org-babel-params-from-buffer)
918 (org-babel-params-from-properties lang)
919 (if (boundp lang-headers) (eval lang-headers) nil)
920 (org-babel-parse-header-arguments
921 (org-babel-clean-text-properties (or (match-string 4) ""))))
922 switches
923 block-indentation)))
925 (defun org-babel-parse-inline-src-block-match ()
926 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
927 (let* ((lang (org-babel-clean-text-properties (match-string 2)))
928 (lang-headers (intern (concat "org-babel-default-header-args:" lang))))
929 (list lang
930 (org-babel-strip-protective-commas
931 (org-babel-clean-text-properties (match-string 5)))
932 (org-babel-merge-params
933 org-babel-default-inline-header-args
934 (org-babel-params-from-buffer)
935 (org-babel-params-from-properties lang)
936 (if (boundp lang-headers) (eval lang-headers) nil)
937 (org-babel-parse-header-arguments
938 (org-babel-clean-text-properties (or (match-string 4) "")))))))
940 (defun org-babel-parse-header-arguments (arg-string)
941 "Parse a string of header arguments returning an alist."
942 (when (> (length arg-string) 0)
943 (delq nil
944 (mapcar
945 (lambda (arg)
946 (if (string-match
947 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
948 arg)
949 (cons (intern (match-string 1 arg))
950 (org-babel-read (org-babel-chomp (match-string 2 arg))))
951 (cons (intern (org-babel-chomp arg)) nil)))
952 (let ((balance 0) (partial nil) (lst nil) (last 0))
953 (mapc (lambda (ch) ; split on [] balanced instances of [ \t]:
954 (setq balance (+ balance
955 (cond ((equal 91 ch) 1)
956 ((equal 93 ch) -1)
957 (t 0))))
958 (setq partial (cons ch partial))
959 (when (and (= ch 58) (= balance 0)
960 (or (= last 32) (= last 9)))
961 (setq lst (cons (apply #'string (nreverse (cddr partial)))
962 lst))
963 (setq partial (list ch)))
964 (setq last ch))
965 (string-to-list arg-string))
966 (nreverse (cons (apply #'string (nreverse partial)) lst)))))))
968 (defun org-babel-process-params (params)
969 "Expand variables in PARAMS and add summary parameters."
970 (let* ((vars-and-names (org-babel-disassemble-tables
971 (mapcar (lambda (el)
972 (if (consp (cdr el))
973 (cdr el) (org-babel-ref-parse (cdr el))))
974 (org-babel-get-header params :var))
975 (cdr (assoc :hlines params))
976 (cdr (assoc :colnames params))
977 (cdr (assoc :rownames params))))
978 (result-params (append
979 (split-string (or (cdr (assoc :results params)) ""))
980 (cdr (assoc :result-params params)))))
981 (append
982 (mapcar (lambda (var) (cons :var var)) (car vars-and-names))
983 (list
984 (cons :colname-names (cadr vars-and-names))
985 (cons :rowname-names (caddr vars-and-names))
986 (cons :result-params result-params)
987 (cons :result-type (cond ((member "output" result-params) 'output)
988 ((member "value" result-params) 'value)
989 (t 'value))))
990 (org-babel-get-header params :var 'other))))
992 ;; row and column names
993 (defun org-babel-del-hlines (table)
994 "Remove all 'hlines from TABLE."
995 (remove 'hline table))
997 (defun org-babel-get-colnames (table)
998 "Return the column names of TABLE.
999 Return a cons cell, the `car' of which contains the TABLE less
1000 colnames, and the `cdr' of which contains a list of the column
1001 names."
1002 (if (equal 'hline (nth 1 table))
1003 (cons (cddr table) (car table))
1004 (cons (cdr table) (car table))))
1006 (defun org-babel-get-rownames (table)
1007 "Return the row names of TABLE.
1008 Return a cons cell, the `car' of which contains the TABLE less
1009 colnames, and the `cdr' of which contains a list of the column
1010 names. Note: this function removes any hlines in TABLE."
1011 (flet ((trans (table) (apply #'mapcar* #'list table)))
1012 (let* ((width (apply 'max
1013 (mapcar (lambda (el) (if (listp el) (length el) 0)) table)))
1014 (table (trans (mapcar (lambda (row)
1015 (if (not (equal row 'hline))
1017 (setq row '())
1018 (dotimes (n width)
1019 (setq row (cons 'hline row)))
1020 row))
1021 table))))
1022 (cons (mapcar (lambda (row) (if (equal (car row) 'hline) 'hline row))
1023 (trans (cdr table)))
1024 (remove 'hline (car table))))))
1026 (defun org-babel-put-colnames (table colnames)
1027 "Add COLNAMES to TABLE if they exist."
1028 (if colnames (apply 'list colnames 'hline table) table))
1030 (defun org-babel-put-rownames (table rownames)
1031 "Add ROWNAMES to TABLE if they exist."
1032 (if rownames
1033 (mapcar (lambda (row)
1034 (if (listp row)
1035 (cons (or (pop rownames) "") row)
1036 row)) table)
1037 table))
1039 (defun org-babel-pick-name (names selector)
1040 "Select one out of an alist of row or column names.
1041 SELECTOR can be either a list of names in which case those names
1042 will be returned directly, or an index into the list NAMES in
1043 which case the indexed names will be return."
1044 (if (listp selector)
1045 selector
1046 (when names
1047 (if (and selector (symbolp selector) (not (equal t selector)))
1048 (cdr (assoc selector names))
1049 (if (integerp selector)
1050 (nth (- selector 1) names)
1051 (cdr (car (last names))))))))
1053 (defun org-babel-disassemble-tables (vars hlines colnames rownames)
1054 "Parse tables for further processing.
1055 Process the variables in VARS according to the HLINES,
1056 ROWNAMES and COLNAMES header arguments. Return a list consisting
1057 of the vars, cnames and rnames."
1058 (let (cnames rnames)
1059 (list
1060 (mapcar
1061 (lambda (var)
1062 (when (listp (cdr var))
1063 (when (and (not (equal colnames "no"))
1064 (or colnames (and (equal (nth 1 (cdr var)) 'hline)
1065 (not (member 'hline (cddr (cdr var)))))))
1066 (let ((both (org-babel-get-colnames (cdr var))))
1067 (setq cnames (cons (cons (car var) (cdr both))
1068 cnames))
1069 (setq var (cons (car var) (car both)))))
1070 (when (and rownames (not (equal rownames "no")))
1071 (let ((both (org-babel-get-rownames (cdr var))))
1072 (setq rnames (cons (cons (car var) (cdr both))
1073 rnames))
1074 (setq var (cons (car var) (car both)))))
1075 (when (and hlines (not (equal hlines "yes")))
1076 (setq var (cons (car var) (org-babel-del-hlines (cdr var))))))
1077 var)
1078 vars)
1079 cnames rnames)))
1081 (defun org-babel-reassemble-table (table colnames rownames)
1082 "Add column and row names to a table.
1083 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1084 to the table for reinsertion to org-mode."
1085 (if (listp table)
1086 ((lambda (table)
1087 (if (and colnames (listp (car table)) (= (length (car table))
1088 (length colnames)))
1089 (org-babel-put-colnames table colnames) table))
1090 (if (and rownames (= (length table) (length rownames)))
1091 (org-babel-put-rownames table rownames) table))
1092 table))
1094 (defun org-babel-where-is-src-block-head ()
1095 "Find where the current source block begins.
1096 Return the point at the beginning of the current source
1097 block. Specifically at the beginning of the #+BEGIN_SRC line.
1098 If the point is not on a source block then return nil."
1099 (let ((initial (point)) top bottom)
1101 (save-excursion ;; on a source name line or a #+header line
1102 (beginning-of-line 1)
1103 (and (or (looking-at org-babel-src-name-regexp)
1104 (looking-at org-babel-multi-line-header-regexp))
1105 (progn
1106 (while (and (forward-line 1)
1107 (looking-at org-babel-multi-line-header-regexp)))
1108 (looking-at org-babel-src-block-regexp))
1109 (point)))
1110 (save-excursion ;; on a #+begin_src line
1111 (beginning-of-line 1)
1112 (and (looking-at org-babel-src-block-regexp)
1113 (point)))
1114 (save-excursion ;; inside a src block
1115 (and
1116 (re-search-backward "^[ \t]*#\\+begin_src" nil t) (setq top (point))
1117 (re-search-forward "^[ \t]*#\\+end_src" nil t) (setq bottom (point))
1118 (< top initial) (< initial bottom)
1119 (progn (goto-char top) (beginning-of-line 1)
1120 (looking-at org-babel-src-block-regexp))
1121 (point))))))
1123 ;;;###autoload
1124 (defun org-babel-goto-src-block-head ()
1125 "Go to the beginning of the current code block."
1126 (interactive)
1127 ((lambda (head)
1128 (if head (goto-char head) (error "not currently in a code block")))
1129 (org-babel-where-is-src-block-head)))
1131 ;;;###autoload
1132 (defun org-babel-goto-named-src-block (name)
1133 "Go to a named source-code block."
1134 (interactive
1135 (let ((completion-ignore-case t))
1136 (list (org-icompleting-read "source-block name: "
1137 (org-babel-src-block-names) nil t))))
1138 (let ((point (org-babel-find-named-block name)))
1139 (if point
1140 ;; taken from `org-open-at-point'
1141 (progn (goto-char point) (org-show-context))
1142 (message "source-code block '%s' not found in this buffer" name))))
1144 (defun org-babel-find-named-block (name)
1145 "Find a named source-code block.
1146 Return the location of the source block identified by source
1147 NAME, or nil if no such block exists. Set match data according to
1148 org-babel-named-src-block-regexp."
1149 (save-excursion
1150 (let ((case-fold-search t)
1151 (regexp (org-babel-named-src-block-regexp-for-name name)) msg)
1152 (goto-char (point-min))
1153 (when (or (re-search-forward regexp nil t)
1154 (re-search-backward regexp nil t))
1155 (match-beginning 0)))))
1157 (defun org-babel-src-block-names (&optional file)
1158 "Returns the names of source blocks in FILE or the current buffer."
1159 (save-excursion
1160 (when file (find-file file)) (goto-char (point-min))
1161 (let (names)
1162 (while (re-search-forward org-babel-src-name-w-name-regexp nil t)
1163 (setq names (cons (org-babel-clean-text-properties (match-string 4))
1164 names)))
1165 names)))
1167 ;;;###autoload
1168 (defun org-babel-goto-named-result (name)
1169 "Go to a named result."
1170 (interactive
1171 (let ((completion-ignore-case t))
1172 (list (org-icompleting-read "source-block name: "
1173 (org-babel-result-names) nil t))))
1174 (let ((point (org-babel-find-named-result name)))
1175 (if point
1176 ;; taken from `org-open-at-point'
1177 (progn (goto-char point) (org-show-context))
1178 (message "result '%s' not found in this buffer" name))))
1180 (defun org-babel-find-named-result (name)
1181 "Find a named result.
1182 Return the location of the result named NAME in the current
1183 buffer or nil if no such result exists."
1184 (save-excursion
1185 (goto-char (point-min))
1186 (when (re-search-forward
1187 (concat org-babel-result-regexp
1188 "[ \t]" (regexp-quote name) "[ \t\n\f\v\r]") nil t)
1189 (beginning-of-line 0) (point))))
1191 (defun org-babel-result-names (&optional file)
1192 "Returns the names of results in FILE or the current buffer."
1193 (save-excursion
1194 (when file (find-file file)) (goto-char (point-min))
1195 (let (names)
1196 (while (re-search-forward org-babel-result-w-name-regexp nil t)
1197 (setq names (cons (org-babel-clean-text-properties (match-string 4))
1198 names)))
1199 names)))
1201 ;;;###autoload
1202 (defun org-babel-next-src-block (&optional arg)
1203 "Jump to the next source block.
1204 With optional prefix argument ARG, jump forward ARG many source blocks."
1205 (interactive "P")
1206 (when (looking-at org-babel-src-block-regexp) (forward-char 1))
1207 (condition-case nil
1208 (re-search-forward org-babel-src-block-regexp nil nil (or arg 1))
1209 (error (error "No further code blocks")))
1210 (goto-char (match-beginning 0)) (org-show-context))
1212 ;;;###autoload
1213 (defun org-babel-previous-src-block (&optional arg)
1214 "Jump to the previous source block.
1215 With optional prefix argument ARG, jump backward ARG many source blocks."
1216 (interactive "P")
1217 (condition-case nil
1218 (re-search-backward org-babel-src-block-regexp nil nil (or arg 1))
1219 (error (error "No previous code blocks")))
1220 (goto-char (match-beginning 0)) (org-show-context))
1222 (defvar org-babel-load-languages)
1224 ;;;###autoload
1225 (defun org-babel-mark-block ()
1226 "Mark current src block"
1227 (interactive)
1228 ((lambda (head)
1229 (when head
1230 (save-excursion
1231 (goto-char head)
1232 (looking-at org-babel-src-block-regexp))
1233 (push-mark (match-end 5) nil t)
1234 (goto-char (match-beginning 5))))
1235 (org-babel-where-is-src-block-head)))
1237 (defun org-babel-demarcate-block (&optional arg)
1238 "Wrap or split the code in the region or on the point.
1239 When called from inside of a code block the current block is
1240 split. When called from outside of a code block a new code block
1241 is created. In both cases if the region is demarcated and if the
1242 region is not active then the point is demarcated."
1243 (interactive "P")
1244 (let ((info (org-babel-get-src-block-info 'light))
1245 (stars (concat (make-string (or (org-current-level) 1) ?*) " ")))
1246 (if info
1247 (mapc
1248 (lambda (place)
1249 (save-excursion
1250 (goto-char place)
1251 (let ((lang (nth 0 info))
1252 (indent (make-string (nth 5 info) ? )))
1253 (when (string-match "^[[:space:]]*$"
1254 (buffer-substring (point-at-bol)
1255 (point-at-eol)))
1256 (delete-region (point-at-bol) (point-at-eol)))
1257 (insert (concat (if (looking-at "^") "" "\n")
1258 indent "#+end_src\n"
1259 (if arg stars indent) "\n"
1260 indent "#+begin_src " lang
1261 (if (looking-at "[\n\r]") "" "\n")))))
1262 (move-end-of-line 2))
1263 (sort (if (region-active-p) (list (mark) (point)) (list (point))) #'>))
1264 (let ((start (point))
1265 (lang (org-icompleting-read "Lang: "
1266 (mapcar (lambda (el) (symbol-name (car el)))
1267 org-babel-load-languages)))
1268 (body (delete-and-extract-region
1269 (if (region-active-p) (mark) (point)) (point))))
1270 (insert (concat (if (looking-at "^") "" "\n")
1271 (if arg (concat stars "\n") "")
1272 "#+begin_src " lang "\n"
1273 body
1274 (if (or (= (length body) 0)
1275 (string-match "[\r\n]$" body)) "" "\n")
1276 "#+end_src\n"))
1277 (goto-char start) (move-end-of-line 1)))))
1279 (defvar org-babel-lob-one-liner-regexp)
1280 (defun org-babel-where-is-src-block-result (&optional insert info hash indent)
1281 "Find where the current source block results begin.
1282 Return the point at the beginning of the result of the current
1283 source block. Specifically at the beginning of the results line.
1284 If no result exists for this block then create a results line
1285 following the source block."
1286 (save-excursion
1287 (let* ((on-lob-line (save-excursion
1288 (beginning-of-line 1)
1289 (looking-at org-babel-lob-one-liner-regexp)))
1290 (inlinep (save-excursion
1291 (re-search-backward "[ \f\t\n\r\v]" nil t)
1292 (when (looking-at org-babel-inline-src-block-regexp)
1293 (match-end 0))))
1294 (name (if on-lob-line
1295 (nth 0 (org-babel-lob-get-info))
1296 (nth 4 (or info (org-babel-get-src-block-info)))))
1297 (head (unless on-lob-line (org-babel-where-is-src-block-head)))
1298 found beg end)
1299 (when head (goto-char head))
1300 (setq
1301 found ;; was there a result (before we potentially insert one)
1303 inlinep
1304 (and
1305 ;; named results:
1306 ;; - return t if it is found, else return nil
1307 ;; - if it does not need to be rebuilt, then don't set end
1308 ;; - if it does need to be rebuilt then do set end
1309 name (setq beg (org-babel-find-named-result name))
1310 (prog1 beg
1311 (when (and hash (not (string= hash (match-string 3))))
1312 (goto-char beg) (setq end beg) ;; beginning of result
1313 (forward-line 1)
1314 (delete-region end (org-babel-result-end)) nil)))
1315 (and
1316 ;; unnamed results:
1317 ;; - return t if it is found, else return nil
1318 ;; - if it is found, and the hash doesn't match, delete and set end
1319 (or on-lob-line (re-search-forward "^[ \t]*#\\+end_src" nil t))
1320 (progn (end-of-line 1)
1321 (if (eobp) (insert "\n") (forward-char 1))
1322 (setq end (point))
1323 (or (and (not name)
1324 (progn ;; unnamed results line already exists
1325 (re-search-forward "[^ \f\t\n\r\v]" nil t)
1326 (beginning-of-line 1)
1327 (looking-at
1328 (concat org-babel-result-regexp "\n")))
1329 (prog1 (point)
1330 ;; must remove and rebuild if hash!=old-hash
1331 (if (and hash (not (string= hash (match-string 3))))
1332 (prog1 nil
1333 (forward-line 1)
1334 (delete-region
1335 end (org-babel-result-end)))
1336 (setq end nil)))))))))
1337 (if (and insert end)
1338 (progn
1339 (goto-char end)
1340 (unless beg
1341 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1342 (insert (concat
1343 (if indent
1344 (mapconcat
1345 (lambda (el) " ")
1346 (org-number-sequence 1 indent) "")
1348 "#+results"
1349 (when hash (concat "["hash"]"))
1351 (when name (concat " " name)) "\n"))
1352 (unless beg (insert "\n") (backward-char))
1353 (beginning-of-line 0)
1354 (if hash (org-babel-hide-hash))
1355 (point))
1356 found))))
1358 (defvar org-block-regexp)
1359 (defun org-babel-read-result ()
1360 "Read the result at `point' into emacs-lisp."
1361 (let ((case-fold-search t) result-string)
1362 (cond
1363 ((org-at-table-p) (org-babel-read-table))
1364 ((org-in-item-p) (org-babel-read-list))
1365 ((looking-at org-bracket-link-regexp) (org-babel-read-link))
1366 ((looking-at org-block-regexp) (org-babel-trim (match-string 4)))
1367 ((looking-at "^[ \t]*: ")
1368 (setq result-string
1369 (org-babel-trim
1370 (mapconcat (lambda (line)
1371 (if (and (> (length line) 1)
1372 (string-match "^[ \t]*: \\(.+\\)" line))
1373 (match-string 1 line)
1374 line))
1375 (split-string
1376 (buffer-substring
1377 (point) (org-babel-result-end)) "[\r\n]+")
1378 "\n")))
1379 (or (org-babel-number-p result-string) result-string))
1380 ((looking-at org-babel-result-regexp)
1381 (save-excursion (forward-line 1) (org-babel-read-result))))))
1383 (defun org-babel-read-table ()
1384 "Read the table at `point' into emacs-lisp."
1385 (mapcar (lambda (row)
1386 (if (and (symbolp row) (equal row 'hline)) row
1387 (mapcar #'org-babel-read row)))
1388 (org-table-to-lisp)))
1390 (defun org-babel-read-list ()
1391 "Read the list at `point' into emacs-lisp."
1392 (mapcar #'org-babel-read (cdr (org-list-parse-list))))
1394 (defvar org-link-types-re)
1395 (defun org-babel-read-link ()
1396 "Read the link at `point' into emacs-lisp.
1397 If the path of the link is a file path it is expanded using
1398 `expand-file-name'."
1399 (let* ((case-fold-search t)
1400 (raw (and (looking-at org-bracket-link-regexp)
1401 (org-babel-clean-text-properties (match-string 1))))
1402 (type (and (string-match org-link-types-re raw)
1403 (match-string 1 raw))))
1404 (cond
1405 ((not type) (expand-file-name raw))
1406 ((string= type "file")
1407 (and (string-match "file\\(.*\\):\\(.+\\)" raw)
1408 (expand-file-name (match-string 2 raw))))
1409 (t raw))))
1411 (defun org-babel-format-result (result &optional sep)
1412 "Format RESULT for writing to file."
1413 (flet ((echo-res (result)
1414 (if (stringp result) result (format "%S" result))))
1415 (if (listp result)
1416 ;; table result
1417 (orgtbl-to-generic
1418 result
1419 (list
1420 :sep (or sep "\t")
1421 :fmt 'echo-res))
1422 ;; scalar result
1423 (echo-res result))))
1425 (defun org-babel-insert-result
1426 (result &optional result-params info hash indent lang)
1427 "Insert RESULT into the current buffer.
1428 By default RESULT is inserted after the end of the
1429 current source block. With optional argument RESULT-PARAMS
1430 controls insertion of results in the org-mode file.
1431 RESULT-PARAMS can take the following values...
1433 replace - (default option) insert results after the source block
1434 replacing any previously inserted results
1436 silent -- no results are inserted
1438 file ---- the results are interpreted as a file path, and are
1439 inserted into the buffer using the Org-mode file syntax
1441 list ---- the results are interpreted as an Org-mode list.
1443 raw ----- results are added directly to the Org-mode file. This
1444 is a good option if you code block will output org-mode
1445 formatted text.
1447 org ----- similar in effect to raw, only the results are wrapped
1448 in an org code block. Similar to the raw option, on
1449 export the results will be interpreted as org-formatted
1450 text, however by wrapping the results in an org code
1451 block they can be replaced upon re-execution of the
1452 code block.
1454 html ---- results are added inside of a #+BEGIN_HTML block. This
1455 is a good option if you code block will output html
1456 formatted text.
1458 latex --- results are added inside of a #+BEGIN_LATEX block.
1459 This is a good option if you code block will output
1460 latex formatted text.
1462 code ---- the results are extracted in the syntax of the source
1463 code of the language being evaluated and are added
1464 inside of a #+BEGIN_SRC block with the source-code
1465 language set appropriately. Note this relies on the
1466 optional LANG argument."
1467 (if (stringp result)
1468 (progn
1469 (setq result (org-babel-clean-text-properties result))
1470 (when (member "file" result-params)
1471 (setq result (org-babel-result-to-file result))))
1472 (unless (listp result) (setq result (format "%S" result))))
1473 (if (and result-params (member "silent" result-params))
1474 (progn
1475 (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
1476 result)
1477 (save-excursion
1478 (let* ((inlinep (save-excursion
1479 (re-search-backward "[ \f\t\n\r\v]" nil t)
1480 (when (looking-at org-babel-inline-src-block-regexp)
1481 (goto-char (match-end 0))
1482 (insert (if (listp result) "\n" " "))
1483 (point))))
1484 (existing-result (unless inlinep
1485 (org-babel-where-is-src-block-result
1486 t info hash indent)))
1487 (results-switches
1488 (cdr (assoc :results_switches (nth 2 info))))
1489 beg end)
1490 (when (and (stringp result) ; ensure results end in a newline
1491 (not inlinep)
1492 (> (length result) 0)
1493 (not (or (string-equal (substring result -1) "\n")
1494 (string-equal (substring result -1) "\r"))))
1495 (setq result (concat result "\n")))
1496 (if (not existing-result)
1497 (setq beg (or inlinep (point)))
1498 (goto-char existing-result)
1499 (save-excursion
1500 (re-search-forward "#" nil t)
1501 (setq indent (- (current-column) 1)))
1502 (forward-line 1)
1503 (setq beg (point))
1504 (cond
1505 ((member "replace" result-params)
1506 (delete-region (point) (org-babel-result-end)))
1507 ((member "append" result-params)
1508 (goto-char (org-babel-result-end)) (setq beg (point-marker)))
1509 ((member "prepend" result-params)))) ; already there
1510 (setq results-switches
1511 (if results-switches (concat " " results-switches) ""))
1512 ;; insert results based on type
1513 (cond
1514 ;; do nothing for an empty result
1515 ((= (length result) 0))
1516 ;; insert a list if preferred
1517 ((member "list" result-params)
1518 (insert
1519 (org-babel-trim
1520 (org-list-to-generic (cons 'unordered
1521 (if (listp result) result (list result)))
1522 '(:splicep nil :istart "- " :iend "\n")))))
1523 ;; assume the result is a table if it's not a string
1524 ((not (stringp result))
1525 (goto-char beg)
1526 (insert (concat (orgtbl-to-orgtbl
1527 (if (or (eq 'hline (car result))
1528 (and (listp (car result))
1529 (listp (cdr (car result)))))
1530 result (list result))
1531 '(:fmt (lambda (cell) (format "%s" cell)))) "\n"))
1532 (goto-char beg) (when (org-at-table-p) (org-table-align)))
1533 ((member "file" result-params)
1534 (insert result))
1535 (t (goto-char beg) (insert result)))
1536 (when (listp result) (goto-char (org-table-end)))
1537 (setq end (point-marker))
1538 ;; possibly wrap result
1539 (flet ((wrap (start finish)
1540 (goto-char beg) (insert (concat start "\n"))
1541 (goto-char end) (insert (concat finish "\n"))
1542 (setq end (point-marker))))
1543 (cond
1544 ((member "html" result-params)
1545 (wrap "#+BEGIN_HTML" "#+END_HTML"))
1546 ((member "latex" result-params)
1547 (wrap "#+BEGIN_LaTeX" "#+END_LaTeX"))
1548 ((member "code" result-params)
1549 (wrap (format "#+BEGIN_SRC %s%s" (or lang "none") results-switches)
1550 "#+END_SRC"))
1551 ((member "org" result-params)
1552 (wrap "#+BEGIN_ORG" "#+END_ORG"))
1553 ((member "raw" result-params)
1554 (goto-char beg) (if (org-at-table-p) (org-cycle)))
1555 ((member "wrap" result-params)
1556 (when (and (stringp result) (not (member "file" result-params)))
1557 (org-babel-examplize-region beg end results-switches))
1558 (wrap "#+BEGIN_RESULT" "#+END_RESULT"))
1559 ((and (stringp result) (not (member "file" result-params)))
1560 (org-babel-examplize-region beg end results-switches)
1561 (setq end (point)))))
1562 ;; possibly indent the results to match the #+results line
1563 (when (and (not inlinep) indent (> indent 0)
1564 ;; in this case `table-align' does the work for us
1565 (not (and (listp result)
1566 (member "append" result-params))))
1567 (indent-rigidly beg end indent))))
1568 (if (= (length result) 0)
1569 (if (member "value" result-params)
1570 (message "Code block returned no value.")
1571 (message "Code block produced no output."))
1572 (message "Code block evaluation complete."))))
1574 (defun org-babel-remove-result (&optional info)
1575 "Remove the result of the current source block."
1576 (interactive)
1577 (let ((location (org-babel-where-is-src-block-result nil info)) start)
1578 (when location
1579 (save-excursion
1580 (goto-char location) (setq start (point)) (forward-line 1)
1581 (delete-region start (org-babel-result-end))))))
1583 (defun org-babel-result-end ()
1584 "Return the point at the end of the current set of results"
1585 (save-excursion
1586 (cond
1587 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
1588 ((org-at-item-p) (- (org-list-bottom-point) 1))
1590 (let ((case-fold-search t)
1591 (blocks-re (regexp-opt
1592 (list "latex" "html" "example" "src" "result" "org"))))
1593 (if (looking-at (concat "[ \t]*#\\+begin_" blocks-re))
1594 (progn (re-search-forward (concat "[ \t]*#\\+end_" blocks-re) nil t)
1595 (forward-char 1))
1596 (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
1597 (forward-line 1))))
1598 (point)))))
1600 (defun org-babel-result-to-file (result)
1601 "Convert RESULT into an `org-mode' link.
1602 If the `default-directory' is different from the containing
1603 file's directory then expand relative links."
1604 (flet ((cond-exp (file)
1605 (if (and default-directory
1606 buffer-file-name
1607 (not (string= (expand-file-name default-directory)
1608 (expand-file-name
1609 (file-name-directory buffer-file-name)))))
1610 (expand-file-name file default-directory)
1611 file)))
1612 (if (stringp result)
1613 (format "[[file:%s]]" (cond-exp result))
1614 (when (and (listp result) (= 2 (length result))
1615 (stringp (car result)) (stringp (cadr result)))
1616 (format "[[file:%s][%s]]" (car result) (cadr result))))))
1618 (defun org-babel-examplize-region (beg end &optional results-switches)
1619 "Comment out region using the inline '==' or ': ' org example quote."
1620 (interactive "*r")
1621 (flet ((chars-between (b e) (string-match "[\\S]" (buffer-substring b e))))
1622 (if (or (chars-between (save-excursion (goto-char beg) (point-at-bol)) beg)
1623 (chars-between end (save-excursion (goto-char end) (point-at-eol))))
1624 (save-excursion
1625 (goto-char beg)
1626 (insert (format "=%s=" (prog1 (buffer-substring beg end)
1627 (delete-region beg end)))))
1628 (let ((size (count-lines beg end)))
1629 (save-excursion
1630 (cond ((= size 0)) ; do nothing for an empty result
1631 ((< size org-babel-min-lines-for-block-output)
1632 (goto-char beg)
1633 (dotimes (n size)
1634 (beginning-of-line 1) (insert ": ") (forward-line 1)))
1636 (goto-char beg)
1637 (insert (if results-switches
1638 (format "#+begin_example%s\n" results-switches)
1639 "#+begin_example\n"))
1640 (if (markerp end) (goto-char end) (forward-char (- end beg)))
1641 (insert "#+end_example\n"))))))))
1643 (defun org-babel-update-block-body (new-body)
1644 "Update the body of the current code block to NEW-BODY."
1645 (if (not (org-babel-where-is-src-block-head))
1646 (error "not in source block")
1647 (save-match-data
1648 (replace-match (concat (org-babel-trim new-body) "\n") nil t nil 5))
1649 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
1651 (defun org-babel-merge-params (&rest plists)
1652 "Combine all parameter association lists in PLISTS.
1653 Later elements of PLISTS override the values of previous elements.
1654 This takes into account some special considerations for certain
1655 parameters when merging lists."
1656 (let ((results-exclusive-groups
1657 '(("file" "list" "vector" "table" "scalar" "raw" "org"
1658 "html" "latex" "code" "pp" "wrap")
1659 ("replace" "silent" "append" "prepend")
1660 ("output" "value")))
1661 (exports-exclusive-groups
1662 '(("code" "results" "both" "none")))
1663 params results exports tangle noweb cache vars shebang comments)
1664 (flet ((e-merge (exclusive-groups &rest result-params)
1665 ;; maintain exclusivity of mutually exclusive parameters
1666 (let (output)
1667 (mapc (lambda (new-params)
1668 (mapc (lambda (new-param)
1669 (mapc (lambda (exclusive-group)
1670 (when (member new-param exclusive-group)
1671 (mapcar (lambda (excluded-param)
1672 (setq output
1673 (delete
1674 excluded-param
1675 output)))
1676 exclusive-group)))
1677 exclusive-groups)
1678 (setq output (org-uniquify
1679 (cons new-param output))))
1680 new-params))
1681 result-params)
1682 output)))
1683 (mapc
1684 (lambda (plist)
1685 (mapc
1686 (lambda (pair)
1687 (case (car pair)
1688 (:var
1689 (let ((name (if (listp (cdr pair))
1690 (cadr pair)
1691 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
1692 (cdr pair))
1693 (intern (match-string 1 (cdr pair)))))))
1694 (when name
1695 (setq vars
1696 (cons (cons name pair)
1697 (if (member name (mapcar #'car vars))
1698 (delq nil
1699 (mapcar
1700 (lambda (p) (unless (equal (car p) name) p))
1701 vars))
1702 vars))))))
1703 (:results
1704 (setq results (e-merge results-exclusive-groups
1705 results (split-string (cdr pair)))))
1706 (:file
1707 (when (cdr pair)
1708 (setq results (e-merge results-exclusive-groups
1709 results '("file")))
1710 (unless (or (member "both" exports)
1711 (member "none" exports)
1712 (member "code" exports))
1713 (setq exports (e-merge exports-exclusive-groups
1714 exports '("results"))))
1715 (setq params (cons pair (assq-delete-all (car pair) params)))))
1716 (:exports
1717 (setq exports (e-merge exports-exclusive-groups
1718 exports (split-string (cdr pair)))))
1719 (:tangle ;; take the latest -- always overwrite
1720 (setq tangle (or (list (cdr pair)) tangle)))
1721 (:noweb
1722 (setq noweb (e-merge '(("yes" "no" "tangle")) noweb
1723 (split-string (or (cdr pair) "")))))
1724 (:cache
1725 (setq cache (e-merge '(("yes" "no")) cache
1726 (split-string (or (cdr pair) "")))))
1727 (:shebang ;; take the latest -- always overwrite
1728 (setq shebang (or (list (cdr pair)) shebang)))
1729 (:comments
1730 (setq comments (e-merge '(("yes" "no")) comments
1731 (split-string (or (cdr pair) "")))))
1732 (t ;; replace: this covers e.g. :session
1733 (setq params (cons pair (assq-delete-all (car pair) params))))))
1734 plist))
1735 plists))
1736 (while vars (setq params (cons (cons :var (cddr (pop vars))) params)))
1737 (cons (cons :comments (mapconcat 'identity comments " "))
1738 (cons (cons :shebang (mapconcat 'identity shebang " "))
1739 (cons (cons :cache (mapconcat 'identity cache " "))
1740 (cons (cons :noweb (mapconcat 'identity noweb " "))
1741 (cons (cons :tangle (mapconcat 'identity tangle " "))
1742 (cons (cons :exports
1743 (mapconcat 'identity exports " "))
1744 (cons
1745 (cons :results
1746 (mapconcat 'identity results " "))
1747 params)))))))))
1749 (defun org-babel-expand-noweb-references (&optional info parent-buffer)
1750 "Expand Noweb references in the body of the current source code block.
1752 For example the following reference would be replaced with the
1753 body of the source-code block named 'example-block'.
1755 <<example-block>>
1757 Note that any text preceding the <<foo>> construct on a line will
1758 be interposed between the lines of the replacement text. So for
1759 example if <<foo>> is placed behind a comment, then the entire
1760 replacement text will also be commented.
1762 This function must be called from inside of the buffer containing
1763 the source-code block which holds BODY.
1765 In addition the following syntax can be used to insert the
1766 results of evaluating the source-code block named 'example-block'.
1768 <<example-block()>>
1770 Any optional arguments can be passed to example-block by placing
1771 the arguments inside the parenthesis following the convention
1772 defined by `org-babel-lob'. For example
1774 <<example-block(a=9)>>
1776 would set the value of argument \"a\" equal to \"9\". Note that
1777 these arguments are not evaluated in the current source-code
1778 block but are passed literally to the \"example-block\"."
1779 (let* ((parent-buffer (or parent-buffer (current-buffer)))
1780 (info (or info (org-babel-get-src-block-info)))
1781 (lang (nth 0 info))
1782 (body (nth 1 info))
1783 (comment (string= "noweb" (cdr (assoc :comments (nth 2 info)))))
1784 (new-body "") index source-name evaluate prefix)
1785 (flet ((nb-add (text) (setq new-body (concat new-body text)))
1786 (c-wrap (text)
1787 (with-temp-buffer
1788 (funcall (intern (concat lang "-mode")))
1789 (comment-region (point) (progn (insert text) (point)))
1790 (org-babel-trim (buffer-string)))))
1791 (with-temp-buffer
1792 (insert body) (goto-char (point-min))
1793 (setq index (point))
1794 (while (and (re-search-forward "<<\\(.+?\\)>>" nil t))
1795 (save-match-data (setf source-name (match-string 1)))
1796 (save-match-data (setq evaluate (string-match "\(.*\)" source-name)))
1797 (save-match-data
1798 (setq prefix
1799 (buffer-substring (match-beginning 0)
1800 (save-excursion
1801 (beginning-of-line 1) (point)))))
1802 ;; add interval to new-body (removing noweb reference)
1803 (goto-char (match-beginning 0))
1804 (nb-add (buffer-substring index (point)))
1805 (goto-char (match-end 0))
1806 (setq index (point))
1807 (nb-add
1808 (with-current-buffer parent-buffer
1809 (mapconcat ;; interpose PREFIX between every line
1810 #'identity
1811 (split-string
1812 (if evaluate
1813 (let ((raw (org-babel-ref-resolve source-name)))
1814 (if (stringp raw) raw (format "%S" raw)))
1815 (or (nth 2 (assoc (intern source-name)
1816 org-babel-library-of-babel))
1817 (save-restriction
1818 (widen)
1819 (let ((point (org-babel-find-named-block
1820 source-name)))
1821 (if point
1822 (save-excursion
1823 (goto-char point)
1824 ;; possibly wrap body in comments
1825 (let* ((i (org-babel-get-src-block-info 'light))
1826 (body (org-babel-trim
1827 (org-babel-expand-noweb-references
1828 i))))
1829 (if comment
1830 ((lambda (cs) (concat (c-wrap (car cs)) "\n"
1831 body
1832 "\n" (c-wrap (cadr cs))))
1833 (org-babel-tangle-comment-links i))
1834 body)))
1835 ;; optionally raise an error if named
1836 ;; source-block doesn't exist
1837 (if (member lang org-babel-noweb-error-langs)
1838 (error "%s"
1839 (concat
1840 "<<" source-name ">> "
1841 "could not be resolved (see "
1842 "`org-babel-noweb-error-langs')"))
1843 ""))))))
1844 "[\n\r]") (concat "\n" prefix)))))
1845 (nb-add (buffer-substring index (point-max)))))
1846 new-body))
1848 (defun org-babel-clean-text-properties (text)
1849 "Strip all properties from text return."
1850 (when text
1851 (set-text-properties 0 (length text) nil text) text))
1853 (defun org-babel-strip-protective-commas (body)
1854 "Strip protective commas from bodies of source blocks."
1855 (replace-regexp-in-string "^,#" "#" body))
1857 (defun org-babel-script-escape (str)
1858 "Safely convert tables into elisp lists."
1859 (let (in-single in-double out)
1860 (org-babel-read
1861 (if (and (stringp str) (string-match "^\\[.+\\]$" str))
1862 (org-babel-read
1863 (concat
1865 (progn
1866 (mapc
1867 (lambda (ch)
1868 (setq
1870 (case ch
1871 (91 (if (or in-double in-single) ; [
1872 (cons 91 out)
1873 (cons 40 out)))
1874 (93 (if (or in-double in-single) ; ]
1875 (cons 93 out)
1876 (cons 41 out)))
1877 (44 (if (or in-double in-single) ; ,
1878 (cons 44 out) (cons 32 out)))
1879 (39 (if in-double ; '
1880 (cons 39 out)
1881 (setq in-single (not in-single)) (cons 34 out)))
1882 (34 (if in-single ; "
1883 (append (list 34 32) out)
1884 (setq in-double (not in-double)) (cons 34 out)))
1885 (t (cons ch out)))))
1886 (string-to-list str))
1887 (apply #'string (reverse out)))))
1888 str))))
1890 (defun org-babel-read (cell)
1891 "Convert the string value of CELL to a number if appropriate.
1892 Otherwise if cell looks like lisp (meaning it starts with a
1893 \"(\" or a \"'\") then read it as lisp, otherwise return it
1894 unmodified as a string.
1896 This is taken almost directly from `org-read-prop'."
1897 (if (and (stringp cell) (not (equal cell "")))
1898 (or (org-babel-number-p cell)
1899 (if (or (equal "(" (substring cell 0 1))
1900 (equal "'" (substring cell 0 1))
1901 (equal "`" (substring cell 0 1)))
1902 (eval (read cell))
1903 (progn (set-text-properties 0 (length cell) nil cell) cell)))
1904 cell))
1906 (defun org-babel-number-p (string)
1907 "If STRING represents a number return it's value."
1908 (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string)
1909 (= (length (substring string (match-beginning 0)
1910 (match-end 0)))
1911 (length string)))
1912 (string-to-number string)))
1914 (defun org-babel-import-elisp-from-file (file-name &optional separator)
1915 "Read the results located at FILE-NAME into an elisp table.
1916 If the table is trivial, then return it as a scalar."
1917 (let (result)
1918 (save-window-excursion
1919 (with-temp-buffer
1920 (condition-case nil
1921 (progn
1922 (org-table-import file-name separator)
1923 (delete-file file-name)
1924 (setq result (mapcar (lambda (row)
1925 (mapcar #'org-babel-string-read row))
1926 (org-table-to-lisp))))
1927 (error nil)))
1928 (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
1929 (if (consp (car result))
1930 (if (null (cdr (car result)))
1931 (caar result)
1932 result)
1933 (car result))
1934 result))))
1936 (defun org-babel-string-read (cell)
1937 "Strip nested \"s from around strings."
1938 (org-babel-read (or (and (stringp cell)
1939 (string-match "\\\"\\(.+\\)\\\"" cell)
1940 (match-string 1 cell))
1941 cell)))
1943 (defun org-babel-reverse-string (string)
1944 "Return the reverse of STRING."
1945 (apply 'string (reverse (string-to-list string))))
1947 (defun org-babel-chomp (string &optional regexp)
1948 "Strip trailing spaces and carriage returns from STRING.
1949 Default regexp used is \"[ \f\t\n\r\v]\" but can be
1950 overwritten by specifying a regexp as a second argument."
1951 (let ((regexp (or regexp "[ \f\t\n\r\v]")))
1952 (while (and (> (length string) 0)
1953 (string-match regexp (substring string -1)))
1954 (setq string (substring string 0 -1)))
1955 string))
1957 (defun org-babel-trim (string &optional regexp)
1958 "Strip leading and trailing spaces and carriage returns from STRING.
1959 Like `org-babel-chomp' only it runs on both the front and back
1960 of the string."
1961 (org-babel-chomp (org-babel-reverse-string
1962 (org-babel-chomp (org-babel-reverse-string string) regexp))
1963 regexp))
1965 (defvar org-babel-org-babel-call-process-region-original nil)
1966 (defun org-babel-tramp-handle-call-process-region
1967 (start end program &optional delete buffer display &rest args)
1968 "Use tramp to handle call-process-region.
1969 Fixes a bug in `tramp-handle-call-process-region'."
1970 (if (and (featurep 'tramp) (file-remote-p default-directory))
1971 (let ((tmpfile (tramp-compat-make-temp-file "")))
1972 (write-region start end tmpfile)
1973 (when delete (delete-region start end))
1974 (unwind-protect
1975 ;; (apply 'call-process program tmpfile buffer display args)
1976 ;; bug in tramp
1977 (apply 'process-file program tmpfile buffer display args)
1978 (delete-file tmpfile)))
1979 ;; org-babel-call-process-region-original is the original emacs
1980 ;; definition. It is in scope from the let binding in
1981 ;; org-babel-execute-src-block
1982 (apply org-babel-call-process-region-original
1983 start end program delete buffer display args)))
1985 (defun org-babel-local-file-name (file)
1986 "Return the local name component of FILE."
1987 (if (file-remote-p file)
1988 (let (localname)
1989 (with-parsed-tramp-file-name file nil
1990 localname))
1991 file))
1993 (defun org-babel-process-file-name (name &optional no-quote-p)
1994 "Prepare NAME to be used in an external process.
1995 If NAME specifies a remote location, the remote portion of the
1996 name is removed, since in that case the process will be executing
1997 remotely. The file name is then processed by
1998 `expand-file-name'. Unless second argument NO-QUOTE-P is non-nil,
1999 the file name is additionally processed by
2000 `shell-quote-argument'"
2001 ((lambda (f) (if no-quote-p f (shell-quote-argument f)))
2002 (expand-file-name (org-babel-local-file-name name))))
2004 (defvar org-babel-temporary-directory)
2005 (unless (or noninteractive (boundp 'org-babel-temporary-directory))
2006 (defvar org-babel-temporary-directory
2007 (or (and (boundp 'org-babel-temporary-directory)
2008 (file-exists-p org-babel-temporary-directory)
2009 org-babel-temporary-directory)
2010 (make-temp-file "babel-" t))
2011 "Directory to hold temporary files created to execute code blocks.
2012 Used by `org-babel-temp-file'. This directory will be removed on
2013 Emacs shutdown."))
2015 (defun org-babel-temp-file (prefix &optional suffix)
2016 "Create a temporary file in the `org-babel-temporary-directory'.
2017 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2018 value of `temporary-file-directory' temporarily set to the value
2019 of `org-babel-temporary-directory'."
2020 (if (file-remote-p default-directory)
2021 (make-temp-file
2022 (concat (file-remote-p default-directory)
2023 (expand-file-name
2024 prefix temporary-file-directory)
2025 nil suffix))
2026 (let ((temporary-file-directory
2027 (or (and (boundp 'org-babel-temporary-directory)
2028 (file-exists-p org-babel-temporary-directory)
2029 org-babel-temporary-directory)
2030 temporary-file-directory)))
2031 (make-temp-file prefix nil suffix))))
2033 (defun org-babel-remove-temporary-directory ()
2034 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2035 (when (and (boundp 'org-babel-temporary-directory)
2036 (file-exists-p org-babel-temporary-directory))
2037 ;; taken from `delete-directory' in files.el
2038 (condition-case nil
2039 (progn
2040 (mapc (lambda (file)
2041 ;; This test is equivalent to
2042 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2043 ;; but more efficient
2044 (if (eq t (car (file-attributes file)))
2045 (delete-directory file)
2046 (delete-file file)))
2047 ;; We do not want to delete "." and "..".
2048 (directory-files org-babel-temporary-directory 'full
2049 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2050 (delete-directory org-babel-temporary-directory))
2051 (error
2052 (message "Failed to remove temporary Org-babel directory %s"
2053 (if (boundp 'org-babel-temporary-directory)
2054 org-babel-temporary-directory
2055 "[directory not defined]"))))))
2057 (add-hook 'kill-emacs-hook 'org-babel-remove-temporary-directory)
2059 (provide 'ob)
2061 ;; arch-tag: 01a7ebee-06c5-4ee4-a709-e660d28c0af1
2063 ;;; ob.el ends here