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
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-lob-execute-maybe
"ob-lob" ())
72 (declare-function org-number-sequence
"org-compat" (from &optional to inc
))
73 (declare-function org-at-item-p
"org-list" ())
74 (declare-function org-list-parse-list
"org-list" (&optional delete
))
75 (declare-function org-list-to-generic
"org-list" (LIST PARAMS
))
76 (declare-function org-list-struct
"org-list" ())
77 (declare-function org-list-prevs-alist
"org-list" (struct))
78 (declare-function org-list-get-list-end
"org-list" (item struct prevs
))
80 (defgroup org-babel nil
81 "Code block evaluation and management in `org-mode' documents."
85 (defcustom org-confirm-babel-evaluate t
86 "Confirm before evaluation.
87 Require confirmation before interactively evaluating code
88 blocks in Org-mode buffers. The default value of this variable
89 is t, meaning confirmation is required for any code block
90 evaluation. This variable can be set to nil to inhibit any
91 future confirmation requests. This variable can also be set to a
92 function which takes two arguments the language of the code block
93 and the body of the code block. Such a function should then
94 return a non-nil value if the user should be prompted for
95 execution or nil if no prompt is required.
97 Warning: Disabling confirmation may result in accidental
98 evaluation of potentially harmful code. It may be advisable
99 remove code block execution from C-c C-c as further protection
100 against accidental code block evaluation. The
101 `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
102 remove code block execution from the C-c C-c keybinding."
104 :type
'(choice boolean function
))
105 ;; don't allow this variable to be changed through file settings
106 (put 'org-confirm-babel-evaluate
'safe-local-variable
(lambda (x) (eq x t
)))
108 (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
109 "Remove code block evaluation from the C-c C-c key binding."
113 (defvar org-babel-src-name-regexp
114 "^[ \t]*#\\+\\(srcname\\|source\\|function\\):[ \t]*"
115 "Regular expression used to match a source name line.")
117 (defvar org-babel-multi-line-header-regexp
118 "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
119 "Regular expression used to match multi-line header arguments.")
121 (defvar org-babel-src-name-w-name-regexp
122 (concat org-babel-src-name-regexp
124 org-babel-multi-line-header-regexp
126 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)")
127 "Regular expression matching source name lines with a name.")
129 (defvar org-babel-src-block-regexp
131 ;; (1) indentation (2) lang
132 "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
134 "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
135 ;; (4) header arguments
138 "\\([^\000]*?\\)[ \t]*#\\+end_src")
139 "Regexp used to identify code blocks.")
141 (defvar org-babel-inline-src-block-regexp
143 ;; (1) replacement target (2) lang
144 "[^-[:alnum:]]\\(src_\\([^ \f\t\n\r\v]+\\)"
145 ;; (3,4) (unused, headers)
146 "\\(\\|\\[\\(.*?\\)\\]\\)"
148 "{\\([^\f\n\r\v]+?\\)}\\)")
149 "Regexp used to identify inline src-blocks.")
151 (defun org-babel-get-header (params key
&optional others
)
152 "Select only header argument of type KEY from a list.
153 Optional argument OTHERS indicates that only the header that do
154 not match KEY should be returned."
157 (lambda (p) (when (funcall (if others
#'not
#'identity
) (eq (car p
) key
)) p
))
160 (defun org-babel-get-src-block-info (&optional light
)
161 "Get information on the current source block.
163 Optional argument LIGHT does not resolve remote variable
164 references; a process which could likely result in the execution
165 of other code blocks.
168 (language body header-arguments-alist switches name indent)."
169 (let ((case-fold-search t
) head info name indent
)
171 (if (setq head
(org-babel-where-is-src-block-head))
174 (setq info
(org-babel-parse-src-block-match))
175 (setq indent
(car (last info
)))
176 (setq info
(butlast info
))
177 (while (and (forward-line -
1)
178 (looking-at org-babel-multi-line-header-regexp
))
180 (org-babel-merge-params
182 (org-babel-parse-header-arguments (match-string 1)))))
183 (when (looking-at org-babel-src-name-w-name-regexp
)
184 (setq name
(org-babel-clean-text-properties (match-string 4)))
185 (when (match-string 6)
186 (setf (nth 2 info
) ;; merge functional-syntax vars and header-args
187 (org-babel-merge-params
188 (mapcar (lambda (ref) (cons :var ref
))
189 (org-babel-ref-split-args (match-string 6)))
191 ;; inline source block
192 (when (save-excursion (re-search-backward "[ \f\t\n\r\v]" nil t
)
193 (looking-at org-babel-inline-src-block-regexp
))
194 (setq info
(org-babel-parse-inline-src-block-match))))
195 ;; resolve variable references and add summary parameters
196 (when (and info
(not light
))
197 (setf (nth 2 info
) (org-babel-process-params (nth 2 info
))))
198 (when info
(append info
(list name indent
)))))
200 (defun org-babel-confirm-evaluate (info)
201 "Confirm evaluation of the code block INFO.
202 This behavior can be suppressed by setting the value of
203 `org-confirm-babel-evaluate' to nil, in which case all future
204 interactive code block evaluations will proceed without any
205 confirmation from the user.
207 Note disabling confirmation may result in accidental evaluation
208 of potentially harmful code."
209 (let* ((eval (or (cdr (assoc :eval
(nth 2 info
)))
210 (when (assoc :noeval
(nth 2 info
)) "no")))
211 (query (cond ((equal eval
"query") t
)
212 ((functionp org-confirm-babel-evaluate
)
213 (funcall org-confirm-babel-evaluate
214 (nth 0 info
) (nth 1 info
)))
215 (t org-confirm-babel-evaluate
))))
216 (if (or (equal eval
"never") (equal eval
"no")
219 (format "Evaluate this%scode block%son your system? "
220 (if info
(format " %s " (nth 0 info
)) " ")
222 (format " (%s) " (nth 4 info
)) " "))))))
223 (prog1 nil
(message "Evaluation %s"
224 (if (or (equal eval
"never") (equal eval
"no"))
225 "Disabled" "Aborted")))
229 (defun org-babel-execute-safely-maybe ()
230 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
231 (org-babel-execute-maybe)))
233 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-execute-safely-maybe
)
236 (defun org-babel-execute-maybe ()
238 (or (org-babel-execute-src-block-maybe)
239 (org-babel-lob-execute-maybe)))
241 (defun org-babel-execute-src-block-maybe ()
242 "Conditionally execute a source block.
243 Detect if this is context for a Babel src-block and if so
244 then run `org-babel-execute-src-block'."
246 (let ((info (org-babel-get-src-block-info)))
248 (progn (org-babel-eval-wipe-error-buffer)
249 (org-babel-execute-src-block current-prefix-arg info
) t
) nil
)))
252 (defun org-babel-expand-src-block-maybe ()
253 "Conditionally expand a source block.
254 Detect if this is context for a org-babel src-block and if so
255 then run `org-babel-expand-src-block'."
257 (let ((info (org-babel-get-src-block-info)))
259 (progn (org-babel-expand-src-block current-prefix-arg info
) t
)
263 (defun org-babel-load-in-session-maybe ()
264 "Conditionally load a source block in a session.
265 Detect if this is context for a org-babel src-block and if so
266 then run `org-babel-load-in-session'."
268 (let ((info (org-babel-get-src-block-info)))
270 (progn (org-babel-load-in-session current-prefix-arg info
) t
)
273 (add-hook 'org-metaup-hook
'org-babel-load-in-session-maybe
)
276 (defun org-babel-pop-to-session-maybe ()
277 "Conditionally pop to a session.
278 Detect if this is context for a org-babel src-block and if so
279 then run `org-babel-pop-to-session'."
281 (let ((info (org-babel-get-src-block-info)))
282 (if info
(progn (org-babel-pop-to-session current-prefix-arg info
) t
) nil
)))
284 (add-hook 'org-metadown-hook
'org-babel-pop-to-session-maybe
)
286 (defconst org-babel-header-arg-names
287 '(cache cmdline colnames dir exports file noweb results
288 session tangle var eval noeval comments no-expand shebang
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 (:padnewline .
"yes"))
298 "Default arguments to use when evaluating a source block.")
300 (defvar org-babel-default-inline-header-args
301 '((:session .
"none") (:results .
"replace") (:exports .
"results"))
302 "Default arguments to use when evaluating an inline source block.")
304 (defvar org-babel-data-names
'("TBLNAME" "RESNAME" "RESULTS" "DATA"))
306 (defvar org-babel-result-regexp
307 (concat "^[ \t]*#\\+"
308 (regexp-opt org-babel-data-names t
)
309 "\\(\\[\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*")
310 "Regular expression used to match result lines.
311 If the results are associated with a hash key then the hash will
312 be saved in the second match data.")
314 (defvar org-babel-result-w-name-regexp
315 (concat org-babel-result-regexp
316 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
318 (defvar org-babel-min-lines-for-block-output
10
319 "The minimum number of lines for block output.
320 If number of lines of output is equal to or exceeds this
321 value, the output is placed in a #+begin_example...#+end_example
322 block. Otherwise the output is marked as literal by inserting
323 colons at the starts of the lines. This variable only takes
324 effect if the :results output option is in effect.")
326 (defvar org-babel-noweb-error-langs nil
327 "Languages for which Babel will raise literate programming errors.
328 List of languages for which errors should be raised when the
329 source code block satisfying a noweb reference in this language
330 can not be resolved.")
332 (defvar org-babel-hash-show
4
333 "Number of initial characters to show of a hidden results hash.")
335 (defvar org-babel-after-execute-hook nil
336 "Hook for functions to be called after `org-babel-execute-src-block'")
337 (defun org-babel-named-src-block-regexp-for-name (name)
338 "This generates a regexp used to match a src block named NAME."
339 (concat org-babel-src-name-regexp
(regexp-quote name
) "[ \t\n]*"
340 (substring org-babel-src-block-regexp
1)))
343 (defvar call-process-region
)
346 (defun org-babel-execute-src-block (&optional arg info params
)
347 "Execute the current source code block.
348 Insert the results of execution into the buffer. Source code
349 execution and the collection and formatting of results can be
350 controlled through a variety of header arguments.
352 With prefix argument ARG, force re-execution even if a an
353 existing result cached in the buffer would otherwise have been
356 Optionally supply a value for INFO in the form returned by
357 `org-babel-get-src-block-info'.
359 Optionally supply a value for PARAMS which will be merged with
360 the header arguments specified at the front of the source code
363 (let ((info (or info
(org-babel-get-src-block-info))))
364 (when (org-babel-confirm-evaluate info
)
365 (let* ((lang (nth 0 info
))
367 (org-babel-process-params
368 (org-babel-merge-params (nth 2 info
) params
))
370 (cache?
(and (not arg
) (cdr (assoc :cache params
))
371 (string= "yes" (cdr (assoc :cache params
)))))
372 (result-params (cdr (assoc :result-params params
)))
373 (new-hash (when cache?
(org-babel-sha1-hash info
)))
374 (old-hash (when cache?
(org-babel-result-hash info
)))
375 (body (setf (nth 1 info
)
376 (let ((noweb (cdr (assoc :noweb params
))))
378 (or (string= "yes" noweb
)
379 (string= "tangle" noweb
)))
380 (org-babel-expand-noweb-references info
)
382 (dir (cdr (assoc :dir params
)))
384 (or (and dir
(file-name-as-directory dir
)) default-directory
))
385 (org-babel-call-process-region-original
386 (if (boundp 'org-babel-call-process-region-original
)
387 org-babel-call-process-region-original
388 (symbol-function 'call-process-region
)))
389 (indent (car (last info
)))
392 (flet ((call-process-region (&rest args
)
393 (apply 'org-babel-tramp-handle-call-process-region args
)))
394 (flet ((lang-check (f)
395 (let ((f (intern (concat "org-babel-execute:" f
))))
396 (when (fboundp f
) f
))))
398 (or (lang-check lang
)
399 (lang-check (symbol-name
400 (cdr (assoc lang org-src-lang-modes
))))
401 (error "No org-babel-execute function for %s!" lang
))))
402 (if (and (not arg
) new-hash
(equal new-hash old-hash
))
403 (save-excursion ;; return cached result
404 (goto-char (org-babel-where-is-src-block-result nil info
))
405 (end-of-line 1) (forward-char 1)
406 (setq result
(org-babel-read-result))
407 (message (replace-regexp-in-string
408 "%" "%%" (format "%S" result
))) result
)
409 (message "executing %s code block%s..."
411 (if (nth 4 info
) (format " (%s)" (nth 4 info
)) ""))
414 (if (and (eq (cdr (assoc :result-type params
)) 'value
)
415 (or (member "vector" result-params
)
416 (member "table" result-params
))
417 (not (listp result
)))
418 (list (list result
)) result
))
419 (funcall cmd body params
)))
420 ;; if non-empty result and :file then write to :file
421 (when (cdr (assoc :file params
))
423 (with-temp-file (cdr (assoc :file params
))
425 (org-babel-format-result
426 result
(cdr (assoc :sep
(nth 2 info
)))))))
427 (setq result
(cdr (assoc :file params
))))
428 (org-babel-insert-result
429 result result-params info new-hash indent lang
)
430 (run-hooks 'org-babel-after-execute-hook
)
432 (setq call-process-region
'org-babel-call-process-region-original
))))))
434 (defun org-babel-expand-body:generic
(body params
&optional var-lines
)
435 "Expand BODY with PARAMS.
436 Expand a block of code with org-babel according to it's header
437 arguments. This generic implementation of body expansion is
438 called for languages which have not defined their own specific
439 org-babel-expand-body:lang function."
440 (mapconcat #'identity
(append var-lines
(list body
)) "\n"))
443 (defun org-babel-expand-src-block (&optional arg info params
)
444 "Expand the current source code block.
445 Expand according to the source code block's header
446 arguments and pop open the results in a preview buffer."
448 (let* ((info (or info
(org-babel-get-src-block-info)))
450 (params (setf (nth 2 info
)
451 (sort (org-babel-merge-params (nth 2 info
) params
)
452 (lambda (el1 el2
) (string< (symbol-name (car el1
))
453 (symbol-name (car el2
)))))))
454 (body (setf (nth 1 info
)
455 (if (and (cdr (assoc :noweb params
))
456 (string= "yes" (cdr (assoc :noweb params
))))
457 (org-babel-expand-noweb-references info
) (nth 1 info
))))
458 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
459 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
462 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
463 (org-babel-expand-body:generic
464 body params
(and (fboundp assignments-cmd
)
465 (funcall assignments-cmd params
))))))
467 nil expanded
(concat "*Org-Babel Preview " (buffer-name) "[ " lang
" ]*"))))
469 (defun org-babel-edit-distance (s1 s2
)
470 "Return the edit (levenshtein) distance between strings S1 S2."
471 (let* ((l1 (length s1
))
473 (dist (map 'vector
(lambda (_) (make-vector (1+ l2
) nil
))
474 (number-sequence 1 (1+ l1
)))))
475 (flet ((in (i j
) (aref (aref dist i
) j
))
476 (mmin (&rest lst
) (apply #'min
(remove nil lst
))))
477 (setf (aref (aref dist
0) 0) 0)
478 (dolist (i (number-sequence 1 l1
))
479 (dolist (j (number-sequence 1 l2
))
480 (setf (aref (aref dist i
) j
)
481 (+ (if (equal (aref s1
(1- i
)) (aref s2
(1- j
))) 0 1)
482 (mmin (in (1- i
) j
) (in i
(1- j
)) (in (1- i
) (1- j
)))))))
486 (defun org-babel-check-src-block ()
487 "Check for misspelled header arguments in the current code block."
489 ;; TODO: report malformed code block
490 ;; TODO: report incompatible combinations of header arguments
491 (let ((too-close 2)) ;; <- control closeness to report potential match
492 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg
)) 1))
493 (and (org-babel-where-is-src-block-head)
494 (org-babel-parse-header-arguments
495 (org-babel-clean-text-properties
496 (match-string 4))))))
497 (dolist (name (mapcar #'symbol-name org-babel-header-arg-names
))
498 (when (and (not (string= header name
))
499 (<= (org-babel-edit-distance header name
) too-close
))
500 (error "supplied header \"%S\" is suspiciously close to \"%S\""
502 (message "No suspicious header arguments found.")))
505 (defun org-babel-load-in-session (&optional arg info
)
506 "Load the body of the current source-code block.
507 Evaluate the header arguments for the source block before
508 entering the session. After loading the body this pops open the
511 (let* ((info (or info
(org-babel-get-src-block-info)))
513 (params (nth 2 info
))
514 (body (setf (nth 1 info
)
515 (if (and (cdr (assoc :noweb params
))
516 (string= "yes" (cdr (assoc :noweb params
))))
517 (org-babel-expand-noweb-references info
)
519 (session (cdr (assoc :session params
)))
520 (dir (cdr (assoc :dir params
)))
522 (or (and dir
(file-name-as-directory dir
)) default-directory
))
523 (cmd (intern (concat "org-babel-load-session:" lang
))))
524 (unless (fboundp cmd
)
525 (error "No org-babel-load-session function for %s!" lang
))
526 (pop-to-buffer (funcall cmd session body params
))
530 (defun org-babel-initiate-session (&optional arg info
)
531 "Initiate session for current code block.
532 If called with a prefix argument then resolve any variable
533 references in the header arguments and assign these variables in
534 the session. Copy the body of the code block to the kill ring."
536 (let* ((info (or info
(org-babel-get-src-block-info (not arg
))))
539 (params (nth 2 info
))
540 (session (cdr (assoc :session params
)))
541 (dir (cdr (assoc :dir params
)))
543 (or (and dir
(file-name-as-directory dir
)) default-directory
))
544 (init-cmd (intern (format "org-babel-%s-initiate-session" lang
)))
545 (prep-cmd (intern (concat "org-babel-prep-session:" lang
))))
546 (if (and (stringp session
) (string= session
"none"))
547 (error "This block is not using a session!"))
548 (unless (fboundp init-cmd
)
549 (error "No org-babel-initiate-session function for %s!" lang
))
550 (with-temp-buffer (insert (org-babel-trim body
))
551 (copy-region-as-kill (point-min) (point-max)))
553 (unless (fboundp prep-cmd
)
554 (error "No org-babel-prep-session function for %s!" lang
))
555 (funcall prep-cmd session params
))
556 (funcall init-cmd session params
)))
559 (defun org-babel-switch-to-session (&optional arg info
)
560 "Switch to the session of the current code block.
561 Uses `org-babel-initiate-session' to start the session. If called
562 with a prefix argument then this is passed on to
563 `org-babel-initiate-session'."
565 (pop-to-buffer (org-babel-initiate-session arg info
))
568 (defalias 'org-babel-pop-to-session
'org-babel-switch-to-session
)
571 (defun org-babel-switch-to-session-with-code (&optional arg info
)
572 "Switch to code buffer and display session."
576 (let ((other-window-buffer (window-buffer (next-window))))
577 (set-window-buffer (next-window) (current-buffer))
578 (set-window-buffer (selected-window) other-window-buffer
))
580 (let ((info (org-babel-get-src-block-info))
581 (org-src-window-setup 'reorganize-frame
))
583 (org-babel-switch-to-session arg info
))
587 (defmacro org-babel-do-in-edit-buffer
(&rest body
)
588 "Evaluate BODY in edit buffer if there is a code block at point.
589 Return t if a code block was found at point, nil otherwise."
590 `(let ((org-src-window-setup 'switch-invisibly
))
591 (when (and (org-babel-where-is-src-block-head)
592 (org-edit-src-code nil nil nil
))
593 (unwind-protect (progn ,@body
)
594 (if (org-bound-and-true-p org-edit-src-from-org-mode
)
595 (org-edit-src-exit)))
598 (defun org-babel-do-key-sequence-in-edit-buffer (key)
599 "Read key sequence and execute the command in edit buffer.
600 Enter a key sequence to be executed in the language major-mode
601 edit buffer. For example, TAB will alter the contents of the
602 Org-mode code block according to the effect of TAB in the
603 language major-mode buffer. For languages that support
604 interactive sessions, this can be used to send code from the Org
605 buffer to the session for evaluation using the native major-mode
606 evaluation mechanisms."
607 (interactive "kEnter key-sequence to execute in edit buffer: ")
608 (org-babel-do-in-edit-buffer
610 (key-binding (or key
(read-key-sequence nil
))))))
612 (defvar org-bracket-link-regexp
)
614 (defun org-babel-open-src-block-result (&optional re-run
)
615 "If `point' is on a src block then open the results of the
616 source code block, otherwise return nil. With optional prefix
617 argument RE-RUN the source-code block is evaluated even if
618 results already exist."
620 (let ((info (org-babel-get-src-block-info)))
623 ;; go to the results, if there aren't any then run the block
624 (goto-char (or (and (not re-run
) (org-babel-where-is-src-block-result))
625 (progn (org-babel-execute-src-block)
626 (org-babel-where-is-src-block-result))))
628 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
630 (if (looking-at org-bracket-link-regexp
)
633 (let ((r (org-babel-format-result
634 (org-babel-read-result) (cdr (assoc :sep
(nth 2 info
))))))
635 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
636 (delete-region (point-min) (point-max))
641 (defmacro org-babel-map-src-blocks
(file &rest body
)
642 "Evaluate BODY forms on each source-block in FILE.
643 If FILE is nil evaluate BODY forms on source blocks in current
644 buffer. During evaluation of BODY the following local variables
645 are set relative to the currently matched code block.
647 full-block ------- string holding the entirety of the code block
648 beg-block -------- point at the beginning of the code block
649 end-block -------- point at the end of the matched code block
650 lang ------------- string holding the language of the code block
651 beg-lang --------- point at the beginning of the lang
652 end-lang --------- point at the end of the lang
653 switches --------- string holding the switches
654 beg-switches ----- point at the beginning of the switches
655 end-switches ----- point at the end of the switches
656 header-args ------ string holding the header-args
657 beg-header-args -- point at the beginning of the header-args
658 end-header-args -- point at the end of the header-args
659 body ------------- string holding the body of the code block
660 beg-body --------- point at the beginning of the body
661 end-body --------- point at the end of the body"
663 (let ((tempvar (make-symbol "file")))
664 `(let* ((,tempvar
,file
)
665 (visited-p (or (null ,tempvar
)
666 (get-file-buffer (expand-file-name ,tempvar
))))
667 (point (point)) to-be-removed
)
668 (save-window-excursion
669 (when ,tempvar
(find-file ,tempvar
))
670 (setq to-be-removed
(current-buffer))
671 (goto-char (point-min))
672 (while (re-search-forward org-babel-src-block-regexp nil t
)
673 (goto-char (match-beginning 0))
674 (let ((full-block (match-string 0))
675 (beg-block (match-beginning 0))
676 (end-block (match-end 0))
677 (lang (match-string 2))
678 (beg-lang (match-beginning 2))
679 (end-lang (match-end 2))
680 (switches (match-string 3))
681 (beg-switches (match-beginning 3))
682 (end-switches (match-end 3))
683 (header-args (match-string 4))
684 (beg-header-args (match-beginning 4))
685 (end-header-args (match-end 4))
686 (body (match-string 5))
687 (beg-body (match-beginning 5))
688 (end-body (match-end 5)))
690 (goto-char end-block
))))
691 (unless visited-p
(kill-buffer to-be-removed
))
695 (defmacro org-babel-map-inline-src-blocks
(file &rest body
)
696 "Evaluate BODY forms on each inline source-block in FILE.
697 If FILE is nil evaluate BODY forms on source blocks in current
700 (let ((tempvar (make-symbol "file")))
701 `(let* ((,tempvar
,file
)
702 (visited-p (or (null ,tempvar
)
703 (get-file-buffer (expand-file-name ,tempvar
))))
704 (point (point)) to-be-removed
)
705 (save-window-excursion
706 (when ,tempvar
(find-file ,tempvar
))
707 (setq to-be-removed
(current-buffer))
708 (goto-char (point-min))
709 (while (re-search-forward org-babel-inline-src-block-regexp nil t
)
710 (goto-char (match-beginning 1))
711 (save-match-data ,@body
)
712 (goto-char (match-end 0))))
713 (unless visited-p
(kill-buffer to-be-removed
))
717 (defun org-babel-execute-buffer (&optional arg
)
718 "Execute source code blocks in a buffer.
719 Call `org-babel-execute-src-block' on every source block in
722 (org-babel-eval-wipe-error-buffer)
723 (org-save-outline-visibility t
724 (org-babel-map-src-blocks nil
725 (org-babel-execute-src-block arg
))
726 (org-babel-map-inline-src-blocks nil
727 (org-babel-execute-src-block arg
))))
730 (defun org-babel-execute-subtree (&optional arg
)
731 "Execute source code blocks in a subtree.
732 Call `org-babel-execute-src-block' on every source block in
733 the current subtree."
737 (org-narrow-to-subtree)
738 (org-babel-execute-buffer arg
)
742 (defun org-babel-sha1-hash (&optional info
)
743 "Generate an sha1 hash based on the value of info."
745 (let ((print-level nil
)
746 (info (or info
(org-babel-get-src-block-info))))
748 (sort (copy-sequence (nth 2 info
))
749 (lambda (a b
) (string< (car a
) (car b
)))))
750 ((lambda (hash) (when (interactive-p) (message hash
)) hash
)
751 (sha1 (format "%s-%s"
758 (when (and v
(not (and (sequencep v
)
761 ((lambda (el) (format "%S" el
))
763 ((and (listp v
) ; lists are sorted
764 (member (car arg
) '(:result-params
)))
765 (sort (copy-sequence v
) #'string
<))
766 ((and (stringp v
) ; strings are sorted
767 (member (car arg
) '(:results
:exports
)))
768 (mapconcat #'identity
(sort (split-string v
)
770 (t v
)))))) ; atomic are left untouched
774 (defun org-babel-result-hash (&optional info
)
775 "Return the in-buffer hash associated with INFO."
776 (org-babel-where-is-src-block-result nil info
)
777 (org-babel-clean-text-properties (match-string 3)))
779 (defun org-babel-hide-hash ()
780 "Hide the hash in the current results line.
781 Only the initial `org-babel-hash-show' characters of the hash
782 will remain visible."
783 (add-to-invisibility-spec '(org-babel-hide-hash . t
))
785 (when (and (re-search-forward org-babel-result-regexp nil t
)
787 (let* ((start (match-beginning 3))
788 (hide-start (+ org-babel-hash-show start
))
790 (hash (match-string 3))
792 (setq ov1
(make-overlay start hide-start
))
793 (setq ov2
(make-overlay hide-start end
))
794 (overlay-put ov2
'invisible
'org-babel-hide-hash
)
795 (overlay-put ov1
'babel-hash hash
)))))
797 (defun org-babel-hide-all-hashes ()
798 "Hide the hash in the current buffer.
799 Only the initial `org-babel-hash-show' characters of each hash
800 will remain visible. This function should be called as part of
801 the `org-mode-hook'."
803 (while (re-search-forward org-babel-result-regexp nil t
)
804 (goto-char (match-beginning 0))
805 (org-babel-hide-hash)
806 (goto-char (match-end 0)))))
807 (add-hook 'org-mode-hook
'org-babel-hide-all-hashes
)
809 (defun org-babel-hash-at-point (&optional point
)
810 "Return the value of the hash at POINT.
811 The hash is also added as the last element of the kill ring.
812 This can be called with C-c C-c."
814 (let ((hash (car (delq nil
(mapcar
815 (lambda (ol) (overlay-get ol
'babel-hash
))
816 (overlays-at (or point
(point))))))))
817 (when hash
(kill-new hash
) (message hash
))))
818 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-hash-at-point
)
820 (defun org-babel-result-hide-spec ()
821 "Hide portions of results lines.
822 Add `org-babel-hide-result' as an invisibility spec for hiding
823 portions of results lines."
824 (add-to-invisibility-spec '(org-babel-hide-result . t
)))
825 (add-hook 'org-mode-hook
'org-babel-result-hide-spec
)
827 (defvar org-babel-hide-result-overlays nil
828 "Overlays hiding results.")
830 (defun org-babel-result-hide-all ()
831 "Fold all results in the current buffer."
833 (org-babel-show-result-all)
835 (while (re-search-forward org-babel-result-regexp nil t
)
836 (save-excursion (goto-char (match-beginning 0))
837 (org-babel-hide-result-toggle-maybe)))))
839 (defun org-babel-show-result-all ()
840 "Unfold all results in the current buffer."
841 (mapc 'delete-overlay org-babel-hide-result-overlays
)
842 (setq org-babel-hide-result-overlays nil
))
845 (defun org-babel-hide-result-toggle-maybe ()
846 "Toggle visibility of result at point."
848 (let ((case-fold-search t
))
850 (beginning-of-line 1)
851 (looking-at org-babel-result-regexp
))
852 (progn (org-babel-hide-result-toggle)
853 t
) ;; to signal that we took action
854 nil
))) ;; to signal that we did not
856 (defun org-babel-hide-result-toggle (&optional force
)
857 "Toggle the visibility of the current result."
861 (if (re-search-forward org-babel-result-regexp nil t
)
862 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
863 (end (progn (goto-char (- (org-babel-result-end) 1)) (point)))
865 (if (memq t
(mapcar (lambda (overlay)
866 (eq (overlay-get overlay
'invisible
)
867 'org-babel-hide-result
))
868 (overlays-at start
)))
869 (if (or (not force
) (eq force
'off
))
871 (when (member ov org-babel-hide-result-overlays
)
872 (setq org-babel-hide-result-overlays
873 (delq ov org-babel-hide-result-overlays
)))
874 (when (eq (overlay-get ov
'invisible
)
875 'org-babel-hide-result
)
876 (delete-overlay ov
)))
877 (overlays-at start
)))
878 (setq ov
(make-overlay start end
))
879 (overlay-put ov
'invisible
'org-babel-hide-result
)
880 ;; make the block accessible to isearch
882 ov
'isearch-open-invisible
884 (when (member ov org-babel-hide-result-overlays
)
885 (setq org-babel-hide-result-overlays
886 (delq ov org-babel-hide-result-overlays
)))
887 (when (eq (overlay-get ov
'invisible
)
888 'org-babel-hide-result
)
889 (delete-overlay ov
))))
890 (push ov org-babel-hide-result-overlays
)))
891 (error "Not looking at a result line"))))
893 ;; org-tab-after-check-for-cycling-hook
894 (add-hook 'org-tab-first-hook
'org-babel-hide-result-toggle-maybe
)
895 ;; Remove overlays when changing major mode
896 (add-hook 'org-mode-hook
897 (lambda () (org-add-hook 'change-major-mode-hook
898 'org-babel-show-result-all
'append
'local
)))
900 (defvar org-file-properties
)
901 (defun org-babel-params-from-properties (&optional lang
)
902 "Retrieve parameters specified as properties.
903 Return an association list of any source block params which
904 may be specified in the properties of the current outline entry."
911 (or (org-entry-get (point) header-arg t
)
912 (org-entry-get (point) (concat ":" header-arg
) t
)))
913 (cons (intern (concat ":" header-arg
))
914 (org-babel-read val
))))
918 org-babel-header-arg-names
920 (setq sym
(intern (concat "org-babel-header-arg-names:" lang
)))
921 (and (boundp sym
) (eval sym
))))))))))
923 (defun org-babel-params-from-buffer ()
924 "Retrieve per-buffer parameters.
925 Return an association list of any source block params which
926 may be specified in the current buffer."
927 (let (local-properties)
932 (goto-char (point-min))
933 (while (re-search-forward
934 (org-make-options-regexp (list "BABEL" "PROPERTIES")) nil t
)
935 (setq local-properties
936 (org-babel-merge-params
938 (org-babel-parse-header-arguments
939 (org-match-string-no-properties 2)))))
940 local-properties
)))))
942 (defvar org-src-preserve-indentation
)
943 (defun org-babel-parse-src-block-match ()
944 "Parse the results from a match of the `org-babel-src-block-regexp'."
945 (let* ((block-indentation (length (match-string 1)))
946 (lang (org-babel-clean-text-properties (match-string 2)))
947 (lang-headers (intern (concat "org-babel-default-header-args:" lang
)))
948 (switches (match-string 3))
949 (body (org-babel-clean-text-properties (match-string 5)))
950 (preserve-indentation (or org-src-preserve-indentation
951 (string-match "-i\\>" switches
))))
953 ;; get block body less properties, protective commas, and indentation
956 (insert (org-babel-strip-protective-commas body
))
957 (unless preserve-indentation
(org-do-remove-indentation))
959 (org-babel-merge-params
960 org-babel-default-header-args
961 (org-babel-params-from-buffer)
962 (org-babel-params-from-properties lang
)
963 (if (boundp lang-headers
) (eval lang-headers
) nil
)
964 (org-babel-parse-header-arguments
965 (org-babel-clean-text-properties (or (match-string 4) ""))))
969 (defun org-babel-parse-inline-src-block-match ()
970 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
971 (let* ((lang (org-babel-clean-text-properties (match-string 2)))
972 (lang-headers (intern (concat "org-babel-default-header-args:" lang
))))
974 (org-babel-strip-protective-commas
975 (org-babel-clean-text-properties (match-string 5)))
976 (org-babel-merge-params
977 org-babel-default-inline-header-args
978 (org-babel-params-from-buffer)
979 (org-babel-params-from-properties lang
)
980 (if (boundp lang-headers
) (eval lang-headers
) nil
)
981 (org-babel-parse-header-arguments
982 (org-babel-clean-text-properties (or (match-string 4) "")))))))
984 (defun org-babel-parse-header-arguments (arg-string)
985 "Parse a string of header arguments returning an alist."
986 (when (> (length arg-string
) 0)
991 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
993 (cons (intern (match-string 1 arg
))
994 (org-babel-read (org-babel-chomp (match-string 2 arg
))))
995 (cons (intern (org-babel-chomp arg
)) nil
)))
996 (let ((balance 0) (partial nil
) (lst nil
) (last 0))
997 (mapc (lambda (ch) ; split on [] balanced instances of [ \t]:
998 (setq balance
(+ balance
999 (cond ((equal 91 ch
) 1)
1002 (setq partial
(cons ch partial
))
1003 (when (and (= ch
58) (= balance
0)
1004 (or (= last
32) (= last
9)))
1005 (setq lst
(cons (apply #'string
(nreverse (cddr partial
)))
1007 (setq partial
(list ch
)))
1009 (string-to-list arg-string
))
1010 (nreverse (cons (apply #'string
(nreverse partial
)) lst
)))))))
1012 (defun org-babel-process-params (params)
1013 "Expand variables in PARAMS and add summary parameters."
1014 (let* ((vars-and-names (org-babel-disassemble-tables
1015 (mapcar (lambda (el)
1016 (if (consp (cdr el
))
1017 (cdr el
) (org-babel-ref-parse (cdr el
))))
1018 (org-babel-get-header params
:var
))
1019 (cdr (assoc :hlines params
))
1020 (cdr (assoc :colnames params
))
1021 (cdr (assoc :rownames params
))))
1022 (raw-result (or (cdr (assoc :results params
)) ""))
1023 (result-params (append
1024 (split-string (if (stringp raw-result
)
1027 (cdr (assoc :result-params params
)))))
1029 (mapcar (lambda (var) (cons :var var
)) (car vars-and-names
))
1031 (cons :colname-names
(or (cdr (assoc :colname-names params
))
1032 (cadr vars-and-names
)))
1033 (cons :rowname-names
(or (cdr (assoc :rowname-names params
))
1034 (caddr vars-and-names
)))
1035 (cons :result-params result-params
)
1036 (cons :result-type
(cond ((member "output" result-params
) 'output
)
1037 ((member "value" result-params
) 'value
)
1039 (org-babel-get-header params
:var
'other
))))
1041 ;; row and column names
1042 (defun org-babel-del-hlines (table)
1043 "Remove all 'hlines from TABLE."
1044 (remove 'hline table
))
1046 (defun org-babel-get-colnames (table)
1047 "Return the column names of TABLE.
1048 Return a cons cell, the `car' of which contains the TABLE less
1049 colnames, and the `cdr' of which contains a list of the column
1051 (if (equal 'hline
(nth 1 table
))
1052 (cons (cddr table
) (car table
))
1053 (cons (cdr table
) (car table
))))
1055 (defun org-babel-get-rownames (table)
1056 "Return the row names of TABLE.
1057 Return a cons cell, the `car' of which contains the TABLE less
1058 colnames, and the `cdr' of which contains a list of the column
1059 names. Note: this function removes any hlines in TABLE."
1060 (flet ((trans (table) (apply #'mapcar
* #'list table
)))
1061 (let* ((width (apply 'max
1062 (mapcar (lambda (el) (if (listp el
) (length el
) 0)) table
)))
1063 (table (trans (mapcar (lambda (row)
1064 (if (not (equal row
'hline
))
1068 (setq row
(cons 'hline row
)))
1071 (cons (mapcar (lambda (row) (if (equal (car row
) 'hline
) 'hline row
))
1072 (trans (cdr table
)))
1073 (remove 'hline
(car table
))))))
1075 (defun org-babel-put-colnames (table colnames
)
1076 "Add COLNAMES to TABLE if they exist."
1077 (if colnames
(apply 'list colnames
'hline table
) table
))
1079 (defun org-babel-put-rownames (table rownames
)
1080 "Add ROWNAMES to TABLE if they exist."
1082 (mapcar (lambda (row)
1084 (cons (or (pop rownames
) "") row
)
1088 (defun org-babel-pick-name (names selector
)
1089 "Select one out of an alist of row or column names.
1090 SELECTOR can be either a list of names in which case those names
1091 will be returned directly, or an index into the list NAMES in
1092 which case the indexed names will be return."
1093 (if (listp selector
)
1096 (if (and selector
(symbolp selector
) (not (equal t selector
)))
1097 (cdr (assoc selector names
))
1098 (if (integerp selector
)
1099 (nth (- selector
1) names
)
1100 (cdr (car (last names
))))))))
1102 (defun org-babel-disassemble-tables (vars hlines colnames rownames
)
1103 "Parse tables for further processing.
1104 Process the variables in VARS according to the HLINES,
1105 ROWNAMES and COLNAMES header arguments. Return a list consisting
1106 of the vars, cnames and rnames."
1107 (let (cnames rnames
)
1111 (when (listp (cdr var
))
1112 (when (and (not (equal colnames
"no"))
1113 (or colnames
(and (equal (nth 1 (cdr var
)) 'hline
)
1114 (not (member 'hline
(cddr (cdr var
)))))))
1115 (let ((both (org-babel-get-colnames (cdr var
))))
1116 (setq cnames
(cons (cons (car var
) (cdr both
))
1118 (setq var
(cons (car var
) (car both
)))))
1119 (when (and rownames
(not (equal rownames
"no")))
1120 (let ((both (org-babel-get-rownames (cdr var
))))
1121 (setq rnames
(cons (cons (car var
) (cdr both
))
1123 (setq var
(cons (car var
) (car both
)))))
1124 (when (and hlines
(not (equal hlines
"yes")))
1125 (setq var
(cons (car var
) (org-babel-del-hlines (cdr var
))))))
1130 (defun org-babel-reassemble-table (table colnames rownames
)
1131 "Add column and row names to a table.
1132 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1133 to the table for reinsertion to org-mode."
1136 (if (and colnames
(listp (car table
)) (= (length (car table
))
1138 (org-babel-put-colnames table colnames
) table
))
1139 (if (and rownames
(= (length table
) (length rownames
)))
1140 (org-babel-put-rownames table rownames
) table
))
1143 (defun org-babel-where-is-src-block-head ()
1144 "Find where the current source block begins.
1145 Return the point at the beginning of the current source
1146 block. Specifically at the beginning of the #+BEGIN_SRC line.
1147 If the point is not on a source block then return nil."
1148 (let ((initial (point)) top bottom
)
1150 (save-excursion ;; on a source name line or a #+header line
1151 (beginning-of-line 1)
1152 (and (or (looking-at org-babel-src-name-regexp
)
1153 (looking-at org-babel-multi-line-header-regexp
))
1155 (while (and (forward-line 1)
1156 (looking-at org-babel-multi-line-header-regexp
)))
1157 (looking-at org-babel-src-block-regexp
))
1159 (save-excursion ;; on a #+begin_src line
1160 (beginning-of-line 1)
1161 (and (looking-at org-babel-src-block-regexp
)
1163 (save-excursion ;; inside a src block
1165 (re-search-backward "^[ \t]*#\\+begin_src" nil t
) (setq top
(point))
1166 (re-search-forward "^[ \t]*#\\+end_src" nil t
) (setq bottom
(point))
1167 (< top initial
) (< initial bottom
)
1168 (progn (goto-char top
) (beginning-of-line 1)
1169 (looking-at org-babel-src-block-regexp
))
1173 (defun org-babel-goto-src-block-head ()
1174 "Go to the beginning of the current code block."
1177 (if head
(goto-char head
) (error "not currently in a code block")))
1178 (org-babel-where-is-src-block-head)))
1181 (defun org-babel-goto-named-src-block (name)
1182 "Go to a named source-code block."
1184 (let ((completion-ignore-case t
))
1185 (list (org-icompleting-read "source-block name: "
1186 (org-babel-src-block-names) nil t
))))
1187 (let ((point (org-babel-find-named-block name
)))
1189 ;; taken from `org-open-at-point'
1190 (progn (goto-char point
) (org-show-context))
1191 (message "source-code block '%s' not found in this buffer" name
))))
1193 (defun org-babel-find-named-block (name)
1194 "Find a named source-code block.
1195 Return the location of the source block identified by source
1196 NAME, or nil if no such block exists. Set match data according to
1197 org-babel-named-src-block-regexp."
1199 (let ((case-fold-search t
)
1200 (regexp (org-babel-named-src-block-regexp-for-name name
)) msg
)
1201 (goto-char (point-min))
1202 (when (or (re-search-forward regexp nil t
)
1203 (re-search-backward regexp nil t
))
1204 (match-beginning 0)))))
1206 (defun org-babel-src-block-names (&optional file
)
1207 "Returns the names of source blocks in FILE or the current buffer."
1209 (when file
(find-file file
)) (goto-char (point-min))
1211 (while (re-search-forward org-babel-src-name-w-name-regexp nil t
)
1212 (setq names
(cons (match-string 4) names
)))
1216 (defun org-babel-goto-named-result (name)
1217 "Go to a named result."
1219 (let ((completion-ignore-case t
))
1220 (list (org-icompleting-read "source-block name: "
1221 (org-babel-result-names) nil t
))))
1222 (let ((point (org-babel-find-named-result name
)))
1224 ;; taken from `org-open-at-point'
1225 (progn (goto-char point
) (org-show-context))
1226 (message "result '%s' not found in this buffer" name
))))
1228 (defun org-babel-find-named-result (name)
1229 "Find a named result.
1230 Return the location of the result named NAME in the current
1231 buffer or nil if no such result exists."
1233 (goto-char (point-min))
1234 (when (re-search-forward
1235 (concat org-babel-result-regexp
1236 "[ \t]" (regexp-quote name
) "[ \t\n\f\v\r]") nil t
)
1237 (beginning-of-line 0) (point))))
1239 (defun org-babel-result-names (&optional file
)
1240 "Returns the names of results in FILE or the current buffer."
1242 (when file
(find-file file
)) (goto-char (point-min))
1244 (while (re-search-forward org-babel-result-w-name-regexp nil t
)
1245 (setq names
(cons (match-string 4) names
)))
1249 (defun org-babel-next-src-block (&optional arg
)
1250 "Jump to the next source block.
1251 With optional prefix argument ARG, jump forward ARG many source blocks."
1253 (when (looking-at org-babel-src-block-regexp
) (forward-char 1))
1255 (re-search-forward org-babel-src-block-regexp nil nil
(or arg
1))
1256 (error (error "No further code blocks")))
1257 (goto-char (match-beginning 0)) (org-show-context))
1260 (defun org-babel-previous-src-block (&optional arg
)
1261 "Jump to the previous source block.
1262 With optional prefix argument ARG, jump backward ARG many source blocks."
1265 (re-search-backward org-babel-src-block-regexp nil nil
(or arg
1))
1266 (error (error "No previous code blocks")))
1267 (goto-char (match-beginning 0)) (org-show-context))
1269 (defvar org-babel-load-languages
)
1272 (defun org-babel-mark-block ()
1273 "Mark current src block"
1279 (looking-at org-babel-src-block-regexp
))
1280 (push-mark (match-end 5) nil t
)
1281 (goto-char (match-beginning 5))))
1282 (org-babel-where-is-src-block-head)))
1284 (defun org-babel-demarcate-block (&optional arg
)
1285 "Wrap or split the code in the region or on the point.
1286 When called from inside of a code block the current block is
1287 split. When called from outside of a code block a new code block
1288 is created. In both cases if the region is demarcated and if the
1289 region is not active then the point is demarcated."
1291 (let ((info (org-babel-get-src-block-info 'light
))
1292 (stars (concat (make-string (or (org-current-level) 1) ?
*) " ")))
1298 (let ((lang (nth 0 info
))
1299 (indent (make-string (nth 5 info
) ?
)))
1300 (when (string-match "^[[:space:]]*$"
1301 (buffer-substring (point-at-bol)
1303 (delete-region (point-at-bol) (point-at-eol)))
1304 (insert (concat (if (looking-at "^") "" "\n")
1305 indent
"#+end_src\n"
1306 (if arg stars indent
) "\n"
1307 indent
"#+begin_src " lang
1308 (if (looking-at "[\n\r]") "" "\n")))))
1309 (move-end-of-line 2))
1310 (sort (if (region-active-p) (list (mark) (point)) (list (point))) #'>))
1311 (let ((start (point))
1312 (lang (org-icompleting-read "Lang: "
1313 (mapcar (lambda (el) (symbol-name (car el
)))
1314 org-babel-load-languages
)))
1315 (body (delete-and-extract-region
1316 (if (region-active-p) (mark) (point)) (point))))
1317 (insert (concat (if (looking-at "^") "" "\n")
1318 (if arg
(concat stars
"\n") "")
1319 "#+begin_src " lang
"\n"
1321 (if (or (= (length body
) 0)
1322 (string-match "[\r\n]$" body
)) "" "\n")
1324 (goto-char start
) (move-end-of-line 1)))))
1326 (defvar org-babel-lob-one-liner-regexp
)
1327 (defun org-babel-where-is-src-block-result (&optional insert info hash indent
)
1328 "Find where the current source block results begin.
1329 Return the point at the beginning of the result of the current
1330 source block. Specifically at the beginning of the results line.
1331 If no result exists for this block then create a results line
1332 following the source block."
1334 (let* ((on-lob-line (save-excursion
1335 (beginning-of-line 1)
1336 (looking-at org-babel-lob-one-liner-regexp
)))
1337 (inlinep (save-excursion
1338 (re-search-backward "[ \f\t\n\r\v]" nil t
)
1339 (when (looking-at org-babel-inline-src-block-regexp
)
1341 (name (if on-lob-line
1342 (nth 0 (org-babel-lob-get-info))
1343 (nth 4 (or info
(org-babel-get-src-block-info)))))
1344 (head (unless on-lob-line
(org-babel-where-is-src-block-head)))
1346 (when head
(goto-char head
))
1348 found
;; was there a result (before we potentially insert one)
1353 ;; - return t if it is found, else return nil
1354 ;; - if it does not need to be rebuilt, then don't set end
1355 ;; - if it does need to be rebuilt then do set end
1356 name
(setq beg
(org-babel-find-named-result name
))
1358 (when (and hash
(not (string= hash
(match-string 3))))
1359 (goto-char beg
) (setq end beg
) ;; beginning of result
1361 (delete-region end
(org-babel-result-end)) nil
)))
1364 ;; - return t if it is found, else return nil
1365 ;; - if it is found, and the hash doesn't match, delete and set end
1366 (or on-lob-line
(re-search-forward "^[ \t]*#\\+end_src" nil t
))
1367 (progn (end-of-line 1)
1368 (if (eobp) (insert "\n") (forward-char 1))
1371 (progn ;; unnamed results line already exists
1372 (re-search-forward "[^ \f\t\n\r\v]" nil t
)
1373 (beginning-of-line 1)
1375 (concat org-babel-result-regexp
"\n")))
1377 ;; must remove and rebuild if hash!=old-hash
1378 (if (and hash
(not (string= hash
(match-string 3))))
1382 end
(org-babel-result-end)))
1383 (setq end nil
)))))))))
1384 (if (and insert end
)
1388 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1393 (org-number-sequence 1 indent
) "")
1396 (when hash
(concat "["hash
"]"))
1398 (when name
(concat " " name
)) "\n"))
1399 (unless beg
(insert "\n") (backward-char))
1400 (beginning-of-line 0)
1401 (if hash
(org-babel-hide-hash))
1405 (defvar org-block-regexp
)
1406 (defun org-babel-read-result ()
1407 "Read the result at `point' into emacs-lisp."
1408 (let ((case-fold-search t
) result-string
)
1410 ((org-at-table-p) (org-babel-read-table))
1411 ((org-at-item-p) (org-babel-read-list))
1412 ((looking-at org-bracket-link-regexp
) (org-babel-read-link))
1413 ((looking-at org-block-regexp
) (org-babel-trim (match-string 4)))
1414 ((looking-at "^[ \t]*: ")
1417 (mapconcat (lambda (line)
1418 (if (and (> (length line
) 1)
1419 (string-match "^[ \t]*: \\(.+\\)" line
))
1420 (match-string 1 line
)
1424 (point) (org-babel-result-end)) "[\r\n]+")
1426 (or (org-babel-number-p result-string
) result-string
))
1427 ((looking-at org-babel-result-regexp
)
1428 (save-excursion (forward-line 1) (org-babel-read-result))))))
1430 (defun org-babel-read-table ()
1431 "Read the table at `point' into emacs-lisp."
1432 (mapcar (lambda (row)
1433 (if (and (symbolp row
) (equal row
'hline
)) row
1434 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
)) row
)))
1435 (org-table-to-lisp)))
1437 (defun org-babel-read-list ()
1438 "Read the list at `point' into emacs-lisp."
1439 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
))
1440 (mapcar #'cadr
(cdr (org-list-parse-list)))))
1442 (defvar org-link-types-re
)
1443 (defun org-babel-read-link ()
1444 "Read the link at `point' into emacs-lisp.
1445 If the path of the link is a file path it is expanded using
1446 `expand-file-name'."
1447 (let* ((case-fold-search t
)
1448 (raw (and (looking-at org-bracket-link-regexp
)
1449 (org-babel-clean-text-properties (match-string 1))))
1450 (type (and (string-match org-link-types-re raw
)
1451 (match-string 1 raw
))))
1453 ((not type
) (expand-file-name raw
))
1454 ((string= type
"file")
1455 (and (string-match "file\\(.*\\):\\(.+\\)" raw
)
1456 (expand-file-name (match-string 2 raw
))))
1459 (defun org-babel-format-result (result &optional sep
)
1460 "Format RESULT for writing to file."
1461 (flet ((echo-res (result)
1462 (if (stringp result
) result
(format "%S" result
))))
1471 (echo-res result
))))
1473 (defun org-babel-insert-result
1474 (result &optional result-params info hash indent lang
)
1475 "Insert RESULT into the current buffer.
1476 By default RESULT is inserted after the end of the
1477 current source block. With optional argument RESULT-PARAMS
1478 controls insertion of results in the org-mode file.
1479 RESULT-PARAMS can take the following values...
1481 replace - (default option) insert results after the source block
1482 replacing any previously inserted results
1484 silent -- no results are inserted
1486 file ---- the results are interpreted as a file path, and are
1487 inserted into the buffer using the Org-mode file syntax
1489 list ---- the results are interpreted as an Org-mode list.
1491 raw ----- results are added directly to the Org-mode file. This
1492 is a good option if you code block will output org-mode
1495 org ----- similar in effect to raw, only the results are wrapped
1496 in an org code block. Similar to the raw option, on
1497 export the results will be interpreted as org-formatted
1498 text, however by wrapping the results in an org code
1499 block they can be replaced upon re-execution of the
1502 html ---- results are added inside of a #+BEGIN_HTML block. This
1503 is a good option if you code block will output html
1506 latex --- results are added inside of a #+BEGIN_LATEX block.
1507 This is a good option if you code block will output
1508 latex formatted text.
1510 code ---- the results are extracted in the syntax of the source
1511 code of the language being evaluated and are added
1512 inside of a #+BEGIN_SRC block with the source-code
1513 language set appropriately. Note this relies on the
1514 optional LANG argument."
1515 (if (stringp result
)
1517 (setq result
(org-babel-clean-text-properties result
))
1518 (when (member "file" result-params
)
1519 (setq result
(org-babel-result-to-file result
))))
1520 (unless (listp result
) (setq result
(format "%S" result
))))
1521 (if (and result-params
(member "silent" result-params
))
1523 (message (replace-regexp-in-string "%" "%%" (format "%S" result
)))
1528 (re-search-backward "[ \f\t\n\r\v]" nil t
)
1529 (when (or (looking-at org-babel-inline-src-block-regexp
)
1530 (looking-at org-babel-inline-lob-one-liner-regexp
))
1531 (goto-char (match-end 0))
1532 (insert (if (listp result
) "\n" " "))
1534 (existing-result (unless inlinep
1535 (org-babel-where-is-src-block-result
1536 t info hash indent
)))
1538 (cdr (assoc :results_switches
(nth 2 info
))))
1540 (when (and (stringp result
) ; ensure results end in a newline
1542 (> (length result
) 0)
1543 (not (or (string-equal (substring result -
1) "\n")
1544 (string-equal (substring result -
1) "\r"))))
1545 (setq result
(concat result
"\n")))
1546 (if (not existing-result
)
1547 (setq beg
(or inlinep
(point)))
1548 (goto-char existing-result
)
1550 (re-search-forward "#" nil t
)
1551 (setq indent
(- (current-column) 1)))
1555 ((member "replace" result-params
)
1556 (delete-region (point) (org-babel-result-end)))
1557 ((member "append" result-params
)
1558 (goto-char (org-babel-result-end)) (setq beg
(point-marker)))
1559 ((member "prepend" result-params
)))) ; already there
1560 (setq results-switches
1561 (if results-switches
(concat " " results-switches
) ""))
1562 ;; insert results based on type
1564 ;; do nothing for an empty result
1565 ((= (length result
) 0))
1566 ;; insert a list if preferred
1567 ((member "list" result-params
)
1570 (org-list-to-generic
1573 (lambda (el) (list nil
(if (stringp el
) el
(format "%S" el
))))
1574 (if (listp result
) result
(list result
))))
1575 '(:splicep nil
:istart
"- " :iend
"\n")))
1577 ;; assume the result is a table if it's not a string
1578 ((not (stringp result
))
1580 (insert (concat (orgtbl-to-orgtbl
1581 (if (or (eq 'hline
(car result
))
1582 (and (listp (car result
))
1583 (listp (cdr (car result
)))))
1584 result
(list result
))
1585 '(:fmt
(lambda (cell) (format "%s" cell
)))) "\n"))
1586 (goto-char beg
) (when (org-at-table-p) (org-table-align)))
1587 ((member "file" result-params
)
1589 (t (goto-char beg
) (insert result
)))
1590 (when (listp result
) (goto-char (org-table-end)))
1591 (setq end
(point-marker))
1592 ;; possibly wrap result
1593 (flet ((wrap (start finish
)
1594 (goto-char beg
) (insert (concat start
"\n"))
1595 (goto-char end
) (insert (concat finish
"\n"))
1596 (setq end
(point-marker))))
1598 ((member "html" result-params
)
1599 (wrap "#+BEGIN_HTML" "#+END_HTML"))
1600 ((member "latex" result-params
)
1601 (wrap "#+BEGIN_LaTeX" "#+END_LaTeX"))
1602 ((member "code" result-params
)
1603 (wrap (format "#+BEGIN_SRC %s%s" (or lang
"none") results-switches
)
1605 ((member "org" result-params
)
1606 (wrap "#+BEGIN_ORG" "#+END_ORG"))
1607 ((member "raw" result-params
)
1608 (goto-char beg
) (if (org-at-table-p) (org-cycle)))
1609 ((member "wrap" result-params
)
1610 (when (and (stringp result
) (not (member "file" result-params
)))
1611 (org-babel-examplize-region beg end results-switches
))
1612 (wrap "#+BEGIN_RESULT" "#+END_RESULT"))
1613 ((and (stringp result
) (not (member "file" result-params
)))
1614 (org-babel-examplize-region beg end results-switches
)
1615 (setq end
(point)))))
1616 ;; possibly indent the results to match the #+results line
1617 (when (and (not inlinep
) (numberp indent
) indent
(> indent
0)
1618 ;; in this case `table-align' does the work for us
1619 (not (and (listp result
)
1620 (member "append" result-params
))))
1621 (indent-rigidly beg end indent
))))
1622 (if (= (length result
) 0)
1623 (if (member "value" result-params
)
1624 (message "Code block returned no value.")
1625 (message "Code block produced no output."))
1626 (message "Code block evaluation complete."))))
1628 (defun org-babel-remove-result (&optional info
)
1629 "Remove the result of the current source block."
1631 (let ((location (org-babel-where-is-src-block-result nil info
)) start
)
1634 (goto-char location
) (setq start
(point)) (forward-line 1)
1635 (delete-region start
(org-babel-result-end))))))
1637 (defun org-babel-result-end ()
1638 "Return the point at the end of the current set of results"
1641 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
1642 ((org-at-item-p) (let* ((struct (org-list-struct))
1643 (prvs (org-list-prevs-alist struct
)))
1644 (org-list-get-list-end (point-at-bol) struct prvs
)))
1646 (let ((case-fold-search t
)
1647 (blocks-re (regexp-opt
1648 (list "latex" "html" "example" "src" "result" "org"))))
1649 (if (looking-at (concat "[ \t]*#\\+begin_" blocks-re
))
1650 (progn (re-search-forward (concat "[ \t]*#\\+end_" blocks-re
) nil t
)
1652 (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
1656 (defun org-babel-result-to-file (result)
1657 "Convert RESULT into an `org-mode' link.
1658 If the `default-directory' is different from the containing
1659 file's directory then expand relative links."
1660 (flet ((cond-exp (file)
1661 (if (and default-directory
1663 (not (string= (expand-file-name default-directory
)
1665 (file-name-directory buffer-file-name
)))))
1666 (expand-file-name file default-directory
)
1668 (if (stringp result
)
1669 (format "[[file:%s]]" (cond-exp result
))
1670 (when (and (listp result
) (= 2 (length result
))
1671 (stringp (car result
)) (stringp (cadr result
)))
1672 (format "[[file:%s][%s]]" (car result
) (cadr result
))))))
1674 (defun org-babel-examplize-region (beg end
&optional results-switches
)
1675 "Comment out region using the inline '==' or ': ' org example quote."
1677 (flet ((chars-between (b e
) (string-match "[\\S]" (buffer-substring b e
))))
1678 (if (or (chars-between (save-excursion (goto-char beg
) (point-at-bol)) beg
)
1679 (chars-between end
(save-excursion (goto-char end
) (point-at-eol))))
1682 (insert (format "=%s=" (prog1 (buffer-substring beg end
)
1683 (delete-region beg end
)))))
1684 (let ((size (count-lines beg end
)))
1686 (cond ((= size
0)) ; do nothing for an empty result
1687 ((< size org-babel-min-lines-for-block-output
)
1690 (beginning-of-line 1) (insert ": ") (forward-line 1)))
1693 (insert (if results-switches
1694 (format "#+begin_example%s\n" results-switches
)
1695 "#+begin_example\n"))
1696 (if (markerp end
) (goto-char end
) (forward-char (- end beg
)))
1697 (insert "#+end_example\n"))))))))
1699 (defun org-babel-update-block-body (new-body)
1700 "Update the body of the current code block to NEW-BODY."
1701 (if (not (org-babel-where-is-src-block-head))
1702 (error "not in source block")
1704 (replace-match (concat (org-babel-trim new-body
) "\n") nil t nil
5))
1705 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
1707 (defun org-babel-merge-params (&rest plists
)
1708 "Combine all parameter association lists in PLISTS.
1709 Later elements of PLISTS override the values of previous elements.
1710 This takes into account some special considerations for certain
1711 parameters when merging lists."
1712 (let ((results-exclusive-groups
1713 '(("file" "list" "vector" "table" "scalar" "raw" "org"
1714 "html" "latex" "code" "pp" "wrap")
1715 ("replace" "silent" "append" "prepend")
1716 ("output" "value")))
1717 (exports-exclusive-groups
1718 '(("code" "results" "both" "none")))
1720 params results exports tangle noweb cache vars shebang comments padline
)
1721 (flet ((e-merge (exclusive-groups &rest result-params
)
1722 ;; maintain exclusivity of mutually exclusive parameters
1724 (mapc (lambda (new-params)
1725 (mapc (lambda (new-param)
1726 (mapc (lambda (exclusive-group)
1727 (when (member new-param exclusive-group
)
1728 (mapcar (lambda (excluded-param)
1735 (setq output
(org-uniquify
1736 (cons new-param output
))))
1746 (let ((name (if (listp (cdr pair
))
1748 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
1750 (intern (match-string 1 (cdr pair
)))))))
1754 (if (member name
(mapcar #'car vars
))
1758 (unless (equal (car p
) name
) p
))
1761 (list (cons name pair
))))
1762 ;; if no name is given, then assign to variables in order
1763 (prog1 (setf (cddr (nth variable-index vars
))
1764 (concat (symbol-name
1765 (car (nth variable-index vars
)))
1767 (incf variable-index
)))))
1769 (setq results
(e-merge results-exclusive-groups
1772 (let ((r (cdr pair
)))
1773 (if (stringp r
) r
(eval r
)))))))
1776 (setq results
(e-merge results-exclusive-groups
1778 (unless (or (member "both" exports
)
1779 (member "none" exports
)
1780 (member "code" exports
))
1781 (setq exports
(e-merge exports-exclusive-groups
1782 exports
'("results"))))
1783 (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))
1785 (setq exports
(e-merge exports-exclusive-groups
1786 exports
(split-string (cdr pair
)))))
1787 (:tangle
;; take the latest -- always overwrite
1788 (setq tangle
(or (list (cdr pair
)) tangle
)))
1790 (setq noweb
(e-merge '(("yes" "no" "tangle")) noweb
1791 (split-string (or (cdr pair
) "")))))
1793 (setq cache
(e-merge '(("yes" "no")) cache
1794 (split-string (or (cdr pair
) "")))))
1796 (setq padline
(e-merge '(("yes" "no")) padline
1797 (split-string (or (cdr pair
) "")))))
1798 (:shebang
;; take the latest -- always overwrite
1799 (setq shebang
(or (list (cdr pair
)) shebang
)))
1801 (setq comments
(e-merge '(("yes" "no")) comments
1802 (split-string (or (cdr pair
) "")))))
1803 (t ;; replace: this covers e.g. :session
1804 (setq params
(cons pair
(assq-delete-all (car pair
) params
))))))
1807 (while vars
(setq params
(cons (cons :var
(cddr (pop vars
))) params
)))
1810 (let ((key (intern (concat ":" (symbol-name hd
))))
1812 (setf params
(cons (cons key
(mapconcat 'identity val
" ")) params
))))
1813 '(results exports tangle noweb padline cache shebang comments
))
1816 (defun org-babel-expand-noweb-references (&optional info parent-buffer
)
1817 "Expand Noweb references in the body of the current source code block.
1819 For example the following reference would be replaced with the
1820 body of the source-code block named 'example-block'.
1824 Note that any text preceding the <<foo>> construct on a line will
1825 be interposed between the lines of the replacement text. So for
1826 example if <<foo>> is placed behind a comment, then the entire
1827 replacement text will also be commented.
1829 This function must be called from inside of the buffer containing
1830 the source-code block which holds BODY.
1832 In addition the following syntax can be used to insert the
1833 results of evaluating the source-code block named 'example-block'.
1837 Any optional arguments can be passed to example-block by placing
1838 the arguments inside the parenthesis following the convention
1839 defined by `org-babel-lob'. For example
1841 <<example-block(a=9)>>
1843 would set the value of argument \"a\" equal to \"9\". Note that
1844 these arguments are not evaluated in the current source-code
1845 block but are passed literally to the \"example-block\"."
1846 (let* ((parent-buffer (or parent-buffer
(current-buffer)))
1847 (info (or info
(org-babel-get-src-block-info)))
1850 (comment (string= "noweb" (cdr (assoc :comments
(nth 2 info
)))))
1851 (new-body "") index source-name evaluate prefix blocks-in-buffer
)
1852 (flet ((nb-add (text) (setq new-body
(concat new-body text
)))
1855 (funcall (intern (concat lang
"-mode")))
1856 (comment-region (point) (progn (insert text
) (point)))
1857 (org-babel-trim (buffer-string))))
1858 (blocks () ;; return the info lists of all blocks in this buffer
1862 (org-babel-map-src-blocks nil
1863 (setq infos
(cons (org-babel-get-src-block-info 'light
)
1867 (insert body
) (goto-char (point-min))
1868 (setq index
(point))
1869 (while (and (re-search-forward "<<\\(.+?\\)>>" nil t
))
1870 (save-match-data (setf source-name
(match-string 1)))
1871 (save-match-data (setq evaluate
(string-match "\(.*\)" source-name
)))
1874 (buffer-substring (match-beginning 0)
1876 (beginning-of-line 1) (point)))))
1877 ;; add interval to new-body (removing noweb reference)
1878 (goto-char (match-beginning 0))
1879 (nb-add (buffer-substring index
(point)))
1880 (goto-char (match-end 0))
1881 (setq index
(point))
1883 (with-current-buffer parent-buffer
1884 (mapconcat ;; interpose PREFIX between every line
1888 (let ((raw (org-babel-ref-resolve source-name
)))
1889 (if (stringp raw
) raw
(format "%S" raw
)))
1891 ;; retrieve from the library of babel
1892 (nth 2 (assoc (intern source-name
)
1893 org-babel-library-of-babel
))
1894 ;; find the expansion of reference in this buffer
1897 (when (string= source-name
1898 (or (cdr (assoc :noweb-ref
(nth 2 i
)))
1900 (let ((body (org-babel-expand-noweb-references i
)))
1902 ((lambda (cs) (concat (c-wrap (car cs
)) "\n"
1903 body
"\n" (c-wrap (cadr cs
))))
1904 (org-babel-tangle-comment-links i
))
1906 (or blocks-in-buffer
1907 (setq blocks-in-buffer
(blocks)))
1909 ;; possibly raise an error if named block doesn't exist
1910 (if (member lang org-babel-noweb-error-langs
)
1912 "<<" source-name
">> "
1913 "could not be resolved (see "
1914 "`org-babel-noweb-error-langs')"))
1916 "[\n\r]") (concat "\n" prefix
)))))
1917 (nb-add (buffer-substring index
(point-max)))))
1920 (defun org-babel-clean-text-properties (text)
1921 "Strip all properties from text return."
1923 (set-text-properties 0 (length text
) nil text
) text
))
1925 (defun org-babel-strip-protective-commas (body)
1926 "Strip protective commas from bodies of source blocks."
1927 (replace-regexp-in-string "^,#" "#" body
))
1929 (defun org-babel-script-escape (str)
1930 "Safely convert tables into elisp lists."
1931 (let (in-single in-double out
)
1932 ((lambda (escaped) (condition-case nil
(org-babel-read escaped
) (error escaped
)))
1933 (if (and (stringp str
)
1935 (string-equal "[" (substring str
0 1))
1936 (string-equal "]" (substring str -
1)))
1946 (91 (if (or in-double in-single
) ; [
1949 (93 (if (or in-double in-single
) ; ]
1952 (44 (if (or in-double in-single
) ; ,
1953 (cons 44 out
) (cons 32 out
)))
1954 (39 (if in-double
; '
1956 (setq in-single
(not in-single
)) (cons 34 out
)))
1957 (34 (if in-single
; "
1958 (append (list 34 32) out
)
1959 (setq in-double
(not in-double
)) (cons 34 out
)))
1960 (t (cons ch out
)))))
1961 (string-to-list str
))
1962 (apply #'string
(reverse out
)))))
1965 (defun org-babel-read (cell &optional inhibit-lisp-eval
)
1966 "Convert the string value of CELL to a number if appropriate.
1967 Otherwise if cell looks like lisp (meaning it starts with a
1968 \"(\", \"'\", \"`\" or a \"[\") then read it as lisp, otherwise
1969 return it unmodified as a string. Optional argument NO-LISP-EVAL
1970 inhibits lisp evaluation for situations in which is it not
1972 (if (and (stringp cell
) (not (equal cell
"")))
1973 (or (org-babel-number-p cell
)
1974 (if (and (not inhibit-lisp-eval
)
1975 (member (substring cell
0 1) '("(" "'" "`" "[")))
1977 (if (string= (substring cell
0 1) "\"")
1979 (progn (set-text-properties 0 (length cell
) nil cell
) cell
))))
1982 (defun org-babel-number-p (string)
1983 "If STRING represents a number return it's value."
1984 (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string
)
1985 (= (length (substring string
(match-beginning 0)
1988 (string-to-number string
)))
1990 (defun org-babel-import-elisp-from-file (file-name &optional separator
)
1991 "Read the results located at FILE-NAME into an elisp table.
1992 If the table is trivial, then return it as a scalar."
1994 (save-window-excursion
1998 (org-table-import file-name separator
)
1999 (delete-file file-name
)
2000 (setq result
(mapcar (lambda (row)
2001 (mapcar #'org-babel-string-read row
))
2002 (org-table-to-lisp))))
2004 (if (null (cdr result
)) ;; if result is trivial vector, then scalarize it
2005 (if (consp (car result
))
2006 (if (null (cdr (car result
)))
2012 (defun org-babel-string-read (cell)
2013 "Strip nested \"s from around strings."
2014 (org-babel-read (or (and (stringp cell
)
2015 (string-match "\\\"\\(.+\\)\\\"" cell
)
2016 (match-string 1 cell
))
2019 (defun org-babel-reverse-string (string)
2020 "Return the reverse of STRING."
2021 (apply 'string
(reverse (string-to-list string
))))
2023 (defun org-babel-chomp (string &optional regexp
)
2024 "Strip trailing spaces and carriage returns from STRING.
2025 Default regexp used is \"[ \f\t\n\r\v]\" but can be
2026 overwritten by specifying a regexp as a second argument."
2027 (let ((regexp (or regexp
"[ \f\t\n\r\v]")))
2028 (while (and (> (length string
) 0)
2029 (string-match regexp
(substring string -
1)))
2030 (setq string
(substring string
0 -
1)))
2033 (defun org-babel-trim (string &optional regexp
)
2034 "Strip leading and trailing spaces and carriage returns from STRING.
2035 Like `org-babel-chomp' only it runs on both the front and back
2037 (org-babel-chomp (org-babel-reverse-string
2038 (org-babel-chomp (org-babel-reverse-string string
) regexp
))
2041 (defvar org-babel-org-babel-call-process-region-original nil
)
2042 (defun org-babel-tramp-handle-call-process-region
2043 (start end program
&optional delete buffer display
&rest args
)
2044 "Use tramp to handle call-process-region.
2045 Fixes a bug in `tramp-handle-call-process-region'."
2046 (if (and (featurep 'tramp
) (file-remote-p default-directory
))
2047 (let ((tmpfile (tramp-compat-make-temp-file "")))
2048 (write-region start end tmpfile
)
2049 (when delete
(delete-region start end
))
2051 ;; (apply 'call-process program tmpfile buffer display args)
2053 (apply 'process-file program tmpfile buffer display args
)
2054 (delete-file tmpfile
)))
2055 ;; org-babel-call-process-region-original is the original emacs
2056 ;; definition. It is in scope from the let binding in
2057 ;; org-babel-execute-src-block
2058 (apply org-babel-call-process-region-original
2059 start end program delete buffer display args
)))
2061 (defun org-babel-local-file-name (file)
2062 "Return the local name component of FILE."
2063 (if (file-remote-p file
)
2065 (with-parsed-tramp-file-name file nil
2069 (defun org-babel-process-file-name (name &optional no-quote-p
)
2070 "Prepare NAME to be used in an external process.
2071 If NAME specifies a remote location, the remote portion of the
2072 name is removed, since in that case the process will be executing
2073 remotely. The file name is then processed by
2074 `expand-file-name'. Unless second argument NO-QUOTE-P is non-nil,
2075 the file name is additionally processed by
2076 `shell-quote-argument'"
2077 ((lambda (f) (if no-quote-p f
(shell-quote-argument f
)))
2078 (expand-file-name (org-babel-local-file-name name
))))
2080 (defvar org-babel-temporary-directory
)
2081 (unless (or noninteractive
(boundp 'org-babel-temporary-directory
))
2082 (defvar org-babel-temporary-directory
2083 (or (and (boundp 'org-babel-temporary-directory
)
2084 (file-exists-p org-babel-temporary-directory
)
2085 org-babel-temporary-directory
)
2086 (make-temp-file "babel-" t
))
2087 "Directory to hold temporary files created to execute code blocks.
2088 Used by `org-babel-temp-file'. This directory will be removed on
2091 (defun org-babel-temp-file (prefix &optional suffix
)
2092 "Create a temporary file in the `org-babel-temporary-directory'.
2093 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2094 value of `temporary-file-directory' temporarily set to the value
2095 of `org-babel-temporary-directory'."
2096 (if (file-remote-p default-directory
)
2098 (concat (file-remote-p default-directory
)
2100 prefix temporary-file-directory
)
2102 (let ((temporary-file-directory
2103 (or (and (boundp 'org-babel-temporary-directory
)
2104 (file-exists-p org-babel-temporary-directory
)
2105 org-babel-temporary-directory
)
2106 temporary-file-directory
)))
2107 (make-temp-file prefix nil suffix
))))
2109 (defun org-babel-remove-temporary-directory ()
2110 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2111 (when (and (boundp 'org-babel-temporary-directory
)
2112 (file-exists-p org-babel-temporary-directory
))
2113 ;; taken from `delete-directory' in files.el
2116 (mapc (lambda (file)
2117 ;; This test is equivalent to
2118 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2119 ;; but more efficient
2120 (if (eq t
(car (file-attributes file
)))
2121 (delete-directory file
)
2122 (delete-file file
)))
2123 ;; We do not want to delete "." and "..".
2124 (directory-files org-babel-temporary-directory
'full
2125 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2126 (delete-directory org-babel-temporary-directory
))
2128 (message "Failed to remove temporary Org-babel directory %s"
2129 (if (boundp 'org-babel-temporary-directory
)
2130 org-babel-temporary-directory
2131 "[directory not defined]"))))))
2133 (add-hook 'kill-emacs-hook
'org-babel-remove-temporary-directory
)
2137 ;; arch-tag: 01a7ebee-06c5-4ee4-a709-e660d28c0af1