1 ;;; ob.el --- working with code blocks in org-mode
3 ;; Copyright (C) 2009-2011 Free Software Foundation, Inc.
5 ;; Author: Eric Schulte
7 ;; Keywords: literate programming, reproducible research
8 ;; Homepage: http://orgmode.org
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
31 (defvar org-babel-call-process-region-original
)
32 (defvar org-src-lang-modes
)
33 (defvar org-babel-library-of-babel
)
34 (declare-function show-all
"outline" ())
35 (declare-function tramp-compat-make-temp-file
"tramp-compat"
36 (filename &optional dir-flag
))
37 (declare-function tramp-dissect-file-name
"tramp" (name &optional nodefault
))
38 (declare-function tramp-file-name-user
"tramp" (vec))
39 (declare-function tramp-file-name-host
"tramp" (vec))
40 (declare-function with-parsed-tramp-file-name
"tramp" (filename var
&rest body
))
41 (declare-function org-icompleting-read
"org" (&rest args
))
42 (declare-function org-edit-src-code
"org-src"
43 (&optional context code edit-buffer-name quietp
))
44 (declare-function org-edit-src-exit
"org-src" (&optional context
))
45 (declare-function org-open-at-point
"org" (&optional in-emacs reference-buffer
))
46 (declare-function org-save-outline-visibility
"org" (use-markers &rest body
))
47 (declare-function org-outline-overlay-data
"org" (&optional use-markers
))
48 (declare-function org-set-outline-overlay-data
"org" (data))
49 (declare-function org-narrow-to-subtree
"org" ())
50 (declare-function org-entry-get
"org"
51 (pom property
&optional inherit literal-nil
))
52 (declare-function org-make-options-regexp
"org" (kwds &optional extra
))
53 (declare-function org-do-remove-indentation
"org" (&optional n
))
54 (declare-function org-show-context
"org" (&optional key
))
55 (declare-function org-at-table-p
"org" (&optional table-type
))
56 (declare-function org-cycle
"org" (&optional arg
))
57 (declare-function org-uniquify
"org" (list))
58 (declare-function org-current-level
"org" ())
59 (declare-function org-table-import
"org-table" (file arg
))
60 (declare-function org-add-hook
"org-compat"
61 (hook function
&optional append local
))
62 (declare-function org-table-align
"org-table" ())
63 (declare-function org-table-end
"org-table" (&optional table-type
))
64 (declare-function orgtbl-to-generic
"org-table" (table params
))
65 (declare-function orgtbl-to-orgtbl
"org-table" (table params
))
66 (declare-function org-babel-tangle-comment-links
"ob-tangle" (&optional info
))
67 (declare-function org-babel-lob-get-info
"ob-lob" nil
)
68 (declare-function org-babel-ref-split-args
"ob-ref" (arg-string))
69 (declare-function org-babel-ref-parse
"ob-ref" (assignment))
70 (declare-function org-babel-ref-resolve
"ob-ref" (ref))
71 (declare-function org-babel-ref-goto-headline-id
"ob-ref" (id))
72 (declare-function org-babel-ref-headline-body
"ob-ref" ())
73 (declare-function org-babel-lob-execute-maybe
"ob-lob" ())
74 (declare-function org-number-sequence
"org-compat" (from &optional to inc
))
75 (declare-function org-at-item-p
"org-list" ())
76 (declare-function org-list-parse-list
"org-list" (&optional delete
))
77 (declare-function org-list-to-generic
"org-list" (LIST PARAMS
))
78 (declare-function org-list-struct
"org-list" ())
79 (declare-function org-list-prevs-alist
"org-list" (struct))
80 (declare-function org-list-get-list-end
"org-list" (item struct prevs
))
82 (defgroup org-babel nil
83 "Code block evaluation and management in `org-mode' documents."
87 (defcustom org-confirm-babel-evaluate t
88 "Confirm before evaluation.
89 Require confirmation before interactively evaluating code
90 blocks in Org-mode buffers. The default value of this variable
91 is t, meaning confirmation is required for any code block
92 evaluation. This variable can be set to nil to inhibit any
93 future confirmation requests. This variable can also be set to a
94 function which takes two arguments the language of the code block
95 and the body of the code block. Such a function should then
96 return a non-nil value if the user should be prompted for
97 execution or nil if no prompt is required.
99 Warning: Disabling confirmation may result in accidental
100 evaluation of potentially harmful code. It may be advisable
101 remove code block execution from C-c C-c as further protection
102 against accidental code block evaluation. The
103 `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
104 remove code block execution from the C-c C-c keybinding."
106 :type
'(choice boolean function
))
107 ;; don't allow this variable to be changed through file settings
108 (put 'org-confirm-babel-evaluate
'safe-local-variable
(lambda (x) (eq x t
)))
110 (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
111 "Remove code block evaluation from the C-c C-c key binding."
115 (defvar org-babel-src-name-regexp
116 "^[ \t]*#\\+\\(srcname\\|source\\|function\\):[ \t]*"
117 "Regular expression used to match a source name line.")
119 (defvar org-babel-multi-line-header-regexp
120 "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
121 "Regular expression used to match multi-line header arguments.")
123 (defvar org-babel-src-name-w-name-regexp
124 (concat org-babel-src-name-regexp
126 org-babel-multi-line-header-regexp
128 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)")
129 "Regular expression matching source name lines with a name.")
131 (defvar org-babel-src-block-regexp
133 ;; (1) indentation (2) lang
134 "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
136 "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
137 ;; (4) header arguments
140 "\\([^\000]*?\n\\)?[ \t]*#\\+end_src")
141 "Regexp used to identify code blocks.")
143 (defvar org-babel-inline-src-block-regexp
145 ;; (1) replacement target (2) lang
146 "\\(?:^\\|[^-[:alnum:]]\\)\\(src_\\([^ \f\t\n\r\v]+\\)"
147 ;; (3,4) (unused, headers)
148 "\\(\\|\\[\\(.*?\\)\\]\\)"
150 "{\\([^\f\n\r\v]+?\\)}\\)")
151 "Regexp used to identify inline src-blocks.")
153 (defun org-babel-get-header (params key
&optional others
)
154 "Select only header argument of type KEY from a list.
155 Optional argument OTHERS indicates that only the header that do
156 not match KEY should be returned."
159 (lambda (p) (when (funcall (if others
#'not
#'identity
) (eq (car p
) key
)) p
))
162 (defun org-babel-get-inline-src-block-matches()
163 "Set match data if within body of an inline source block.
164 Returns non-nil if match-data set"
165 (let ((src-at-0-p (save-excursion
166 (beginning-of-line 1)
167 (string= "src" (thing-at-point 'word
))))
168 (first-line-p (= 1 (line-number-at-pos)))
170 (let ((search-for (cond ((and src-at-0-p first-line-p
"src_"))
171 (first-line-p "[ \t]src_")
172 (t "[ \f\t\n\r\v]src_")))
173 (lower-limit (if first-line-p
175 (- (point-at-bol) 1))))
177 (when (or (and src-at-0-p
(bobp))
178 (and (re-search-forward "}" (point-at-eol) t
)
179 (re-search-backward search-for lower-limit t
)
181 (when (looking-at org-babel-inline-src-block-regexp
)
184 (defun org-babel-get-lob-one-liner-matches()
185 "Set match data if on line of an lob one liner.
186 Returns non-nil if match-data set"
189 (unless (= (point) (point-at-bol)) ;; move before inline block
190 (re-search-backward "[ \f\t\n\r\v]" nil t
))
191 (if (looking-at org-babel-inline-lob-one-liner-regexp
)
195 (defun org-babel-get-src-block-info (&optional light
)
196 "Get information on the current source block.
198 Optional argument LIGHT does not resolve remote variable
199 references; a process which could likely result in the execution
200 of other code blocks.
203 (language body header-arguments-alist switches name indent)."
204 (let ((case-fold-search t
) head info name indent
)
206 (if (setq head
(org-babel-where-is-src-block-head))
209 (setq info
(org-babel-parse-src-block-match))
210 (setq indent
(car (last info
)))
211 (setq info
(butlast info
))
212 (while (and (forward-line -
1)
213 (looking-at org-babel-multi-line-header-regexp
))
215 (org-babel-merge-params
217 (org-babel-parse-header-arguments (match-string 1)))))
218 (when (looking-at org-babel-src-name-w-name-regexp
)
219 (setq name
(org-babel-clean-text-properties (match-string 4)))
220 (when (match-string 6)
221 (setf (nth 2 info
) ;; merge functional-syntax vars and header-args
222 (org-babel-merge-params
224 (lambda (ref) (cons :var ref
))
226 (lambda (var) ;; check that each variable is initialized
227 (if (string-match ".+=.+" var
)
230 "variable \"%s\"%s must be assigned a default value"
231 var
(if name
(format " in block \"%s\"" name
) ""))))
232 (org-babel-ref-split-args (match-string 6))))
234 ;; inline source block
235 (when (org-babel-get-inline-src-block-matches)
236 (setq info
(org-babel-parse-inline-src-block-match))))
237 ;; resolve variable references and add summary parameters
238 (when (and info
(not light
))
239 (setf (nth 2 info
) (org-babel-process-params (nth 2 info
))))
240 (when info
(append info
(list name indent
)))))
242 (defun org-babel-confirm-evaluate (info)
243 "Confirm evaluation of the code block INFO.
244 This behavior can be suppressed by setting the value of
245 `org-confirm-babel-evaluate' to nil, in which case all future
246 interactive code block evaluations will proceed without any
247 confirmation from the user.
249 Note disabling confirmation may result in accidental evaluation
250 of potentially harmful code."
251 (let* ((eval (or (cdr (assoc :eval
(nth 2 info
)))
252 (when (assoc :noeval
(nth 2 info
)) "no")))
253 (query (cond ((equal eval
"query") t
)
254 ((functionp org-confirm-babel-evaluate
)
255 (funcall org-confirm-babel-evaluate
256 (nth 0 info
) (nth 1 info
)))
257 (t org-confirm-babel-evaluate
))))
258 (if (or (equal eval
"never") (equal eval
"no")
261 (format "Evaluate this%scode block%son your system? "
262 (if info
(format " %s " (nth 0 info
)) " ")
264 (format " (%s) " (nth 4 info
)) " "))))))
265 (prog1 nil
(message "Evaluation %s"
266 (if (or (equal eval
"never") (equal eval
"no"))
267 "Disabled" "Aborted")))
271 (defun org-babel-execute-safely-maybe ()
272 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
273 (org-babel-execute-maybe)))
275 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-execute-safely-maybe
)
278 (defun org-babel-execute-maybe ()
280 (or (org-babel-execute-src-block-maybe)
281 (org-babel-lob-execute-maybe)))
283 (defun org-babel-execute-src-block-maybe ()
284 "Conditionally execute a source block.
285 Detect if this is context for a Babel src-block and if so
286 then run `org-babel-execute-src-block'."
288 (let ((info (org-babel-get-src-block-info)))
290 (progn (org-babel-eval-wipe-error-buffer)
291 (org-babel-execute-src-block current-prefix-arg info
) t
) nil
)))
294 (defun org-babel-view-src-block-info ()
295 "Display information on the current source block.
296 This includes header arguments, language and name, and is largely
297 a window into the `org-babel-get-src-block-info' function."
299 (let ((info (org-babel-get-src-block-info 'light
)))
300 (flet ((full (it) (> (length it
) 0))
301 (printf (fmt &rest args
) (princ (apply #'format fmt args
))))
303 (with-help-window (help-buffer)
304 (let ((name (nth 4 info
))
306 (switches (nth 3 info
))
307 (header-args (nth 2 info
)))
308 (when name
(printf "Name: %s\n" name
))
309 (when lang
(printf "Lang: %s\n" lang
))
310 (when (full switches
) (printf "Switches: %s\n" switches
))
311 (printf "Header Arguments:\n")
312 (dolist (pair (sort header-args
313 (lambda (a b
) (string< (symbol-name (car a
))
314 (symbol-name (car b
))))))
315 (when (full (cdr pair
))
316 (printf "\t%S%s\t%s\n"
318 (if (> (length (format "%S" (car pair
))) 7) "" "\t")
322 (defun org-babel-expand-src-block-maybe ()
323 "Conditionally expand a source block.
324 Detect if this is context for a org-babel src-block and if so
325 then run `org-babel-expand-src-block'."
327 (let ((info (org-babel-get-src-block-info)))
329 (progn (org-babel-expand-src-block current-prefix-arg info
) t
)
333 (defun org-babel-load-in-session-maybe ()
334 "Conditionally load a source block in a session.
335 Detect if this is context for a org-babel src-block and if so
336 then run `org-babel-load-in-session'."
338 (let ((info (org-babel-get-src-block-info)))
340 (progn (org-babel-load-in-session current-prefix-arg info
) t
)
343 (add-hook 'org-metaup-hook
'org-babel-load-in-session-maybe
)
346 (defun org-babel-pop-to-session-maybe ()
347 "Conditionally pop to a session.
348 Detect if this is context for a org-babel src-block and if so
349 then run `org-babel-pop-to-session'."
351 (let ((info (org-babel-get-src-block-info)))
352 (if info
(progn (org-babel-pop-to-session current-prefix-arg info
) t
) nil
)))
354 (add-hook 'org-metadown-hook
'org-babel-pop-to-session-maybe
)
356 (defconst org-babel-header-arg-names
357 '(cache cmdline colnames dir exports file noweb results
358 session tangle var eval noeval comments no-expand shebang
360 "Common header arguments used by org-babel.
361 Note that individual languages may define their own language
362 specific header arguments as well.")
364 (defvar org-babel-default-header-args
365 '((:session .
"none") (:results .
"replace") (:exports .
"code")
366 (:cache .
"no") (:noweb .
"no") (:hlines .
"no") (:tangle .
"no")
367 (:padnewline .
"yes"))
368 "Default arguments to use when evaluating a source block.")
370 (defvar org-babel-default-inline-header-args
371 '((:session .
"none") (:results .
"replace") (:exports .
"results"))
372 "Default arguments to use when evaluating an inline source block.")
374 (defvar org-babel-data-names
'("TBLNAME" "RESNAME" "RESULTS" "DATA"))
376 (defvar org-babel-result-regexp
377 (concat "^[ \t]*#\\+"
378 (regexp-opt org-babel-data-names t
)
379 "\\(\\[\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*")
380 "Regular expression used to match result lines.
381 If the results are associated with a hash key then the hash will
382 be saved in the second match data.")
384 (defvar org-babel-result-w-name-regexp
385 (concat org-babel-result-regexp
386 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
388 (defvar org-babel-min-lines-for-block-output
10
389 "The minimum number of lines for block output.
390 If number of lines of output is equal to or exceeds this
391 value, the output is placed in a #+begin_example...#+end_example
392 block. Otherwise the output is marked as literal by inserting
393 colons at the starts of the lines. This variable only takes
394 effect if the :results output option is in effect.")
396 (defvar org-babel-noweb-error-langs nil
397 "Languages for which Babel will raise literate programming errors.
398 List of languages for which errors should be raised when the
399 source code block satisfying a noweb reference in this language
400 can not be resolved.")
402 (defvar org-babel-hash-show
4
403 "Number of initial characters to show of a hidden results hash.")
405 (defvar org-babel-after-execute-hook nil
406 "Hook for functions to be called after `org-babel-execute-src-block'")
407 (defun org-babel-named-src-block-regexp-for-name (name)
408 "This generates a regexp used to match a src block named NAME."
409 (concat org-babel-src-name-regexp
(regexp-quote name
) "[ \t\n]*"
410 (substring org-babel-src-block-regexp
1)))
413 (defvar call-process-region
)
416 (defun org-babel-execute-src-block (&optional arg info params
)
417 "Execute the current source code block.
418 Insert the results of execution into the buffer. Source code
419 execution and the collection and formatting of results can be
420 controlled through a variety of header arguments.
422 With prefix argument ARG, force re-execution even if a an
423 existing result cached in the buffer would otherwise have been
426 Optionally supply a value for INFO in the form returned by
427 `org-babel-get-src-block-info'.
429 Optionally supply a value for PARAMS which will be merged with
430 the header arguments specified at the front of the source code
433 (let ((info (or info
(org-babel-get-src-block-info))))
434 (when (org-babel-confirm-evaluate info
)
435 (let* ((lang (nth 0 info
))
437 (org-babel-process-params
438 (org-babel-merge-params (nth 2 info
) params
))
440 (cache?
(and (not arg
) (cdr (assoc :cache params
))
441 (string= "yes" (cdr (assoc :cache params
)))))
442 (result-params (cdr (assoc :result-params params
)))
443 (new-hash (when cache?
(org-babel-sha1-hash info
)))
444 (old-hash (when cache?
(org-babel-current-result-hash)))
445 (body (setf (nth 1 info
)
446 (let ((noweb (cdr (assoc :noweb params
))))
448 (or (string= "yes" noweb
)
449 (string= "tangle" noweb
)))
450 (org-babel-expand-noweb-references info
)
452 (dir (cdr (assoc :dir params
)))
454 (or (and dir
(file-name-as-directory dir
)) default-directory
))
455 (org-babel-call-process-region-original
456 (if (boundp 'org-babel-call-process-region-original
)
457 org-babel-call-process-region-original
458 (symbol-function 'call-process-region
)))
459 (indent (car (last info
)))
462 (flet ((call-process-region (&rest args
)
463 (apply 'org-babel-tramp-handle-call-process-region args
)))
464 (flet ((lang-check (f)
465 (let ((f (intern (concat "org-babel-execute:" f
))))
466 (when (fboundp f
) f
))))
468 (or (lang-check lang
)
469 (lang-check (symbol-name
470 (cdr (assoc lang org-src-lang-modes
))))
471 (error "No org-babel-execute function for %s!" lang
))))
472 (if (and (not arg
) new-hash
(equal new-hash old-hash
))
473 (save-excursion ;; return cached result
474 (goto-char (org-babel-where-is-src-block-result nil info
))
475 (end-of-line 1) (forward-char 1)
476 (setq result
(org-babel-read-result))
477 (message (replace-regexp-in-string
478 "%" "%%" (format "%S" result
))) result
)
479 (message "executing %s code block%s..."
481 (if (nth 4 info
) (format " (%s)" (nth 4 info
)) ""))
484 (if (and (eq (cdr (assoc :result-type params
)) 'value
)
485 (or (member "vector" result-params
)
486 (member "table" result-params
))
487 (not (listp result
)))
488 (list (list result
)) result
))
489 (funcall cmd body params
)))
490 ;; if non-empty result and :file then write to :file
491 (when (cdr (assoc :file params
))
493 (with-temp-file (cdr (assoc :file params
))
495 (org-babel-format-result
496 result
(cdr (assoc :sep
(nth 2 info
)))))))
497 (setq result
(cdr (assoc :file params
))))
498 (org-babel-insert-result
499 result result-params info new-hash indent lang
)
500 (run-hooks 'org-babel-after-execute-hook
)
502 (setq call-process-region
'org-babel-call-process-region-original
))))))
504 (defun org-babel-expand-body:generic
(body params
&optional var-lines
)
505 "Expand BODY with PARAMS.
506 Expand a block of code with org-babel according to it's header
507 arguments. This generic implementation of body expansion is
508 called for languages which have not defined their own specific
509 org-babel-expand-body:lang function."
510 (mapconcat #'identity
(append var-lines
(list body
)) "\n"))
513 (defun org-babel-expand-src-block (&optional arg info params
)
514 "Expand the current source code block.
515 Expand according to the source code block's header
516 arguments and pop open the results in a preview buffer."
518 (let* ((info (or info
(org-babel-get-src-block-info)))
520 (params (setf (nth 2 info
)
521 (sort (org-babel-merge-params (nth 2 info
) params
)
522 (lambda (el1 el2
) (string< (symbol-name (car el1
))
523 (symbol-name (car el2
)))))))
524 (body (setf (nth 1 info
)
525 (if (and (cdr (assoc :noweb params
))
526 (string= "yes" (cdr (assoc :noweb params
))))
527 (org-babel-expand-noweb-references info
) (nth 1 info
))))
528 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
529 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
532 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
533 (org-babel-expand-body:generic
534 body params
(and (fboundp assignments-cmd
)
535 (funcall assignments-cmd params
))))))
537 nil expanded
(concat "*Org-Babel Preview " (buffer-name) "[ " lang
" ]*"))))
539 (defun org-babel-edit-distance (s1 s2
)
540 "Return the edit (levenshtein) distance between strings S1 S2."
541 (let* ((l1 (length s1
))
543 (dist (map 'vector
(lambda (_) (make-vector (1+ l2
) nil
))
544 (number-sequence 1 (1+ l1
)))))
545 (flet ((in (i j
) (aref (aref dist i
) j
))
546 (mmin (&rest lst
) (apply #'min
(remove nil lst
))))
547 (setf (aref (aref dist
0) 0) 0)
548 (dolist (i (number-sequence 1 l1
))
549 (dolist (j (number-sequence 1 l2
))
550 (setf (aref (aref dist i
) j
)
551 (+ (if (equal (aref s1
(1- i
)) (aref s2
(1- j
))) 0 1)
552 (mmin (in (1- i
) j
) (in i
(1- j
)) (in (1- i
) (1- j
)))))))
556 (defun org-babel-check-src-block ()
557 "Check for misspelled header arguments in the current code block."
559 ;; TODO: report malformed code block
560 ;; TODO: report incompatible combinations of header arguments
561 ;; TODO: report uninitialized variables
562 (let ((too-close 2)) ;; <- control closeness to report potential match
563 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg
)) 1))
564 (and (org-babel-where-is-src-block-head)
565 (org-babel-parse-header-arguments
566 (org-babel-clean-text-properties
567 (match-string 4))))))
568 (dolist (name (mapcar #'symbol-name org-babel-header-arg-names
))
569 (when (and (not (string= header name
))
570 (<= (org-babel-edit-distance header name
) too-close
))
571 (error "supplied header \"%S\" is suspiciously close to \"%S\""
573 (message "No suspicious header arguments found.")))
576 (defun org-babel-load-in-session (&optional arg info
)
577 "Load the body of the current source-code block.
578 Evaluate the header arguments for the source block before
579 entering the session. After loading the body this pops open the
582 (let* ((info (or info
(org-babel-get-src-block-info)))
584 (params (nth 2 info
))
585 (body (setf (nth 1 info
)
586 (if (and (cdr (assoc :noweb params
))
587 (string= "yes" (cdr (assoc :noweb params
))))
588 (org-babel-expand-noweb-references info
)
590 (session (cdr (assoc :session params
)))
591 (dir (cdr (assoc :dir params
)))
593 (or (and dir
(file-name-as-directory dir
)) default-directory
))
594 (cmd (intern (concat "org-babel-load-session:" lang
))))
595 (unless (fboundp cmd
)
596 (error "No org-babel-load-session function for %s!" lang
))
597 (pop-to-buffer (funcall cmd session body params
))
601 (defun org-babel-initiate-session (&optional arg info
)
602 "Initiate session for current code block.
603 If called with a prefix argument then resolve any variable
604 references in the header arguments and assign these variables in
605 the session. Copy the body of the code block to the kill ring."
607 (let* ((info (or info
(org-babel-get-src-block-info (not arg
))))
610 (params (nth 2 info
))
611 (session (cdr (assoc :session params
)))
612 (dir (cdr (assoc :dir params
)))
614 (or (and dir
(file-name-as-directory dir
)) default-directory
))
615 (init-cmd (intern (format "org-babel-%s-initiate-session" lang
)))
616 (prep-cmd (intern (concat "org-babel-prep-session:" lang
))))
617 (if (and (stringp session
) (string= session
"none"))
618 (error "This block is not using a session!"))
619 (unless (fboundp init-cmd
)
620 (error "No org-babel-initiate-session function for %s!" lang
))
621 (with-temp-buffer (insert (org-babel-trim body
))
622 (copy-region-as-kill (point-min) (point-max)))
624 (unless (fboundp prep-cmd
)
625 (error "No org-babel-prep-session function for %s!" lang
))
626 (funcall prep-cmd session params
))
627 (funcall init-cmd session params
)))
630 (defun org-babel-switch-to-session (&optional arg info
)
631 "Switch to the session of the current code block.
632 Uses `org-babel-initiate-session' to start the session. If called
633 with a prefix argument then this is passed on to
634 `org-babel-initiate-session'."
636 (pop-to-buffer (org-babel-initiate-session arg info
))
639 (defalias 'org-babel-pop-to-session
'org-babel-switch-to-session
)
642 (defun org-babel-switch-to-session-with-code (&optional arg info
)
643 "Switch to code buffer and display session."
647 (let ((other-window-buffer (window-buffer (next-window))))
648 (set-window-buffer (next-window) (current-buffer))
649 (set-window-buffer (selected-window) other-window-buffer
))
651 (let ((info (org-babel-get-src-block-info))
652 (org-src-window-setup 'reorganize-frame
))
654 (org-babel-switch-to-session arg info
))
658 (defmacro org-babel-do-in-edit-buffer
(&rest body
)
659 "Evaluate BODY in edit buffer if there is a code block at point.
660 Return t if a code block was found at point, nil otherwise."
661 `(let ((org-src-window-setup 'switch-invisibly
))
662 (when (and (org-babel-where-is-src-block-head)
663 (org-edit-src-code nil nil nil
))
664 (unwind-protect (progn ,@body
)
665 (if (org-bound-and-true-p org-edit-src-from-org-mode
)
666 (org-edit-src-exit)))
668 (def-edebug-spec org-babel-do-in-edit-buffer
(body))
670 (defun org-babel-do-key-sequence-in-edit-buffer (key)
671 "Read key sequence and execute the command in edit buffer.
672 Enter a key sequence to be executed in the language major-mode
673 edit buffer. For example, TAB will alter the contents of the
674 Org-mode code block according to the effect of TAB in the
675 language major-mode buffer. For languages that support
676 interactive sessions, this can be used to send code from the Org
677 buffer to the session for evaluation using the native major-mode
678 evaluation mechanisms."
679 (interactive "kEnter key-sequence to execute in edit buffer: ")
680 (org-babel-do-in-edit-buffer
682 (key-binding (or key
(read-key-sequence nil
))))))
684 (defvar org-bracket-link-regexp
)
686 (defun org-babel-open-src-block-result (&optional re-run
)
687 "If `point' is on a src block then open the results of the
688 source code block, otherwise return nil. With optional prefix
689 argument RE-RUN the source-code block is evaluated even if
690 results already exist."
692 (let ((info (org-babel-get-src-block-info)))
695 ;; go to the results, if there aren't any then run the block
696 (goto-char (or (and (not re-run
) (org-babel-where-is-src-block-result))
697 (progn (org-babel-execute-src-block)
698 (org-babel-where-is-src-block-result))))
700 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
702 (if (looking-at org-bracket-link-regexp
)
705 (let ((r (org-babel-format-result
706 (org-babel-read-result) (cdr (assoc :sep
(nth 2 info
))))))
707 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
708 (delete-region (point-min) (point-max))
713 (defmacro org-babel-map-src-blocks
(file &rest body
)
714 "Evaluate BODY forms on each source-block in FILE.
715 If FILE is nil evaluate BODY forms on source blocks in current
716 buffer. During evaluation of BODY the following local variables
717 are set relative to the currently matched code block.
719 full-block ------- string holding the entirety of the code block
720 beg-block -------- point at the beginning of the code block
721 end-block -------- point at the end of the matched code block
722 lang ------------- string holding the language of the code block
723 beg-lang --------- point at the beginning of the lang
724 end-lang --------- point at the end of the lang
725 switches --------- string holding the switches
726 beg-switches ----- point at the beginning of the switches
727 end-switches ----- point at the end of the switches
728 header-args ------ string holding the header-args
729 beg-header-args -- point at the beginning of the header-args
730 end-header-args -- point at the end of the header-args
731 body ------------- string holding the body of the code block
732 beg-body --------- point at the beginning of the body
733 end-body --------- point at the end of the body"
735 (let ((tempvar (make-symbol "file")))
736 `(let* ((,tempvar
,file
)
737 (visited-p (or (null ,tempvar
)
738 (get-file-buffer (expand-file-name ,tempvar
))))
739 (point (point)) to-be-removed
)
740 (save-window-excursion
741 (when ,tempvar
(find-file ,tempvar
))
742 (setq to-be-removed
(current-buffer))
743 (goto-char (point-min))
744 (while (re-search-forward org-babel-src-block-regexp nil t
)
745 (goto-char (match-beginning 0))
746 (let ((full-block (match-string 0))
747 (beg-block (match-beginning 0))
748 (end-block (match-end 0))
749 (lang (match-string 2))
750 (beg-lang (match-beginning 2))
751 (end-lang (match-end 2))
752 (switches (match-string 3))
753 (beg-switches (match-beginning 3))
754 (end-switches (match-end 3))
755 (header-args (match-string 4))
756 (beg-header-args (match-beginning 4))
757 (end-header-args (match-end 4))
758 (body (match-string 5))
759 (beg-body (match-beginning 5))
760 (end-body (match-end 5)))
762 (goto-char end-block
))))
763 (unless visited-p
(kill-buffer to-be-removed
))
765 (def-edebug-spec org-babel-map-src-blocks
(form body
))
768 (defmacro org-babel-map-inline-src-blocks
(file &rest body
)
769 "Evaluate BODY forms on each inline source-block in FILE.
770 If FILE is nil evaluate BODY forms on source blocks in current
773 (let ((tempvar (make-symbol "file")))
774 `(let* ((,tempvar
,file
)
775 (visited-p (or (null ,tempvar
)
776 (get-file-buffer (expand-file-name ,tempvar
))))
777 (point (point)) to-be-removed
)
778 (save-window-excursion
779 (when ,tempvar
(find-file ,tempvar
))
780 (setq to-be-removed
(current-buffer))
781 (goto-char (point-min))
782 (while (re-search-forward org-babel-inline-src-block-regexp nil t
)
783 (goto-char (match-beginning 1))
784 (save-match-data ,@body
)
785 (goto-char (match-end 0))))
786 (unless visited-p
(kill-buffer to-be-removed
))
788 (def-edebug-spec org-babel-map-inline-src-blocks
(form body
))
791 (defun org-babel-execute-buffer (&optional arg
)
792 "Execute source code blocks in a buffer.
793 Call `org-babel-execute-src-block' on every source block in
796 (org-babel-eval-wipe-error-buffer)
797 (org-save-outline-visibility t
798 (org-babel-map-src-blocks nil
799 (org-babel-execute-src-block arg
))
800 (org-babel-map-inline-src-blocks nil
801 (org-babel-execute-src-block arg
))))
804 (defun org-babel-execute-subtree (&optional arg
)
805 "Execute source code blocks in a subtree.
806 Call `org-babel-execute-src-block' on every source block in
807 the current subtree."
811 (org-narrow-to-subtree)
812 (org-babel-execute-buffer arg
)
816 (defun org-babel-sha1-hash (&optional info
)
817 "Generate an sha1 hash based on the value of info."
819 (let ((print-level nil
)
820 (info (or info
(org-babel-get-src-block-info))))
822 (sort (copy-sequence (nth 2 info
))
823 (lambda (a b
) (string< (car a
) (car b
)))))
825 (dolist (p '("replace" "silent" "append" "prepend"))
826 (setq lst
(remove p lst
)))
829 (let ((v (if (and (listp (cdr arg
)) (null (cddr arg
)))
830 (copy-sequence (cdr arg
))
832 (when (and v
(not (and (sequencep v
)
836 ((and (listp v
) ; lists are sorted
837 (member (car arg
) '(:result-params
)))
838 (sort (rm v
) #'string
<))
839 ((and (stringp v
) ; strings are sorted
840 (member (car arg
) '(:results
:exports
)))
841 (mapconcat #'identity
(sort (rm (split-string v
))
845 (when (org-called-interactively-p 'interactive
) (message hash
)) hash
)
846 (let ((it (format "%s-%s"
849 (delq nil
(mapcar (lambda (arg)
850 (let ((normalized (norm arg
)))
852 (format "%S" normalized
))))
857 (defun org-babel-current-result-hash ()
858 "Return the in-buffer hash associated with INFO."
859 (org-babel-where-is-src-block-result)
860 (org-babel-clean-text-properties (match-string 3)))
862 (defun org-babel-hide-hash ()
863 "Hide the hash in the current results line.
864 Only the initial `org-babel-hash-show' characters of the hash
865 will remain visible."
866 (add-to-invisibility-spec '(org-babel-hide-hash . t
))
868 (when (and (re-search-forward org-babel-result-regexp nil t
)
870 (let* ((start (match-beginning 3))
871 (hide-start (+ org-babel-hash-show start
))
873 (hash (match-string 3))
875 (setq ov1
(make-overlay start hide-start
))
876 (setq ov2
(make-overlay hide-start end
))
877 (overlay-put ov2
'invisible
'org-babel-hide-hash
)
878 (overlay-put ov1
'babel-hash hash
)))))
880 (defun org-babel-hide-all-hashes ()
881 "Hide the hash in the current buffer.
882 Only the initial `org-babel-hash-show' characters of each hash
883 will remain visible. This function should be called as part of
884 the `org-mode-hook'."
886 (while (re-search-forward org-babel-result-regexp nil t
)
887 (goto-char (match-beginning 0))
888 (org-babel-hide-hash)
889 (goto-char (match-end 0)))))
890 (add-hook 'org-mode-hook
'org-babel-hide-all-hashes
)
892 (defun org-babel-hash-at-point (&optional point
)
893 "Return the value of the hash at POINT.
894 The hash is also added as the last element of the kill ring.
895 This can be called with C-c C-c."
897 (let ((hash (car (delq nil
(mapcar
898 (lambda (ol) (overlay-get ol
'babel-hash
))
899 (overlays-at (or point
(point))))))))
900 (when hash
(kill-new hash
) (message hash
))))
901 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-hash-at-point
)
903 (defun org-babel-result-hide-spec ()
904 "Hide portions of results lines.
905 Add `org-babel-hide-result' as an invisibility spec for hiding
906 portions of results lines."
907 (add-to-invisibility-spec '(org-babel-hide-result . t
)))
908 (add-hook 'org-mode-hook
'org-babel-result-hide-spec
)
910 (defvar org-babel-hide-result-overlays nil
911 "Overlays hiding results.")
913 (defun org-babel-result-hide-all ()
914 "Fold all results in the current buffer."
916 (org-babel-show-result-all)
918 (while (re-search-forward org-babel-result-regexp nil t
)
919 (save-excursion (goto-char (match-beginning 0))
920 (org-babel-hide-result-toggle-maybe)))))
922 (defun org-babel-show-result-all ()
923 "Unfold all results in the current buffer."
924 (mapc 'delete-overlay org-babel-hide-result-overlays
)
925 (setq org-babel-hide-result-overlays nil
))
928 (defun org-babel-hide-result-toggle-maybe ()
929 "Toggle visibility of result at point."
931 (let ((case-fold-search t
))
933 (beginning-of-line 1)
934 (looking-at org-babel-result-regexp
))
935 (progn (org-babel-hide-result-toggle)
936 t
) ;; to signal that we took action
937 nil
))) ;; to signal that we did not
939 (defun org-babel-hide-result-toggle (&optional force
)
940 "Toggle the visibility of the current result."
944 (if (re-search-forward org-babel-result-regexp nil t
)
945 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
946 (end (progn (goto-char (- (org-babel-result-end) 1)) (point)))
948 (if (memq t
(mapcar (lambda (overlay)
949 (eq (overlay-get overlay
'invisible
)
950 'org-babel-hide-result
))
951 (overlays-at start
)))
952 (if (or (not force
) (eq force
'off
))
954 (when (member ov org-babel-hide-result-overlays
)
955 (setq org-babel-hide-result-overlays
956 (delq ov org-babel-hide-result-overlays
)))
957 (when (eq (overlay-get ov
'invisible
)
958 'org-babel-hide-result
)
959 (delete-overlay ov
)))
960 (overlays-at start
)))
961 (setq ov
(make-overlay start end
))
962 (overlay-put ov
'invisible
'org-babel-hide-result
)
963 ;; make the block accessible to isearch
965 ov
'isearch-open-invisible
967 (when (member ov org-babel-hide-result-overlays
)
968 (setq org-babel-hide-result-overlays
969 (delq ov org-babel-hide-result-overlays
)))
970 (when (eq (overlay-get ov
'invisible
)
971 'org-babel-hide-result
)
972 (delete-overlay ov
))))
973 (push ov org-babel-hide-result-overlays
)))
974 (error "Not looking at a result line"))))
976 ;; org-tab-after-check-for-cycling-hook
977 (add-hook 'org-tab-first-hook
'org-babel-hide-result-toggle-maybe
)
978 ;; Remove overlays when changing major mode
979 (add-hook 'org-mode-hook
980 (lambda () (org-add-hook 'change-major-mode-hook
981 'org-babel-show-result-all
'append
'local
)))
983 (defvar org-file-properties
)
984 (defun org-babel-params-from-properties (&optional lang
)
985 "Retrieve parameters specified as properties.
986 Return an association list of any source block params which
987 may be specified in the properties of the current outline entry."
993 (and (setq val
(org-entry-get (point) header-arg t
))
994 (cons (intern (concat ":" header-arg
))
995 (org-babel-read val
))))
999 org-babel-header-arg-names
1001 (setq sym
(intern (concat "org-babel-header-arg-names:" lang
)))
1002 (and (boundp sym
) (eval sym
))))))))))
1004 (defun org-babel-params-from-buffer ()
1005 "Retrieve per-buffer parameters.
1006 Return an association list of any source block params which
1007 may be specified in the current buffer."
1008 (let (local-properties)
1013 (goto-char (point-min))
1014 (while (re-search-forward
1015 (org-make-options-regexp (list "BABEL" "PROPERTIES")) nil t
)
1016 (setq local-properties
1017 (org-babel-merge-params
1019 (org-babel-parse-header-arguments
1020 (org-match-string-no-properties 2)))))
1021 local-properties
)))))
1023 (defvar org-src-preserve-indentation
)
1024 (defun org-babel-parse-src-block-match ()
1025 "Parse the results from a match of the `org-babel-src-block-regexp'."
1026 (let* ((block-indentation (length (match-string 1)))
1027 (lang (org-babel-clean-text-properties (match-string 2)))
1028 (lang-headers (intern (concat "org-babel-default-header-args:" lang
)))
1029 (switches (match-string 3))
1030 (body (org-babel-clean-text-properties
1031 (let* ((body (match-string 5))
1032 (sub-length (- (length body
) 1)))
1033 (if (and (> sub-length
0)
1034 (string= "\n" (substring body sub-length
)))
1035 (substring body
0 sub-length
)
1037 (preserve-indentation (or org-src-preserve-indentation
1038 (string-match "-i\\>" switches
))))
1040 ;; get block body less properties, protective commas, and indentation
1043 (insert (org-babel-strip-protective-commas body
))
1044 (unless preserve-indentation
(org-do-remove-indentation))
1046 (org-babel-merge-params
1047 org-babel-default-header-args
1048 (org-babel-params-from-buffer)
1049 (org-babel-params-from-properties lang
)
1050 (if (boundp lang-headers
) (eval lang-headers
) nil
)
1051 (org-babel-parse-header-arguments
1052 (org-babel-clean-text-properties (or (match-string 4) ""))))
1054 block-indentation
)))
1056 (defun org-babel-parse-inline-src-block-match ()
1057 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
1058 (let* ((lang (org-babel-clean-text-properties (match-string 2)))
1059 (lang-headers (intern (concat "org-babel-default-header-args:" lang
))))
1061 (org-babel-strip-protective-commas
1062 (org-babel-clean-text-properties (match-string 5)))
1063 (org-babel-merge-params
1064 org-babel-default-inline-header-args
1065 (org-babel-params-from-buffer)
1066 (org-babel-params-from-properties lang
)
1067 (if (boundp lang-headers
) (eval lang-headers
) nil
)
1068 (org-babel-parse-header-arguments
1069 (org-babel-clean-text-properties (or (match-string 4) "")))))))
1071 (defun org-babel-parse-header-arguments (arg-string)
1072 "Parse a string of header arguments returning an alist."
1073 (when (> (length arg-string
) 0)
1078 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1080 (cons (intern (match-string 1 arg
))
1081 (org-babel-read (org-babel-chomp (match-string 2 arg
))))
1082 (cons (intern (org-babel-chomp arg
)) nil
)))
1083 (let ((balance 0) (partial nil
) (lst nil
) (last 0))
1084 (mapc (lambda (ch) ; split on [] balanced instances of [ \t]:
1085 (setq balance
(+ balance
1086 (cond ((equal 91 ch
) 1)
1089 (setq partial
(cons ch partial
))
1090 (when (and (= ch
58) (= balance
0)
1091 (or (= last
32) (= last
9)))
1092 (setq lst
(cons (apply #'string
(nreverse (cddr partial
)))
1094 (setq partial
(list ch
)))
1096 (string-to-list arg-string
))
1097 (nreverse (cons (apply #'string
(nreverse partial
)) lst
)))))))
1099 (defun org-babel-process-params (params)
1100 "Expand variables in PARAMS and add summary parameters."
1101 (let* ((vars-and-names (org-babel-disassemble-tables
1102 (mapcar (lambda (el)
1103 (if (consp (cdr el
))
1104 (cdr el
) (org-babel-ref-parse (cdr el
))))
1105 (org-babel-get-header params
:var
))
1106 (cdr (assoc :hlines params
))
1107 (cdr (assoc :colnames params
))
1108 (cdr (assoc :rownames params
))))
1109 (raw-result (or (cdr (assoc :results params
)) ""))
1110 (result-params (append
1111 (split-string (if (stringp raw-result
)
1114 (cdr (assoc :result-params params
)))))
1116 (mapcar (lambda (var) (cons :var var
)) (car vars-and-names
))
1118 (cons :colname-names
(or (cdr (assoc :colname-names params
))
1119 (cadr vars-and-names
)))
1120 (cons :rowname-names
(or (cdr (assoc :rowname-names params
))
1121 (caddr vars-and-names
)))
1122 (cons :result-params result-params
)
1123 (cons :result-type
(cond ((member "output" result-params
) 'output
)
1124 ((member "value" result-params
) 'value
)
1126 (org-babel-get-header params
:var
'other
))))
1128 ;; row and column names
1129 (defun org-babel-del-hlines (table)
1130 "Remove all 'hlines from TABLE."
1131 (remove 'hline table
))
1133 (defun org-babel-get-colnames (table)
1134 "Return the column names of TABLE.
1135 Return a cons cell, the `car' of which contains the TABLE less
1136 colnames, and the `cdr' of which contains a list of the column
1138 (if (equal 'hline
(nth 1 table
))
1139 (cons (cddr table
) (car table
))
1140 (cons (cdr table
) (car table
))))
1142 (defun org-babel-get-rownames (table)
1143 "Return the row names of TABLE.
1144 Return a cons cell, the `car' of which contains the TABLE less
1145 colnames, and the `cdr' of which contains a list of the column
1146 names. Note: this function removes any hlines in TABLE."
1147 (flet ((trans (table) (apply #'mapcar
* #'list table
)))
1148 (let* ((width (apply 'max
1149 (mapcar (lambda (el) (if (listp el
) (length el
) 0)) table
)))
1150 (table (trans (mapcar (lambda (row)
1151 (if (not (equal row
'hline
))
1155 (setq row
(cons 'hline row
)))
1158 (cons (mapcar (lambda (row) (if (equal (car row
) 'hline
) 'hline row
))
1159 (trans (cdr table
)))
1160 (remove 'hline
(car table
))))))
1162 (defun org-babel-put-colnames (table colnames
)
1163 "Add COLNAMES to TABLE if they exist."
1164 (if colnames
(apply 'list colnames
'hline table
) table
))
1166 (defun org-babel-put-rownames (table rownames
)
1167 "Add ROWNAMES to TABLE if they exist."
1169 (mapcar (lambda (row)
1171 (cons (or (pop rownames
) "") row
)
1175 (defun org-babel-pick-name (names selector
)
1176 "Select one out of an alist of row or column names.
1177 SELECTOR can be either a list of names in which case those names
1178 will be returned directly, or an index into the list NAMES in
1179 which case the indexed names will be return."
1180 (if (listp selector
)
1183 (if (and selector
(symbolp selector
) (not (equal t selector
)))
1184 (cdr (assoc selector names
))
1185 (if (integerp selector
)
1186 (nth (- selector
1) names
)
1187 (cdr (car (last names
))))))))
1189 (defun org-babel-disassemble-tables (vars hlines colnames rownames
)
1190 "Parse tables for further processing.
1191 Process the variables in VARS according to the HLINES,
1192 ROWNAMES and COLNAMES header arguments. Return a list consisting
1193 of the vars, cnames and rnames."
1194 (let (cnames rnames
)
1198 (when (listp (cdr var
))
1199 (when (and (not (equal colnames
"no"))
1200 (or colnames
(and (equal (nth 1 (cdr var
)) 'hline
)
1201 (not (member 'hline
(cddr (cdr var
)))))))
1202 (let ((both (org-babel-get-colnames (cdr var
))))
1203 (setq cnames
(cons (cons (car var
) (cdr both
))
1205 (setq var
(cons (car var
) (car both
)))))
1206 (when (and rownames
(not (equal rownames
"no")))
1207 (let ((both (org-babel-get-rownames (cdr var
))))
1208 (setq rnames
(cons (cons (car var
) (cdr both
))
1210 (setq var
(cons (car var
) (car both
)))))
1211 (when (and hlines
(not (equal hlines
"yes")))
1212 (setq var
(cons (car var
) (org-babel-del-hlines (cdr var
))))))
1217 (defun org-babel-reassemble-table (table colnames rownames
)
1218 "Add column and row names to a table.
1219 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1220 to the table for reinsertion to org-mode."
1223 (if (and colnames
(listp (car table
)) (= (length (car table
))
1225 (org-babel-put-colnames table colnames
) table
))
1226 (if (and rownames
(= (length table
) (length rownames
)))
1227 (org-babel-put-rownames table rownames
) table
))
1230 (defun org-babel-where-is-src-block-head ()
1231 "Find where the current source block begins.
1232 Return the point at the beginning of the current source
1233 block. Specifically at the beginning of the #+BEGIN_SRC line.
1234 If the point is not on a source block then return nil."
1235 (let ((initial (point)) top bottom
)
1237 (save-excursion ;; on a source name line or a #+header line
1238 (beginning-of-line 1)
1239 (and (or (looking-at org-babel-src-name-regexp
)
1240 (looking-at org-babel-multi-line-header-regexp
))
1242 (while (and (forward-line 1)
1243 (looking-at org-babel-multi-line-header-regexp
)))
1244 (looking-at org-babel-src-block-regexp
))
1246 (save-excursion ;; on a #+begin_src line
1247 (beginning-of-line 1)
1248 (and (looking-at org-babel-src-block-regexp
)
1250 (save-excursion ;; inside a src block
1252 (re-search-backward "^[ \t]*#\\+begin_src" nil t
) (setq top
(point))
1253 (re-search-forward "^[ \t]*#\\+end_src" nil t
) (setq bottom
(point))
1254 (< top initial
) (< initial bottom
)
1255 (progn (goto-char top
) (beginning-of-line 1)
1256 (looking-at org-babel-src-block-regexp
))
1260 (defun org-babel-goto-src-block-head ()
1261 "Go to the beginning of the current code block."
1264 (if head
(goto-char head
) (error "not currently in a code block")))
1265 (org-babel-where-is-src-block-head)))
1268 (defun org-babel-goto-named-src-block (name)
1269 "Go to a named source-code block."
1271 (let ((completion-ignore-case t
))
1272 (list (org-icompleting-read "source-block name: "
1273 (org-babel-src-block-names) nil t
))))
1274 (let ((point (org-babel-find-named-block name
)))
1276 ;; taken from `org-open-at-point'
1277 (progn (goto-char point
) (org-show-context))
1278 (message "source-code block '%s' not found in this buffer" name
))))
1280 (defun org-babel-find-named-block (name)
1281 "Find a named source-code block.
1282 Return the location of the source block identified by source
1283 NAME, or nil if no such block exists. Set match data according to
1284 org-babel-named-src-block-regexp."
1286 (let ((case-fold-search t
)
1287 (regexp (org-babel-named-src-block-regexp-for-name name
)) msg
)
1288 (goto-char (point-min))
1289 (when (or (re-search-forward regexp nil t
)
1290 (re-search-backward regexp nil t
))
1291 (match-beginning 0)))))
1293 (defun org-babel-src-block-names (&optional file
)
1294 "Returns the names of source blocks in FILE or the current buffer."
1296 (when file
(find-file file
)) (goto-char (point-min))
1298 (while (re-search-forward org-babel-src-name-w-name-regexp nil t
)
1299 (setq names
(cons (match-string 4) names
)))
1303 (defun org-babel-goto-named-result (name)
1304 "Go to a named result."
1306 (let ((completion-ignore-case t
))
1307 (list (org-icompleting-read "source-block name: "
1308 (org-babel-result-names) nil t
))))
1309 (let ((point (org-babel-find-named-result name
)))
1311 ;; taken from `org-open-at-point'
1312 (progn (goto-char point
) (org-show-context))
1313 (message "result '%s' not found in this buffer" name
))))
1315 (defun org-babel-find-named-result (name)
1316 "Find a named result.
1317 Return the location of the result named NAME in the current
1318 buffer or nil if no such result exists."
1320 (goto-char (point-min))
1321 (when (re-search-forward
1322 (concat org-babel-result-regexp
1323 "[ \t]" (regexp-quote name
) "[ \t\n\f\v\r]") nil t
)
1324 (beginning-of-line 0) (point))))
1326 (defun org-babel-result-names (&optional file
)
1327 "Returns the names of results in FILE or the current buffer."
1329 (when file
(find-file file
)) (goto-char (point-min))
1331 (while (re-search-forward org-babel-result-w-name-regexp nil t
)
1332 (setq names
(cons (match-string 4) names
)))
1336 (defun org-babel-next-src-block (&optional arg
)
1337 "Jump to the next source block.
1338 With optional prefix argument ARG, jump forward ARG many source blocks."
1340 (when (looking-at org-babel-src-block-regexp
) (forward-char 1))
1342 (re-search-forward org-babel-src-block-regexp nil nil
(or arg
1))
1343 (error (error "No further code blocks")))
1344 (goto-char (match-beginning 0)) (org-show-context))
1347 (defun org-babel-previous-src-block (&optional arg
)
1348 "Jump to the previous source block.
1349 With optional prefix argument ARG, jump backward ARG many source blocks."
1352 (re-search-backward org-babel-src-block-regexp nil nil
(or arg
1))
1353 (error (error "No previous code blocks")))
1354 (goto-char (match-beginning 0)) (org-show-context))
1356 (defvar org-babel-load-languages
)
1359 (defun org-babel-mark-block ()
1360 "Mark current src block"
1366 (looking-at org-babel-src-block-regexp
))
1367 (push-mark (match-end 5) nil t
)
1368 (goto-char (match-beginning 5))))
1369 (org-babel-where-is-src-block-head)))
1371 (defun org-babel-demarcate-block (&optional arg
)
1372 "Wrap or split the code in the region or on the point.
1373 When called from inside of a code block the current block is
1374 split. When called from outside of a code block a new code block
1375 is created. In both cases if the region is demarcated and if the
1376 region is not active then the point is demarcated."
1378 (let ((info (org-babel-get-src-block-info 'light
))
1379 (headers (progn (org-babel-where-is-src-block-head)
1381 (stars (concat (make-string (or (org-current-level) 1) ?
*) " ")))
1387 (let ((lang (nth 0 info
))
1388 (indent (make-string (nth 5 info
) ?
)))
1389 (when (string-match "^[[:space:]]*$"
1390 (buffer-substring (point-at-bol)
1392 (delete-region (point-at-bol) (point-at-eol)))
1394 (if (looking-at "^") "" "\n")
1395 indent
"#+end_src\n"
1396 (if arg stars indent
) "\n"
1397 indent
"#+begin_src " lang
1398 (if (> (length headers
) 1)
1399 (concat " " headers
) headers
)
1400 (if (looking-at "[\n\r]")
1402 (concat "\n" (make-string (current-column) ?
)))))))
1403 (move-end-of-line 2))
1404 (sort (if (region-active-p) (list (mark) (point)) (list (point))) #'>))
1405 (let ((start (point))
1406 (lang (org-icompleting-read "Lang: "
1407 (mapcar (lambda (el) (symbol-name (car el
)))
1408 org-babel-load-languages
)))
1409 (body (delete-and-extract-region
1410 (if (region-active-p) (mark) (point)) (point))))
1411 (insert (concat (if (looking-at "^") "" "\n")
1412 (if arg
(concat stars
"\n") "")
1413 "#+begin_src " lang
"\n"
1415 (if (or (= (length body
) 0)
1416 (string-match "[\r\n]$" body
)) "" "\n")
1418 (goto-char start
) (move-end-of-line 1)))))
1420 (defvar org-babel-lob-one-liner-regexp
)
1421 (defvar org-babel-inline-lob-one-liner-regexp
)
1422 (defun org-babel-where-is-src-block-result (&optional insert info hash indent
)
1423 "Find where the current source block results begin.
1424 Return the point at the beginning of the result of the current
1425 source block. Specifically at the beginning of the results line.
1426 If no result exists for this block then create a results line
1427 following the source block."
1429 (let* ((on-lob-line (save-excursion
1430 (beginning-of-line 1)
1431 (looking-at org-babel-lob-one-liner-regexp
)))
1432 (inlinep (when (org-babel-get-inline-src-block-matches)
1434 (name (if on-lob-line
1435 (nth 0 (org-babel-lob-get-info))
1436 (nth 4 (or info
(org-babel-get-src-block-info 'light
)))))
1437 (head (unless on-lob-line
(org-babel-where-is-src-block-head)))
1439 (when head
(goto-char head
))
1441 found
;; was there a result (before we potentially insert one)
1446 ;; - return t if it is found, else return nil
1447 ;; - if it does not need to be rebuilt, then don't set end
1448 ;; - if it does need to be rebuilt then do set end
1449 name
(setq beg
(org-babel-find-named-result name
))
1451 (when (and hash
(not (string= hash
(match-string 3))))
1452 (goto-char beg
) (setq end beg
) ;; beginning of result
1454 (delete-region end
(org-babel-result-end)) nil
)))
1457 ;; - return t if it is found, else return nil
1458 ;; - if it is found, and the hash doesn't match, delete and set end
1459 (or on-lob-line
(re-search-forward "^[ \t]*#\\+end_src" nil t
))
1460 (progn (end-of-line 1)
1461 (if (eobp) (insert "\n") (forward-char 1))
1464 (progn ;; unnamed results line already exists
1465 (re-search-forward "[^ \f\t\n\r\v]" nil t
)
1466 (beginning-of-line 1)
1468 (concat org-babel-result-regexp
"\n")))
1470 ;; must remove and rebuild if hash!=old-hash
1471 (if (and hash
(not (string= hash
(match-string 3))))
1475 end
(org-babel-result-end)))
1476 (setq end nil
)))))))))
1477 (if (and insert end
)
1481 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1486 (org-number-sequence 1 indent
) "")
1489 (when hash
(concat "["hash
"]"))
1491 (when name
(concat " " name
)) "\n"))
1492 (unless beg
(insert "\n") (backward-char))
1493 (beginning-of-line 0)
1494 (if hash
(org-babel-hide-hash))
1498 (defvar org-block-regexp
)
1499 (defun org-babel-read-result ()
1500 "Read the result at `point' into emacs-lisp."
1501 (let ((case-fold-search t
) result-string
)
1503 ((org-at-table-p) (org-babel-read-table))
1504 ((org-at-item-p) (org-babel-read-list))
1505 ((looking-at org-bracket-link-regexp
) (org-babel-read-link))
1506 ((looking-at org-block-regexp
) (org-babel-trim (match-string 4)))
1507 ((looking-at "^[ \t]*: ")
1510 (mapconcat (lambda (line)
1511 (if (and (> (length line
) 1)
1512 (string-match "^[ \t]*: \\(.+\\)" line
))
1513 (match-string 1 line
)
1517 (point) (org-babel-result-end)) "[\r\n]+")
1519 (or (org-babel-number-p result-string
) result-string
))
1520 ((looking-at org-babel-result-regexp
)
1521 (save-excursion (forward-line 1) (org-babel-read-result))))))
1523 (defun org-babel-read-table ()
1524 "Read the table at `point' into emacs-lisp."
1525 (mapcar (lambda (row)
1526 (if (and (symbolp row
) (equal row
'hline
)) row
1527 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
)) row
)))
1528 (org-table-to-lisp)))
1530 (defun org-babel-read-list ()
1531 "Read the list at `point' into emacs-lisp."
1532 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
))
1533 (mapcar #'cadr
(cdr (org-list-parse-list)))))
1535 (defvar org-link-types-re
)
1536 (defun org-babel-read-link ()
1537 "Read the link at `point' into emacs-lisp.
1538 If the path of the link is a file path it is expanded using
1539 `expand-file-name'."
1540 (let* ((case-fold-search t
)
1541 (raw (and (looking-at org-bracket-link-regexp
)
1542 (org-babel-clean-text-properties (match-string 1))))
1543 (type (and (string-match org-link-types-re raw
)
1544 (match-string 1 raw
))))
1546 ((not type
) (expand-file-name raw
))
1547 ((string= type
"file")
1548 (and (string-match "file\\(.*\\):\\(.+\\)" raw
)
1549 (expand-file-name (match-string 2 raw
))))
1552 (defun org-babel-format-result (result &optional sep
)
1553 "Format RESULT for writing to file."
1554 (flet ((echo-res (result)
1555 (if (stringp result
) result
(format "%S" result
))))
1564 (echo-res result
))))
1566 (defun org-babel-insert-result
1567 (result &optional result-params info hash indent lang
)
1568 "Insert RESULT into the current buffer.
1569 By default RESULT is inserted after the end of the
1570 current source block. With optional argument RESULT-PARAMS
1571 controls insertion of results in the org-mode file.
1572 RESULT-PARAMS can take the following values...
1574 replace - (default option) insert results after the source block
1575 replacing any previously inserted results
1577 silent -- no results are inserted
1579 file ---- the results are interpreted as a file path, and are
1580 inserted into the buffer using the Org-mode file syntax
1582 list ---- the results are interpreted as an Org-mode list.
1584 raw ----- results are added directly to the Org-mode file. This
1585 is a good option if you code block will output org-mode
1588 org ----- similar in effect to raw, only the results are wrapped
1589 in an org code block. Similar to the raw option, on
1590 export the results will be interpreted as org-formatted
1591 text, however by wrapping the results in an org code
1592 block they can be replaced upon re-execution of the
1595 html ---- results are added inside of a #+BEGIN_HTML block. This
1596 is a good option if you code block will output html
1599 latex --- results are added inside of a #+BEGIN_LATEX block.
1600 This is a good option if you code block will output
1601 latex formatted text.
1603 code ---- the results are extracted in the syntax of the source
1604 code of the language being evaluated and are added
1605 inside of a #+BEGIN_SRC block with the source-code
1606 language set appropriately. Note this relies on the
1607 optional LANG argument."
1608 (if (stringp result
)
1610 (setq result
(org-babel-clean-text-properties result
))
1611 (when (member "file" result-params
)
1612 (setq result
(org-babel-result-to-file result
))))
1613 (unless (listp result
) (setq result
(format "%S" result
))))
1614 (if (and result-params
(member "silent" result-params
))
1616 (message (replace-regexp-in-string "%" "%%" (format "%S" result
)))
1621 (when (or (org-babel-get-inline-src-block-matches)
1622 (org-babel-get-lob-one-liner-matches))
1623 (goto-char (match-end 0))
1624 (insert (if (listp result
) "\n" " "))
1626 (existing-result (unless inlinep
1627 (org-babel-where-is-src-block-result
1628 t info hash indent
)))
1630 (cdr (assoc :results_switches
(nth 2 info
))))
1632 (when (and (stringp result
) ; ensure results end in a newline
1634 (> (length result
) 0)
1635 (not (or (string-equal (substring result -
1) "\n")
1636 (string-equal (substring result -
1) "\r"))))
1637 (setq result
(concat result
"\n")))
1638 (if (not existing-result
)
1639 (setq beg
(or inlinep
(point)))
1640 (goto-char existing-result
)
1642 (re-search-forward "#" nil t
)
1643 (setq indent
(- (current-column) 1)))
1647 ((member "replace" result-params
)
1648 (delete-region (point) (org-babel-result-end)))
1649 ((member "append" result-params
)
1650 (goto-char (org-babel-result-end)) (setq beg
(point-marker)))
1651 ((member "prepend" result-params
)))) ; already there
1652 (setq results-switches
1653 (if results-switches
(concat " " results-switches
) ""))
1654 ;; insert results based on type
1656 ;; do nothing for an empty result
1657 ((= (length result
) 0))
1658 ;; insert a list if preferred
1659 ((member "list" result-params
)
1662 (org-list-to-generic
1665 (lambda (el) (list nil
(if (stringp el
) el
(format "%S" el
))))
1666 (if (listp result
) result
(list result
))))
1667 '(:splicep nil
:istart
"- " :iend
"\n")))
1669 ;; assume the result is a table if it's not a string
1670 ((not (stringp result
))
1672 (insert (concat (orgtbl-to-orgtbl
1673 (if (or (eq 'hline
(car result
))
1674 (and (listp (car result
))
1675 (listp (cdr (car result
)))))
1676 result
(list result
))
1677 '(:fmt
(lambda (cell) (format "%s" cell
)))) "\n"))
1678 (goto-char beg
) (when (org-at-table-p) (org-table-align)))
1679 ((member "file" result-params
)
1680 (when inlinep
(goto-char inlinep
))
1682 (t (goto-char beg
) (insert result
)))
1683 (when (listp result
) (goto-char (org-table-end)))
1684 (setq end
(point-marker))
1685 ;; possibly wrap result
1686 (flet ((wrap (start finish
)
1687 (goto-char beg
) (insert (concat start
"\n"))
1688 (goto-char end
) (insert (concat finish
"\n"))
1689 (setq end
(point-marker))))
1691 ((member "html" result-params
)
1692 (wrap "#+BEGIN_HTML" "#+END_HTML"))
1693 ((member "latex" result-params
)
1694 (wrap "#+BEGIN_LaTeX" "#+END_LaTeX"))
1695 ((member "code" result-params
)
1696 (wrap (format "#+BEGIN_SRC %s%s" (or lang
"none") results-switches
)
1698 ((member "org" result-params
)
1699 (wrap "#+BEGIN_ORG" "#+END_ORG"))
1700 ((member "raw" result-params
)
1701 (goto-char beg
) (if (org-at-table-p) (org-cycle)))
1702 ((member "wrap" result-params
)
1703 (when (and (stringp result
) (not (member "file" result-params
)))
1704 (org-babel-examplize-region beg end results-switches
))
1705 (wrap "#+BEGIN_RESULT" "#+END_RESULT"))
1706 ((and (stringp result
) (not (member "file" result-params
)))
1707 (org-babel-examplize-region beg end results-switches
)
1708 (setq end
(point)))))
1709 ;; possibly indent the results to match the #+results line
1710 (when (and (not inlinep
) (numberp indent
) indent
(> indent
0)
1711 ;; in this case `table-align' does the work for us
1712 (not (and (listp result
)
1713 (member "append" result-params
))))
1714 (indent-rigidly beg end indent
))))
1715 (if (= (length result
) 0)
1716 (if (member "value" result-params
)
1717 (message "Code block returned no value.")
1718 (message "Code block produced no output."))
1719 (message "Code block evaluation complete."))))
1721 (defun org-babel-remove-result (&optional info
)
1722 "Remove the result of the current source block."
1724 (let ((location (org-babel-where-is-src-block-result nil info
)) start
)
1726 (setq start
(- location
1))
1728 (goto-char location
) (forward-line 1)
1729 (delete-region start
(org-babel-result-end))))))
1731 (defun org-babel-result-end ()
1732 "Return the point at the end of the current set of results"
1735 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
1736 ((org-at-item-p) (let* ((struct (org-list-struct))
1737 (prvs (org-list-prevs-alist struct
)))
1738 (org-list-get-list-end (point-at-bol) struct prvs
)))
1740 (let ((case-fold-search t
)
1741 (blocks-re (regexp-opt
1742 (list "latex" "html" "example" "src" "result" "org"))))
1743 (if (looking-at (concat "[ \t]*#\\+begin_" blocks-re
))
1744 (progn (re-search-forward (concat "[ \t]*#\\+end_" blocks-re
) nil t
)
1746 (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
1750 (defun org-babel-result-to-file (result)
1751 "Convert RESULT into an `org-mode' link.
1752 If the `default-directory' is different from the containing
1753 file's directory then expand relative links."
1754 (flet ((cond-exp (file)
1755 (if (and default-directory
1757 (not (string= (expand-file-name default-directory
)
1759 (file-name-directory buffer-file-name
)))))
1760 (expand-file-name file default-directory
)
1762 (if (stringp result
)
1763 (format "[[file:%s]]" (cond-exp result
))
1764 (when (and (listp result
) (= 2 (length result
))
1765 (stringp (car result
)) (stringp (cadr result
)))
1766 (format "[[file:%s][%s]]" (car result
) (cadr result
))))))
1768 (defun org-babel-examplize-region (beg end
&optional results-switches
)
1769 "Comment out region using the inline '==' or ': ' org example quote."
1771 (flet ((chars-between (b e
) (string-match "[\\S]" (buffer-substring b e
))))
1772 (if (or (chars-between (save-excursion (goto-char beg
) (point-at-bol)) beg
)
1773 (chars-between end
(save-excursion (goto-char end
) (point-at-eol))))
1776 (insert (format "=%s=" (prog1 (buffer-substring beg end
)
1777 (delete-region beg end
)))))
1778 (let ((size (count-lines beg end
)))
1780 (cond ((= size
0)) ; do nothing for an empty result
1781 ((< size org-babel-min-lines-for-block-output
)
1784 (beginning-of-line 1) (insert ": ") (forward-line 1)))
1787 (insert (if results-switches
1788 (format "#+begin_example%s\n" results-switches
)
1789 "#+begin_example\n"))
1790 (if (markerp end
) (goto-char end
) (forward-char (- end beg
)))
1791 (insert "#+end_example\n"))))))))
1793 (defun org-babel-update-block-body (new-body)
1794 "Update the body of the current code block to NEW-BODY."
1795 (if (not (org-babel-where-is-src-block-head))
1796 (error "not in source block")
1798 (replace-match (concat (org-babel-trim new-body
) "\n") nil t nil
5))
1799 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
1801 (defun org-babel-merge-params (&rest plists
)
1802 "Combine all parameter association lists in PLISTS.
1803 Later elements of PLISTS override the values of previous elements.
1804 This takes into account some special considerations for certain
1805 parameters when merging lists."
1806 (let ((results-exclusive-groups
1807 '(("file" "list" "vector" "table" "scalar" "verbatim")
1808 ("raw" "org" "html" "latex" "code" "pp" "wrap")
1809 ("replace" "silent" "append" "prepend")
1810 ("output" "value")))
1811 (exports-exclusive-groups
1812 '(("code" "results" "both" "none")))
1814 params results exports tangle noweb cache vars shebang comments padline
)
1815 (flet ((e-merge (exclusive-groups &rest result-params
)
1816 ;; maintain exclusivity of mutually exclusive parameters
1818 (mapc (lambda (new-params)
1819 (mapc (lambda (new-param)
1820 (mapc (lambda (exclusive-group)
1821 (when (member new-param exclusive-group
)
1822 (mapcar (lambda (excluded-param)
1829 (setq output
(org-uniquify
1830 (cons new-param output
))))
1840 (let ((name (if (listp (cdr pair
))
1842 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
1844 (intern (match-string 1 (cdr pair
)))))))
1848 (if (member name
(mapcar #'car vars
))
1852 (unless (equal (car p
) name
) p
))
1855 (list (cons name pair
))))
1856 ;; if no name is given and we already have named variables
1857 ;; then assign to named variables in order
1858 (if (and vars
(nth variable-index vars
))
1859 (prog1 (setf (cddr (nth variable-index vars
))
1860 (concat (symbol-name
1861 (car (nth variable-index vars
)))
1863 (incf variable-index
))
1864 (error "variable \"%s\" must be assigned a default value"
1867 (setq results
(e-merge results-exclusive-groups
1870 (let ((r (cdr pair
)))
1871 (if (stringp r
) r
(eval r
)))))))
1874 (setq results
(e-merge results-exclusive-groups
1876 (unless (or (member "both" exports
)
1877 (member "none" exports
)
1878 (member "code" exports
))
1879 (setq exports
(e-merge exports-exclusive-groups
1880 exports
'("results"))))
1881 (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))
1883 (setq exports
(e-merge exports-exclusive-groups
1884 exports
(split-string (cdr pair
)))))
1885 (:tangle
;; take the latest -- always overwrite
1886 (setq tangle
(or (list (cdr pair
)) tangle
)))
1888 (setq noweb
(e-merge '(("yes" "no" "tangle")) noweb
1889 (split-string (or (cdr pair
) "")))))
1891 (setq cache
(e-merge '(("yes" "no")) cache
1892 (split-string (or (cdr pair
) "")))))
1894 (setq padline
(e-merge '(("yes" "no")) padline
1895 (split-string (or (cdr pair
) "")))))
1896 (:shebang
;; take the latest -- always overwrite
1897 (setq shebang
(or (list (cdr pair
)) shebang
)))
1899 (setq comments
(e-merge '(("yes" "no")) comments
1900 (split-string (or (cdr pair
) "")))))
1901 (t ;; replace: this covers e.g. :session
1902 (setq params
(cons pair
(assq-delete-all (car pair
) params
))))))
1905 (setq vars
(reverse vars
))
1906 (while vars
(setq params
(cons (cons :var
(cddr (pop vars
))) params
)))
1909 (let ((key (intern (concat ":" (symbol-name hd
))))
1911 (setf params
(cons (cons key
(mapconcat 'identity val
" ")) params
))))
1912 '(results exports tangle noweb padline cache shebang comments
))
1915 (defun org-babel-expand-noweb-references (&optional info parent-buffer
)
1916 "Expand Noweb references in the body of the current source code block.
1918 For example the following reference would be replaced with the
1919 body of the source-code block named 'example-block'.
1923 Note that any text preceding the <<foo>> construct on a line will
1924 be interposed between the lines of the replacement text. So for
1925 example if <<foo>> is placed behind a comment, then the entire
1926 replacement text will also be commented.
1928 This function must be called from inside of the buffer containing
1929 the source-code block which holds BODY.
1931 In addition the following syntax can be used to insert the
1932 results of evaluating the source-code block named 'example-block'.
1936 Any optional arguments can be passed to example-block by placing
1937 the arguments inside the parenthesis following the convention
1938 defined by `org-babel-lob'. For example
1940 <<example-block(a=9)>>
1942 would set the value of argument \"a\" equal to \"9\". Note that
1943 these arguments are not evaluated in the current source-code
1944 block but are passed literally to the \"example-block\"."
1945 (let* ((parent-buffer (or parent-buffer
(current-buffer)))
1946 (info (or info
(org-babel-get-src-block-info)))
1949 (comment (string= "noweb" (cdr (assoc :comments
(nth 2 info
)))))
1950 (new-body "") index source-name evaluate prefix blocks-in-buffer
)
1951 (flet ((nb-add (text) (setq new-body
(concat new-body text
)))
1954 (funcall (intern (concat lang
"-mode")))
1955 (comment-region (point) (progn (insert text
) (point)))
1956 (org-babel-trim (buffer-string))))
1957 (blocks () ;; return the info lists of all blocks in this buffer
1961 (org-babel-map-src-blocks nil
1962 (setq infos
(cons (org-babel-get-src-block-info 'light
)
1966 (insert body
) (goto-char (point-min))
1967 (setq index
(point))
1968 (while (and (re-search-forward "<<\\(.+?\\)>>" nil t
))
1969 (save-match-data (setf source-name
(match-string 1)))
1970 (save-match-data (setq evaluate
(string-match "\(.*\)" source-name
)))
1973 (buffer-substring (match-beginning 0)
1975 (beginning-of-line 1) (point)))))
1976 ;; add interval to new-body (removing noweb reference)
1977 (goto-char (match-beginning 0))
1978 (nb-add (buffer-substring index
(point)))
1979 (goto-char (match-end 0))
1980 (setq index
(point))
1982 (with-current-buffer parent-buffer
1983 (mapconcat ;; interpose PREFIX between every line
1987 (let ((raw (org-babel-ref-resolve source-name
)))
1988 (if (stringp raw
) raw
(format "%S" raw
)))
1990 ;; retrieve from the library of babel
1991 (nth 2 (assoc (intern source-name
)
1992 org-babel-library-of-babel
))
1993 ;; return the contents of headlines literally
1995 (when (org-babel-ref-goto-headline-id source-name
)
1996 (org-babel-ref-headline-body)))
1997 ;; find the expansion of reference in this buffer
2000 (when (string= source-name
2001 (or (cdr (assoc :noweb-ref
(nth 2 i
)))
2003 (let ((body (org-babel-expand-noweb-references i
)))
2006 (concat (c-wrap (car cs
)) "\n"
2007 body
"\n" (c-wrap (cadr cs
))))
2008 (org-babel-tangle-comment-links i
))
2010 (or blocks-in-buffer
2011 (setq blocks-in-buffer
(blocks)))
2013 ;; possibly raise an error if named block doesn't exist
2014 (if (member lang org-babel-noweb-error-langs
)
2016 "<<" source-name
">> "
2017 "could not be resolved (see "
2018 "`org-babel-noweb-error-langs')"))
2020 "[\n\r]") (concat "\n" prefix
)))))
2021 (nb-add (buffer-substring index
(point-max)))))
2024 (defun org-babel-clean-text-properties (text)
2025 "Strip all properties from text return."
2027 (set-text-properties 0 (length text
) nil text
) text
))
2029 (defun org-babel-strip-protective-commas (body)
2030 "Strip protective commas from bodies of source blocks."
2032 (replace-regexp-in-string "^,#" "#" body
)))
2034 (defun org-babel-script-escape (str &optional force
)
2035 "Safely convert tables into elisp lists."
2036 (let (in-single in-double out
)
2037 ((lambda (escaped) (condition-case nil
(org-babel-read escaped
) (error escaped
)))
2041 (or (and (string-equal "[" (substring str
0 1))
2042 (string-equal "]" (substring str -
1)))
2043 (and (string-equal "{" (substring str
0 1))
2044 (string-equal "}" (substring str -
1)))
2045 (and (string-equal "(" (substring str
0 1))
2046 (string-equal ")" (substring str -
1))))))
2056 (91 (if (or in-double in-single
) ; [
2059 (93 (if (or in-double in-single
) ; ]
2062 (123 (if (or in-double in-single
) ; {
2065 (125 (if (or in-double in-single
) ; }
2068 (44 (if (or in-double in-single
) ; ,
2069 (cons 44 out
) (cons 32 out
)))
2070 (39 (if in-double
; '
2072 (setq in-single
(not in-single
)) (cons 34 out
)))
2073 (34 (if in-single
; "
2074 (append (list 34 32) out
)
2075 (setq in-double
(not in-double
)) (cons 34 out
)))
2076 (t (cons ch out
)))))
2077 (string-to-list str
))
2078 (apply #'string
(reverse out
)))))
2081 (defun org-babel-read (cell &optional inhibit-lisp-eval
)
2082 "Convert the string value of CELL to a number if appropriate.
2083 Otherwise if cell looks like lisp (meaning it starts with a
2084 \"(\", \"'\", \"`\" or a \"[\") then read it as lisp, otherwise
2085 return it unmodified as a string. Optional argument NO-LISP-EVAL
2086 inhibits lisp evaluation for situations in which is it not
2088 (if (and (stringp cell
) (not (equal cell
"")))
2089 (or (org-babel-number-p cell
)
2090 (if (and (not inhibit-lisp-eval
)
2091 (member (substring cell
0 1) '("(" "'" "`" "[")))
2093 (if (string= (substring cell
0 1) "\"")
2095 (progn (set-text-properties 0 (length cell
) nil cell
) cell
))))
2098 (defun org-babel-number-p (string)
2099 "If STRING represents a number return it's value."
2100 (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string
)
2101 (= (length (substring string
(match-beginning 0)
2104 (string-to-number string
)))
2106 (defun org-babel-import-elisp-from-file (file-name &optional separator
)
2107 "Read the results located at FILE-NAME into an elisp table.
2108 If the table is trivial, then return it as a scalar."
2110 (save-window-excursion
2114 (org-table-import file-name separator
)
2115 (delete-file file-name
)
2116 (setq result
(mapcar (lambda (row)
2117 (mapcar #'org-babel-string-read row
))
2118 (org-table-to-lisp))))
2120 (if (null (cdr result
)) ;; if result is trivial vector, then scalarize it
2121 (if (consp (car result
))
2122 (if (null (cdr (car result
)))
2128 (defun org-babel-string-read (cell)
2129 "Strip nested \"s from around strings."
2130 (org-babel-read (or (and (stringp cell
)
2131 (string-match "\\\"\\(.+\\)\\\"" cell
)
2132 (match-string 1 cell
))
2135 (defun org-babel-reverse-string (string)
2136 "Return the reverse of STRING."
2137 (apply 'string
(reverse (string-to-list string
))))
2139 (defun org-babel-chomp (string &optional regexp
)
2140 "Strip trailing spaces and carriage returns from STRING.
2141 Default regexp used is \"[ \f\t\n\r\v]\" but can be
2142 overwritten by specifying a regexp as a second argument."
2143 (let ((regexp (or regexp
"[ \f\t\n\r\v]")))
2144 (while (and (> (length string
) 0)
2145 (string-match regexp
(substring string -
1)))
2146 (setq string
(substring string
0 -
1)))
2149 (defun org-babel-trim (string &optional regexp
)
2150 "Strip leading and trailing spaces and carriage returns from STRING.
2151 Like `org-babel-chomp' only it runs on both the front and back
2153 (org-babel-chomp (org-babel-reverse-string
2154 (org-babel-chomp (org-babel-reverse-string string
) regexp
))
2157 (defvar org-babel-org-babel-call-process-region-original nil
)
2158 (defun org-babel-tramp-handle-call-process-region
2159 (start end program
&optional delete buffer display
&rest args
)
2160 "Use tramp to handle call-process-region.
2161 Fixes a bug in `tramp-handle-call-process-region'."
2162 (if (and (featurep 'tramp
) (file-remote-p default-directory
))
2163 (let ((tmpfile (tramp-compat-make-temp-file "")))
2164 (write-region start end tmpfile
)
2165 (when delete
(delete-region start end
))
2167 ;; (apply 'call-process program tmpfile buffer display args)
2169 (apply 'process-file program tmpfile buffer display args
)
2170 (delete-file tmpfile
)))
2171 ;; org-babel-call-process-region-original is the original emacs
2172 ;; definition. It is in scope from the let binding in
2173 ;; org-babel-execute-src-block
2174 (apply org-babel-call-process-region-original
2175 start end program delete buffer display args
)))
2177 (defun org-babel-local-file-name (file)
2178 "Return the local name component of FILE."
2179 (if (file-remote-p file
)
2181 (with-parsed-tramp-file-name file nil
2185 (defun org-babel-process-file-name (name &optional no-quote-p
)
2186 "Prepare NAME to be used in an external process.
2187 If NAME specifies a remote location, the remote portion of the
2188 name is removed, since in that case the process will be executing
2189 remotely. The file name is then processed by
2190 `expand-file-name'. Unless second argument NO-QUOTE-P is non-nil,
2191 the file name is additionally processed by
2192 `shell-quote-argument'"
2193 ((lambda (f) (if no-quote-p f
(shell-quote-argument f
)))
2194 (expand-file-name (org-babel-local-file-name name
))))
2196 (defvar org-babel-temporary-directory
)
2197 (unless (or noninteractive
(boundp 'org-babel-temporary-directory
))
2198 (defvar org-babel-temporary-directory
2199 (or (and (boundp 'org-babel-temporary-directory
)
2200 (file-exists-p org-babel-temporary-directory
)
2201 org-babel-temporary-directory
)
2202 (make-temp-file "babel-" t
))
2203 "Directory to hold temporary files created to execute code blocks.
2204 Used by `org-babel-temp-file'. This directory will be removed on
2207 (defun org-babel-temp-file (prefix &optional suffix
)
2208 "Create a temporary file in the `org-babel-temporary-directory'.
2209 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2210 value of `temporary-file-directory' temporarily set to the value
2211 of `org-babel-temporary-directory'."
2212 (if (file-remote-p default-directory
)
2214 (concat (file-remote-p default-directory
)
2216 prefix temporary-file-directory
)
2218 (let ((temporary-file-directory
2219 (or (and (boundp 'org-babel-temporary-directory
)
2220 (file-exists-p org-babel-temporary-directory
)
2221 org-babel-temporary-directory
)
2222 temporary-file-directory
)))
2223 (make-temp-file prefix nil suffix
))))
2225 (defun org-babel-remove-temporary-directory ()
2226 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2227 (when (and (boundp 'org-babel-temporary-directory
)
2228 (file-exists-p org-babel-temporary-directory
))
2229 ;; taken from `delete-directory' in files.el
2232 (mapc (lambda (file)
2233 ;; This test is equivalent to
2234 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2235 ;; but more efficient
2236 (if (eq t
(car (file-attributes file
)))
2237 (delete-directory file
)
2238 (delete-file file
)))
2239 ;; We do not want to delete "." and "..".
2240 (directory-files org-babel-temporary-directory
'full
2241 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2242 (delete-directory org-babel-temporary-directory
))
2244 (message "Failed to remove temporary Org-babel directory %s"
2245 (if (boundp 'org-babel-temporary-directory
)
2246 org-babel-temporary-directory
2247 "[directory not defined]"))))))
2249 (add-hook 'kill-emacs-hook
'org-babel-remove-temporary-directory
)