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-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]*?\\)[ \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-src-block-info (&optional light
)
163 "Get information on the current source block.
165 Optional argument LIGHT does not resolve remote variable
166 references; a process which could likely result in the execution
167 of other code blocks.
170 (language body header-arguments-alist switches name indent)."
171 (let ((case-fold-search t
) head info name indent
)
173 (if (setq head
(org-babel-where-is-src-block-head))
176 (setq info
(org-babel-parse-src-block-match))
177 (setq indent
(car (last info
)))
178 (setq info
(butlast info
))
179 (while (and (forward-line -
1)
180 (looking-at org-babel-multi-line-header-regexp
))
182 (org-babel-merge-params
184 (org-babel-parse-header-arguments (match-string 1)))))
185 (when (looking-at org-babel-src-name-w-name-regexp
)
186 (setq name
(org-babel-clean-text-properties (match-string 4)))
187 (when (match-string 6)
188 (setf (nth 2 info
) ;; merge functional-syntax vars and header-args
189 (org-babel-merge-params
190 (mapcar (lambda (ref) (cons :var ref
))
191 (org-babel-ref-split-args (match-string 6)))
193 ;; inline source block
194 (when (save-excursion (re-search-backward "[ \f\t\n\r\v]" nil t
)
195 (looking-at org-babel-inline-src-block-regexp
))
196 (setq info
(org-babel-parse-inline-src-block-match))))
197 ;; resolve variable references and add summary parameters
198 (when (and info
(not light
))
199 (setf (nth 2 info
) (org-babel-process-params (nth 2 info
))))
200 (when info
(append info
(list name indent
)))))
202 (defun org-babel-confirm-evaluate (info)
203 "Confirm evaluation of the code block INFO.
204 This behavior can be suppressed by setting the value of
205 `org-confirm-babel-evaluate' to nil, in which case all future
206 interactive code block evaluations will proceed without any
207 confirmation from the user.
209 Note disabling confirmation may result in accidental evaluation
210 of potentially harmful code."
211 (let* ((eval (or (cdr (assoc :eval
(nth 2 info
)))
212 (when (assoc :noeval
(nth 2 info
)) "no")))
213 (query (cond ((equal eval
"query") t
)
214 ((functionp org-confirm-babel-evaluate
)
215 (funcall org-confirm-babel-evaluate
216 (nth 0 info
) (nth 1 info
)))
217 (t org-confirm-babel-evaluate
))))
218 (if (or (equal eval
"never") (equal eval
"no")
221 (format "Evaluate this%scode block%son your system? "
222 (if info
(format " %s " (nth 0 info
)) " ")
224 (format " (%s) " (nth 4 info
)) " "))))))
225 (prog1 nil
(message "Evaluation %s"
226 (if (or (equal eval
"never") (equal eval
"no"))
227 "Disabled" "Aborted")))
231 (defun org-babel-execute-safely-maybe ()
232 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
233 (org-babel-execute-maybe)))
235 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-execute-safely-maybe
)
238 (defun org-babel-execute-maybe ()
240 (or (org-babel-execute-src-block-maybe)
241 (org-babel-lob-execute-maybe)))
243 (defun org-babel-execute-src-block-maybe ()
244 "Conditionally execute a source block.
245 Detect if this is context for a Babel src-block and if so
246 then run `org-babel-execute-src-block'."
248 (let ((info (org-babel-get-src-block-info)))
250 (progn (org-babel-eval-wipe-error-buffer)
251 (org-babel-execute-src-block current-prefix-arg info
) t
) nil
)))
254 (defun org-babel-expand-src-block-maybe ()
255 "Conditionally expand a source block.
256 Detect if this is context for a org-babel src-block and if so
257 then run `org-babel-expand-src-block'."
259 (let ((info (org-babel-get-src-block-info)))
261 (progn (org-babel-expand-src-block current-prefix-arg info
) t
)
265 (defun org-babel-load-in-session-maybe ()
266 "Conditionally load a source block in a session.
267 Detect if this is context for a org-babel src-block and if so
268 then run `org-babel-load-in-session'."
270 (let ((info (org-babel-get-src-block-info)))
272 (progn (org-babel-load-in-session current-prefix-arg info
) t
)
275 (add-hook 'org-metaup-hook
'org-babel-load-in-session-maybe
)
278 (defun org-babel-pop-to-session-maybe ()
279 "Conditionally pop to a session.
280 Detect if this is context for a org-babel src-block and if so
281 then run `org-babel-pop-to-session'."
283 (let ((info (org-babel-get-src-block-info)))
284 (if info
(progn (org-babel-pop-to-session current-prefix-arg info
) t
) nil
)))
286 (add-hook 'org-metadown-hook
'org-babel-pop-to-session-maybe
)
288 (defconst org-babel-header-arg-names
289 '(cache cmdline colnames dir exports file noweb results
290 session tangle var eval noeval comments no-expand shebang
292 "Common header arguments used by org-babel.
293 Note that individual languages may define their own language
294 specific header arguments as well.")
296 (defvar org-babel-default-header-args
297 '((:session .
"none") (:results .
"replace") (:exports .
"code")
298 (:cache .
"no") (:noweb .
"no") (:hlines .
"no") (:tangle .
"no")
299 (:padnewline .
"yes"))
300 "Default arguments to use when evaluating a source block.")
302 (defvar org-babel-default-inline-header-args
303 '((:session .
"none") (:results .
"replace") (:exports .
"results"))
304 "Default arguments to use when evaluating an inline source block.")
306 (defvar org-babel-data-names
'("TBLNAME" "RESNAME" "RESULTS" "DATA"))
308 (defvar org-babel-result-regexp
309 (concat "^[ \t]*#\\+"
310 (regexp-opt org-babel-data-names t
)
311 "\\(\\[\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*")
312 "Regular expression used to match result lines.
313 If the results are associated with a hash key then the hash will
314 be saved in the second match data.")
316 (defvar org-babel-result-w-name-regexp
317 (concat org-babel-result-regexp
318 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
320 (defvar org-babel-min-lines-for-block-output
10
321 "The minimum number of lines for block output.
322 If number of lines of output is equal to or exceeds this
323 value, the output is placed in a #+begin_example...#+end_example
324 block. Otherwise the output is marked as literal by inserting
325 colons at the starts of the lines. This variable only takes
326 effect if the :results output option is in effect.")
328 (defvar org-babel-noweb-error-langs nil
329 "Languages for which Babel will raise literate programming errors.
330 List of languages for which errors should be raised when the
331 source code block satisfying a noweb reference in this language
332 can not be resolved.")
334 (defvar org-babel-hash-show
4
335 "Number of initial characters to show of a hidden results hash.")
337 (defvar org-babel-after-execute-hook nil
338 "Hook for functions to be called after `org-babel-execute-src-block'")
339 (defun org-babel-named-src-block-regexp-for-name (name)
340 "This generates a regexp used to match a src block named NAME."
341 (concat org-babel-src-name-regexp
(regexp-quote name
) "[ \t\n]*"
342 (substring org-babel-src-block-regexp
1)))
345 (defvar call-process-region
)
348 (defun org-babel-execute-src-block (&optional arg info params
)
349 "Execute the current source code block.
350 Insert the results of execution into the buffer. Source code
351 execution and the collection and formatting of results can be
352 controlled through a variety of header arguments.
354 With prefix argument ARG, force re-execution even if a an
355 existing result cached in the buffer would otherwise have been
358 Optionally supply a value for INFO in the form returned by
359 `org-babel-get-src-block-info'.
361 Optionally supply a value for PARAMS which will be merged with
362 the header arguments specified at the front of the source code
365 (let ((info (or info
(org-babel-get-src-block-info))))
366 (when (org-babel-confirm-evaluate info
)
367 (let* ((lang (nth 0 info
))
369 (org-babel-process-params
370 (org-babel-merge-params (nth 2 info
) params
))
372 (cache?
(and (not arg
) (cdr (assoc :cache params
))
373 (string= "yes" (cdr (assoc :cache params
)))))
374 (result-params (cdr (assoc :result-params params
)))
375 (new-hash (when cache?
(org-babel-sha1-hash info
)))
376 (old-hash (when cache?
(org-babel-result-hash info
)))
377 (body (setf (nth 1 info
)
378 (let ((noweb (cdr (assoc :noweb params
))))
380 (or (string= "yes" noweb
)
381 (string= "tangle" noweb
)))
382 (org-babel-expand-noweb-references info
)
384 (dir (cdr (assoc :dir params
)))
386 (or (and dir
(file-name-as-directory dir
)) default-directory
))
387 (org-babel-call-process-region-original
388 (if (boundp 'org-babel-call-process-region-original
)
389 org-babel-call-process-region-original
390 (symbol-function 'call-process-region
)))
391 (indent (car (last info
)))
394 (flet ((call-process-region (&rest args
)
395 (apply 'org-babel-tramp-handle-call-process-region args
)))
396 (flet ((lang-check (f)
397 (let ((f (intern (concat "org-babel-execute:" f
))))
398 (when (fboundp f
) f
))))
400 (or (lang-check lang
)
401 (lang-check (symbol-name
402 (cdr (assoc lang org-src-lang-modes
))))
403 (error "No org-babel-execute function for %s!" lang
))))
404 (if (and (not arg
) new-hash
(equal new-hash old-hash
))
405 (save-excursion ;; return cached result
406 (goto-char (org-babel-where-is-src-block-result nil info
))
407 (end-of-line 1) (forward-char 1)
408 (setq result
(org-babel-read-result))
409 (message (replace-regexp-in-string
410 "%" "%%" (format "%S" result
))) result
)
411 (message "executing %s code block%s..."
413 (if (nth 4 info
) (format " (%s)" (nth 4 info
)) ""))
416 (if (and (eq (cdr (assoc :result-type params
)) 'value
)
417 (or (member "vector" result-params
)
418 (member "table" result-params
))
419 (not (listp result
)))
420 (list (list result
)) result
))
421 (funcall cmd body params
)))
422 ;; if non-empty result and :file then write to :file
423 (when (cdr (assoc :file params
))
425 (with-temp-file (cdr (assoc :file params
))
427 (org-babel-format-result
428 result
(cdr (assoc :sep
(nth 2 info
)))))))
429 (setq result
(cdr (assoc :file params
))))
430 (org-babel-insert-result
431 result result-params info new-hash indent lang
)
432 (run-hooks 'org-babel-after-execute-hook
)
434 (setq call-process-region
'org-babel-call-process-region-original
))))))
436 (defun org-babel-expand-body:generic
(body params
&optional var-lines
)
437 "Expand BODY with PARAMS.
438 Expand a block of code with org-babel according to it's header
439 arguments. This generic implementation of body expansion is
440 called for languages which have not defined their own specific
441 org-babel-expand-body:lang function."
442 (mapconcat #'identity
(append var-lines
(list body
)) "\n"))
445 (defun org-babel-expand-src-block (&optional arg info params
)
446 "Expand the current source code block.
447 Expand according to the source code block's header
448 arguments and pop open the results in a preview buffer."
450 (let* ((info (or info
(org-babel-get-src-block-info)))
452 (params (setf (nth 2 info
)
453 (sort (org-babel-merge-params (nth 2 info
) params
)
454 (lambda (el1 el2
) (string< (symbol-name (car el1
))
455 (symbol-name (car el2
)))))))
456 (body (setf (nth 1 info
)
457 (if (and (cdr (assoc :noweb params
))
458 (string= "yes" (cdr (assoc :noweb params
))))
459 (org-babel-expand-noweb-references info
) (nth 1 info
))))
460 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
461 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
464 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
465 (org-babel-expand-body:generic
466 body params
(and (fboundp assignments-cmd
)
467 (funcall assignments-cmd params
))))))
469 nil expanded
(concat "*Org-Babel Preview " (buffer-name) "[ " lang
" ]*"))))
471 (defun org-babel-edit-distance (s1 s2
)
472 "Return the edit (levenshtein) distance between strings S1 S2."
473 (let* ((l1 (length s1
))
475 (dist (map 'vector
(lambda (_) (make-vector (1+ l2
) nil
))
476 (number-sequence 1 (1+ l1
)))))
477 (flet ((in (i j
) (aref (aref dist i
) j
))
478 (mmin (&rest lst
) (apply #'min
(remove nil lst
))))
479 (setf (aref (aref dist
0) 0) 0)
480 (dolist (i (number-sequence 1 l1
))
481 (dolist (j (number-sequence 1 l2
))
482 (setf (aref (aref dist i
) j
)
483 (+ (if (equal (aref s1
(1- i
)) (aref s2
(1- j
))) 0 1)
484 (mmin (in (1- i
) j
) (in i
(1- j
)) (in (1- i
) (1- j
)))))))
488 (defun org-babel-check-src-block ()
489 "Check for misspelled header arguments in the current code block."
491 ;; TODO: report malformed code block
492 ;; TODO: report incompatible combinations of header arguments
493 (let ((too-close 2)) ;; <- control closeness to report potential match
494 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg
)) 1))
495 (and (org-babel-where-is-src-block-head)
496 (org-babel-parse-header-arguments
497 (org-babel-clean-text-properties
498 (match-string 4))))))
499 (dolist (name (mapcar #'symbol-name org-babel-header-arg-names
))
500 (when (and (not (string= header name
))
501 (<= (org-babel-edit-distance header name
) too-close
))
502 (error "supplied header \"%S\" is suspiciously close to \"%S\""
504 (message "No suspicious header arguments found.")))
507 (defun org-babel-load-in-session (&optional arg info
)
508 "Load the body of the current source-code block.
509 Evaluate the header arguments for the source block before
510 entering the session. After loading the body this pops open the
513 (let* ((info (or info
(org-babel-get-src-block-info)))
515 (params (nth 2 info
))
516 (body (setf (nth 1 info
)
517 (if (and (cdr (assoc :noweb params
))
518 (string= "yes" (cdr (assoc :noweb params
))))
519 (org-babel-expand-noweb-references info
)
521 (session (cdr (assoc :session params
)))
522 (dir (cdr (assoc :dir params
)))
524 (or (and dir
(file-name-as-directory dir
)) default-directory
))
525 (cmd (intern (concat "org-babel-load-session:" lang
))))
526 (unless (fboundp cmd
)
527 (error "No org-babel-load-session function for %s!" lang
))
528 (pop-to-buffer (funcall cmd session body params
))
532 (defun org-babel-initiate-session (&optional arg info
)
533 "Initiate session for current code block.
534 If called with a prefix argument then resolve any variable
535 references in the header arguments and assign these variables in
536 the session. Copy the body of the code block to the kill ring."
538 (let* ((info (or info
(org-babel-get-src-block-info (not arg
))))
541 (params (nth 2 info
))
542 (session (cdr (assoc :session params
)))
543 (dir (cdr (assoc :dir params
)))
545 (or (and dir
(file-name-as-directory dir
)) default-directory
))
546 (init-cmd (intern (format "org-babel-%s-initiate-session" lang
)))
547 (prep-cmd (intern (concat "org-babel-prep-session:" lang
))))
548 (if (and (stringp session
) (string= session
"none"))
549 (error "This block is not using a session!"))
550 (unless (fboundp init-cmd
)
551 (error "No org-babel-initiate-session function for %s!" lang
))
552 (with-temp-buffer (insert (org-babel-trim body
))
553 (copy-region-as-kill (point-min) (point-max)))
555 (unless (fboundp prep-cmd
)
556 (error "No org-babel-prep-session function for %s!" lang
))
557 (funcall prep-cmd session params
))
558 (funcall init-cmd session params
)))
561 (defun org-babel-switch-to-session (&optional arg info
)
562 "Switch to the session of the current code block.
563 Uses `org-babel-initiate-session' to start the session. If called
564 with a prefix argument then this is passed on to
565 `org-babel-initiate-session'."
567 (pop-to-buffer (org-babel-initiate-session arg info
))
570 (defalias 'org-babel-pop-to-session
'org-babel-switch-to-session
)
573 (defun org-babel-switch-to-session-with-code (&optional arg info
)
574 "Switch to code buffer and display session."
578 (let ((other-window-buffer (window-buffer (next-window))))
579 (set-window-buffer (next-window) (current-buffer))
580 (set-window-buffer (selected-window) other-window-buffer
))
582 (let ((info (org-babel-get-src-block-info))
583 (org-src-window-setup 'reorganize-frame
))
585 (org-babel-switch-to-session arg info
))
589 (defmacro org-babel-do-in-edit-buffer
(&rest body
)
590 "Evaluate BODY in edit buffer if there is a code block at point.
591 Return t if a code block was found at point, nil otherwise."
592 `(let ((org-src-window-setup 'switch-invisibly
))
593 (when (and (org-babel-where-is-src-block-head)
594 (org-edit-src-code nil nil nil
))
595 (unwind-protect (progn ,@body
)
596 (if (org-bound-and-true-p org-edit-src-from-org-mode
)
597 (org-edit-src-exit)))
600 (defun org-babel-do-key-sequence-in-edit-buffer (key)
601 "Read key sequence and execute the command in edit buffer.
602 Enter a key sequence to be executed in the language major-mode
603 edit buffer. For example, TAB will alter the contents of the
604 Org-mode code block according to the effect of TAB in the
605 language major-mode buffer. For languages that support
606 interactive sessions, this can be used to send code from the Org
607 buffer to the session for evaluation using the native major-mode
608 evaluation mechanisms."
609 (interactive "kEnter key-sequence to execute in edit buffer: ")
610 (org-babel-do-in-edit-buffer
612 (key-binding (or key
(read-key-sequence nil
))))))
614 (defvar org-bracket-link-regexp
)
616 (defun org-babel-open-src-block-result (&optional re-run
)
617 "If `point' is on a src block then open the results of the
618 source code block, otherwise return nil. With optional prefix
619 argument RE-RUN the source-code block is evaluated even if
620 results already exist."
622 (let ((info (org-babel-get-src-block-info)))
625 ;; go to the results, if there aren't any then run the block
626 (goto-char (or (and (not re-run
) (org-babel-where-is-src-block-result))
627 (progn (org-babel-execute-src-block)
628 (org-babel-where-is-src-block-result))))
630 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
632 (if (looking-at org-bracket-link-regexp
)
635 (let ((r (org-babel-format-result
636 (org-babel-read-result) (cdr (assoc :sep
(nth 2 info
))))))
637 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
638 (delete-region (point-min) (point-max))
643 (defmacro org-babel-map-src-blocks
(file &rest body
)
644 "Evaluate BODY forms on each source-block in FILE.
645 If FILE is nil evaluate BODY forms on source blocks in current
646 buffer. During evaluation of BODY the following local variables
647 are set relative to the currently matched code block.
649 full-block ------- string holding the entirety of the code block
650 beg-block -------- point at the beginning of the code block
651 end-block -------- point at the end of the matched code block
652 lang ------------- string holding the language of the code block
653 beg-lang --------- point at the beginning of the lang
654 end-lang --------- point at the end of the lang
655 switches --------- string holding the switches
656 beg-switches ----- point at the beginning of the switches
657 end-switches ----- point at the end of the switches
658 header-args ------ string holding the header-args
659 beg-header-args -- point at the beginning of the header-args
660 end-header-args -- point at the end of the header-args
661 body ------------- string holding the body of the code block
662 beg-body --------- point at the beginning of the body
663 end-body --------- point at the end of the body"
665 (let ((tempvar (make-symbol "file")))
666 `(let* ((,tempvar
,file
)
667 (visited-p (or (null ,tempvar
)
668 (get-file-buffer (expand-file-name ,tempvar
))))
669 (point (point)) to-be-removed
)
670 (save-window-excursion
671 (when ,tempvar
(find-file ,tempvar
))
672 (setq to-be-removed
(current-buffer))
673 (goto-char (point-min))
674 (while (re-search-forward org-babel-src-block-regexp nil t
)
675 (goto-char (match-beginning 0))
676 (let ((full-block (match-string 0))
677 (beg-block (match-beginning 0))
678 (end-block (match-end 0))
679 (lang (match-string 2))
680 (beg-lang (match-beginning 2))
681 (end-lang (match-end 2))
682 (switches (match-string 3))
683 (beg-switches (match-beginning 3))
684 (end-switches (match-end 3))
685 (header-args (match-string 4))
686 (beg-header-args (match-beginning 4))
687 (end-header-args (match-end 4))
688 (body (match-string 5))
689 (beg-body (match-beginning 5))
690 (end-body (match-end 5)))
692 (goto-char end-block
))))
693 (unless visited-p
(kill-buffer to-be-removed
))
697 (defmacro org-babel-map-inline-src-blocks
(file &rest body
)
698 "Evaluate BODY forms on each inline source-block in FILE.
699 If FILE is nil evaluate BODY forms on source blocks in current
702 (let ((tempvar (make-symbol "file")))
703 `(let* ((,tempvar
,file
)
704 (visited-p (or (null ,tempvar
)
705 (get-file-buffer (expand-file-name ,tempvar
))))
706 (point (point)) to-be-removed
)
707 (save-window-excursion
708 (when ,tempvar
(find-file ,tempvar
))
709 (setq to-be-removed
(current-buffer))
710 (goto-char (point-min))
711 (while (re-search-forward org-babel-inline-src-block-regexp nil t
)
712 (goto-char (match-beginning 1))
713 (save-match-data ,@body
)
714 (goto-char (match-end 0))))
715 (unless visited-p
(kill-buffer to-be-removed
))
719 (defun org-babel-execute-buffer (&optional arg
)
720 "Execute source code blocks in a buffer.
721 Call `org-babel-execute-src-block' on every source block in
724 (org-babel-eval-wipe-error-buffer)
725 (org-save-outline-visibility t
726 (org-babel-map-src-blocks nil
727 (org-babel-execute-src-block arg
))
728 (org-babel-map-inline-src-blocks nil
729 (org-babel-execute-src-block arg
))))
732 (defun org-babel-execute-subtree (&optional arg
)
733 "Execute source code blocks in a subtree.
734 Call `org-babel-execute-src-block' on every source block in
735 the current subtree."
739 (org-narrow-to-subtree)
740 (org-babel-execute-buffer arg
)
744 (defun org-babel-sha1-hash (&optional info
)
745 "Generate an sha1 hash based on the value of info."
747 (let ((print-level nil
)
748 (info (or info
(org-babel-get-src-block-info))))
750 (sort (copy-sequence (nth 2 info
))
751 (lambda (a b
) (string< (car a
) (car b
)))))
753 (dolist (p '("replace" "silent" "append" "prepend"))
754 (setq lst
(remove p lst
)))
757 (let ((v (if (listp (cdr arg
))
760 (when (and v
(not (and (sequencep v
)
764 ((and (listp v
) ; lists are sorted
765 (member (car arg
) '(:result-params
)))
766 (sort (rm v
) #'string
<))
767 ((and (stringp v
) ; strings are sorted
768 (member (car arg
) '(:results
:exports
)))
769 (mapconcat #'identity
(sort (rm (split-string v
))
773 (when (org-called-interactively-p 'interactive
) (message hash
)) hash
)
774 (let ((it (format "%s-%s"
777 (delq nil
(mapcar (lambda (arg)
778 (let ((normalized (norm arg
)))
780 (format "%S" normalized
))))
785 (defun org-babel-result-hash (&optional info
)
786 "Return the in-buffer hash associated with INFO."
787 (org-babel-where-is-src-block-result nil info
)
788 (org-babel-clean-text-properties (match-string 3)))
790 (defun org-babel-hide-hash ()
791 "Hide the hash in the current results line.
792 Only the initial `org-babel-hash-show' characters of the hash
793 will remain visible."
794 (add-to-invisibility-spec '(org-babel-hide-hash . t
))
796 (when (and (re-search-forward org-babel-result-regexp nil t
)
798 (let* ((start (match-beginning 3))
799 (hide-start (+ org-babel-hash-show start
))
801 (hash (match-string 3))
803 (setq ov1
(make-overlay start hide-start
))
804 (setq ov2
(make-overlay hide-start end
))
805 (overlay-put ov2
'invisible
'org-babel-hide-hash
)
806 (overlay-put ov1
'babel-hash hash
)))))
808 (defun org-babel-hide-all-hashes ()
809 "Hide the hash in the current buffer.
810 Only the initial `org-babel-hash-show' characters of each hash
811 will remain visible. This function should be called as part of
812 the `org-mode-hook'."
814 (while (re-search-forward org-babel-result-regexp nil t
)
815 (goto-char (match-beginning 0))
816 (org-babel-hide-hash)
817 (goto-char (match-end 0)))))
818 (add-hook 'org-mode-hook
'org-babel-hide-all-hashes
)
820 (defun org-babel-hash-at-point (&optional point
)
821 "Return the value of the hash at POINT.
822 The hash is also added as the last element of the kill ring.
823 This can be called with C-c C-c."
825 (let ((hash (car (delq nil
(mapcar
826 (lambda (ol) (overlay-get ol
'babel-hash
))
827 (overlays-at (or point
(point))))))))
828 (when hash
(kill-new hash
) (message hash
))))
829 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-hash-at-point
)
831 (defun org-babel-result-hide-spec ()
832 "Hide portions of results lines.
833 Add `org-babel-hide-result' as an invisibility spec for hiding
834 portions of results lines."
835 (add-to-invisibility-spec '(org-babel-hide-result . t
)))
836 (add-hook 'org-mode-hook
'org-babel-result-hide-spec
)
838 (defvar org-babel-hide-result-overlays nil
839 "Overlays hiding results.")
841 (defun org-babel-result-hide-all ()
842 "Fold all results in the current buffer."
844 (org-babel-show-result-all)
846 (while (re-search-forward org-babel-result-regexp nil t
)
847 (save-excursion (goto-char (match-beginning 0))
848 (org-babel-hide-result-toggle-maybe)))))
850 (defun org-babel-show-result-all ()
851 "Unfold all results in the current buffer."
852 (mapc 'delete-overlay org-babel-hide-result-overlays
)
853 (setq org-babel-hide-result-overlays nil
))
856 (defun org-babel-hide-result-toggle-maybe ()
857 "Toggle visibility of result at point."
859 (let ((case-fold-search t
))
861 (beginning-of-line 1)
862 (looking-at org-babel-result-regexp
))
863 (progn (org-babel-hide-result-toggle)
864 t
) ;; to signal that we took action
865 nil
))) ;; to signal that we did not
867 (defun org-babel-hide-result-toggle (&optional force
)
868 "Toggle the visibility of the current result."
872 (if (re-search-forward org-babel-result-regexp nil t
)
873 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
874 (end (progn (goto-char (- (org-babel-result-end) 1)) (point)))
876 (if (memq t
(mapcar (lambda (overlay)
877 (eq (overlay-get overlay
'invisible
)
878 'org-babel-hide-result
))
879 (overlays-at start
)))
880 (if (or (not force
) (eq force
'off
))
882 (when (member ov org-babel-hide-result-overlays
)
883 (setq org-babel-hide-result-overlays
884 (delq ov org-babel-hide-result-overlays
)))
885 (when (eq (overlay-get ov
'invisible
)
886 'org-babel-hide-result
)
887 (delete-overlay ov
)))
888 (overlays-at start
)))
889 (setq ov
(make-overlay start end
))
890 (overlay-put ov
'invisible
'org-babel-hide-result
)
891 ;; make the block accessible to isearch
893 ov
'isearch-open-invisible
895 (when (member ov org-babel-hide-result-overlays
)
896 (setq org-babel-hide-result-overlays
897 (delq ov org-babel-hide-result-overlays
)))
898 (when (eq (overlay-get ov
'invisible
)
899 'org-babel-hide-result
)
900 (delete-overlay ov
))))
901 (push ov org-babel-hide-result-overlays
)))
902 (error "Not looking at a result line"))))
904 ;; org-tab-after-check-for-cycling-hook
905 (add-hook 'org-tab-first-hook
'org-babel-hide-result-toggle-maybe
)
906 ;; Remove overlays when changing major mode
907 (add-hook 'org-mode-hook
908 (lambda () (org-add-hook 'change-major-mode-hook
909 'org-babel-show-result-all
'append
'local
)))
911 (defvar org-file-properties
)
912 (defun org-babel-params-from-properties (&optional lang
)
913 "Retrieve parameters specified as properties.
914 Return an association list of any source block params which
915 may be specified in the properties of the current outline entry."
922 (or (org-entry-get (point) header-arg t
)
923 (org-entry-get (point) (concat ":" header-arg
) t
)))
924 (cons (intern (concat ":" header-arg
))
925 (org-babel-read val
))))
929 org-babel-header-arg-names
931 (setq sym
(intern (concat "org-babel-header-arg-names:" lang
)))
932 (and (boundp sym
) (eval sym
))))))))))
934 (defun org-babel-params-from-buffer ()
935 "Retrieve per-buffer parameters.
936 Return an association list of any source block params which
937 may be specified in the current buffer."
938 (let (local-properties)
943 (goto-char (point-min))
944 (while (re-search-forward
945 (org-make-options-regexp (list "BABEL" "PROPERTIES")) nil t
)
946 (setq local-properties
947 (org-babel-merge-params
949 (org-babel-parse-header-arguments
950 (org-match-string-no-properties 2)))))
951 local-properties
)))))
953 (defvar org-src-preserve-indentation
)
954 (defun org-babel-parse-src-block-match ()
955 "Parse the results from a match of the `org-babel-src-block-regexp'."
956 (let* ((block-indentation (length (match-string 1)))
957 (lang (org-babel-clean-text-properties (match-string 2)))
958 (lang-headers (intern (concat "org-babel-default-header-args:" lang
)))
959 (switches (match-string 3))
960 (body (org-babel-clean-text-properties (match-string 5)))
961 (preserve-indentation (or org-src-preserve-indentation
962 (string-match "-i\\>" switches
))))
964 ;; get block body less properties, protective commas, and indentation
967 (insert (org-babel-strip-protective-commas body
))
968 (unless preserve-indentation
(org-do-remove-indentation))
970 (org-babel-merge-params
971 org-babel-default-header-args
972 (org-babel-params-from-buffer)
973 (org-babel-params-from-properties lang
)
974 (if (boundp lang-headers
) (eval lang-headers
) nil
)
975 (org-babel-parse-header-arguments
976 (org-babel-clean-text-properties (or (match-string 4) ""))))
980 (defun org-babel-parse-inline-src-block-match ()
981 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
982 (let* ((lang (org-babel-clean-text-properties (match-string 2)))
983 (lang-headers (intern (concat "org-babel-default-header-args:" lang
))))
985 (org-babel-strip-protective-commas
986 (org-babel-clean-text-properties (match-string 5)))
987 (org-babel-merge-params
988 org-babel-default-inline-header-args
989 (org-babel-params-from-buffer)
990 (org-babel-params-from-properties lang
)
991 (if (boundp lang-headers
) (eval lang-headers
) nil
)
992 (org-babel-parse-header-arguments
993 (org-babel-clean-text-properties (or (match-string 4) "")))))))
995 (defun org-babel-parse-header-arguments (arg-string)
996 "Parse a string of header arguments returning an alist."
997 (when (> (length arg-string
) 0)
1002 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1004 (cons (intern (match-string 1 arg
))
1005 (org-babel-read (org-babel-chomp (match-string 2 arg
))))
1006 (cons (intern (org-babel-chomp arg
)) nil
)))
1007 (let ((balance 0) (partial nil
) (lst nil
) (last 0))
1008 (mapc (lambda (ch) ; split on [] balanced instances of [ \t]:
1009 (setq balance
(+ balance
1010 (cond ((equal 91 ch
) 1)
1013 (setq partial
(cons ch partial
))
1014 (when (and (= ch
58) (= balance
0)
1015 (or (= last
32) (= last
9)))
1016 (setq lst
(cons (apply #'string
(nreverse (cddr partial
)))
1018 (setq partial
(list ch
)))
1020 (string-to-list arg-string
))
1021 (nreverse (cons (apply #'string
(nreverse partial
)) lst
)))))))
1023 (defun org-babel-process-params (params)
1024 "Expand variables in PARAMS and add summary parameters."
1025 (let* ((vars-and-names (org-babel-disassemble-tables
1026 (mapcar (lambda (el)
1027 (if (consp (cdr el
))
1028 (cdr el
) (org-babel-ref-parse (cdr el
))))
1029 (org-babel-get-header params
:var
))
1030 (cdr (assoc :hlines params
))
1031 (cdr (assoc :colnames params
))
1032 (cdr (assoc :rownames params
))))
1033 (raw-result (or (cdr (assoc :results params
)) ""))
1034 (result-params (append
1035 (split-string (if (stringp raw-result
)
1038 (cdr (assoc :result-params params
)))))
1040 (mapcar (lambda (var) (cons :var var
)) (car vars-and-names
))
1042 (cons :colname-names
(or (cdr (assoc :colname-names params
))
1043 (cadr vars-and-names
)))
1044 (cons :rowname-names
(or (cdr (assoc :rowname-names params
))
1045 (caddr vars-and-names
)))
1046 (cons :result-params result-params
)
1047 (cons :result-type
(cond ((member "output" result-params
) 'output
)
1048 ((member "value" result-params
) 'value
)
1050 (org-babel-get-header params
:var
'other
))))
1052 ;; row and column names
1053 (defun org-babel-del-hlines (table)
1054 "Remove all 'hlines from TABLE."
1055 (remove 'hline table
))
1057 (defun org-babel-get-colnames (table)
1058 "Return the column names of TABLE.
1059 Return a cons cell, the `car' of which contains the TABLE less
1060 colnames, and the `cdr' of which contains a list of the column
1062 (if (equal 'hline
(nth 1 table
))
1063 (cons (cddr table
) (car table
))
1064 (cons (cdr table
) (car table
))))
1066 (defun org-babel-get-rownames (table)
1067 "Return the row names of TABLE.
1068 Return a cons cell, the `car' of which contains the TABLE less
1069 colnames, and the `cdr' of which contains a list of the column
1070 names. Note: this function removes any hlines in TABLE."
1071 (flet ((trans (table) (apply #'mapcar
* #'list table
)))
1072 (let* ((width (apply 'max
1073 (mapcar (lambda (el) (if (listp el
) (length el
) 0)) table
)))
1074 (table (trans (mapcar (lambda (row)
1075 (if (not (equal row
'hline
))
1079 (setq row
(cons 'hline row
)))
1082 (cons (mapcar (lambda (row) (if (equal (car row
) 'hline
) 'hline row
))
1083 (trans (cdr table
)))
1084 (remove 'hline
(car table
))))))
1086 (defun org-babel-put-colnames (table colnames
)
1087 "Add COLNAMES to TABLE if they exist."
1088 (if colnames
(apply 'list colnames
'hline table
) table
))
1090 (defun org-babel-put-rownames (table rownames
)
1091 "Add ROWNAMES to TABLE if they exist."
1093 (mapcar (lambda (row)
1095 (cons (or (pop rownames
) "") row
)
1099 (defun org-babel-pick-name (names selector
)
1100 "Select one out of an alist of row or column names.
1101 SELECTOR can be either a list of names in which case those names
1102 will be returned directly, or an index into the list NAMES in
1103 which case the indexed names will be return."
1104 (if (listp selector
)
1107 (if (and selector
(symbolp selector
) (not (equal t selector
)))
1108 (cdr (assoc selector names
))
1109 (if (integerp selector
)
1110 (nth (- selector
1) names
)
1111 (cdr (car (last names
))))))))
1113 (defun org-babel-disassemble-tables (vars hlines colnames rownames
)
1114 "Parse tables for further processing.
1115 Process the variables in VARS according to the HLINES,
1116 ROWNAMES and COLNAMES header arguments. Return a list consisting
1117 of the vars, cnames and rnames."
1118 (let (cnames rnames
)
1122 (when (listp (cdr var
))
1123 (when (and (not (equal colnames
"no"))
1124 (or colnames
(and (equal (nth 1 (cdr var
)) 'hline
)
1125 (not (member 'hline
(cddr (cdr var
)))))))
1126 (let ((both (org-babel-get-colnames (cdr var
))))
1127 (setq cnames
(cons (cons (car var
) (cdr both
))
1129 (setq var
(cons (car var
) (car both
)))))
1130 (when (and rownames
(not (equal rownames
"no")))
1131 (let ((both (org-babel-get-rownames (cdr var
))))
1132 (setq rnames
(cons (cons (car var
) (cdr both
))
1134 (setq var
(cons (car var
) (car both
)))))
1135 (when (and hlines
(not (equal hlines
"yes")))
1136 (setq var
(cons (car var
) (org-babel-del-hlines (cdr var
))))))
1141 (defun org-babel-reassemble-table (table colnames rownames
)
1142 "Add column and row names to a table.
1143 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1144 to the table for reinsertion to org-mode."
1147 (if (and colnames
(listp (car table
)) (= (length (car table
))
1149 (org-babel-put-colnames table colnames
) table
))
1150 (if (and rownames
(= (length table
) (length rownames
)))
1151 (org-babel-put-rownames table rownames
) table
))
1154 (defun org-babel-where-is-src-block-head ()
1155 "Find where the current source block begins.
1156 Return the point at the beginning of the current source
1157 block. Specifically at the beginning of the #+BEGIN_SRC line.
1158 If the point is not on a source block then return nil."
1159 (let ((initial (point)) top bottom
)
1161 (save-excursion ;; on a source name line or a #+header line
1162 (beginning-of-line 1)
1163 (and (or (looking-at org-babel-src-name-regexp
)
1164 (looking-at org-babel-multi-line-header-regexp
))
1166 (while (and (forward-line 1)
1167 (looking-at org-babel-multi-line-header-regexp
)))
1168 (looking-at org-babel-src-block-regexp
))
1170 (save-excursion ;; on a #+begin_src line
1171 (beginning-of-line 1)
1172 (and (looking-at org-babel-src-block-regexp
)
1174 (save-excursion ;; inside a src block
1176 (re-search-backward "^[ \t]*#\\+begin_src" nil t
) (setq top
(point))
1177 (re-search-forward "^[ \t]*#\\+end_src" nil t
) (setq bottom
(point))
1178 (< top initial
) (< initial bottom
)
1179 (progn (goto-char top
) (beginning-of-line 1)
1180 (looking-at org-babel-src-block-regexp
))
1184 (defun org-babel-goto-src-block-head ()
1185 "Go to the beginning of the current code block."
1188 (if head
(goto-char head
) (error "not currently in a code block")))
1189 (org-babel-where-is-src-block-head)))
1192 (defun org-babel-goto-named-src-block (name)
1193 "Go to a named source-code block."
1195 (let ((completion-ignore-case t
))
1196 (list (org-icompleting-read "source-block name: "
1197 (org-babel-src-block-names) nil t
))))
1198 (let ((point (org-babel-find-named-block name
)))
1200 ;; taken from `org-open-at-point'
1201 (progn (goto-char point
) (org-show-context))
1202 (message "source-code block '%s' not found in this buffer" name
))))
1204 (defun org-babel-find-named-block (name)
1205 "Find a named source-code block.
1206 Return the location of the source block identified by source
1207 NAME, or nil if no such block exists. Set match data according to
1208 org-babel-named-src-block-regexp."
1210 (let ((case-fold-search t
)
1211 (regexp (org-babel-named-src-block-regexp-for-name name
)) msg
)
1212 (goto-char (point-min))
1213 (when (or (re-search-forward regexp nil t
)
1214 (re-search-backward regexp nil t
))
1215 (match-beginning 0)))))
1217 (defun org-babel-src-block-names (&optional file
)
1218 "Returns the names of source blocks in FILE or the current buffer."
1220 (when file
(find-file file
)) (goto-char (point-min))
1222 (while (re-search-forward org-babel-src-name-w-name-regexp nil t
)
1223 (setq names
(cons (match-string 4) names
)))
1227 (defun org-babel-goto-named-result (name)
1228 "Go to a named result."
1230 (let ((completion-ignore-case t
))
1231 (list (org-icompleting-read "source-block name: "
1232 (org-babel-result-names) nil t
))))
1233 (let ((point (org-babel-find-named-result name
)))
1235 ;; taken from `org-open-at-point'
1236 (progn (goto-char point
) (org-show-context))
1237 (message "result '%s' not found in this buffer" name
))))
1239 (defun org-babel-find-named-result (name)
1240 "Find a named result.
1241 Return the location of the result named NAME in the current
1242 buffer or nil if no such result exists."
1244 (goto-char (point-min))
1245 (when (re-search-forward
1246 (concat org-babel-result-regexp
1247 "[ \t]" (regexp-quote name
) "[ \t\n\f\v\r]") nil t
)
1248 (beginning-of-line 0) (point))))
1250 (defun org-babel-result-names (&optional file
)
1251 "Returns the names of results in FILE or the current buffer."
1253 (when file
(find-file file
)) (goto-char (point-min))
1255 (while (re-search-forward org-babel-result-w-name-regexp nil t
)
1256 (setq names
(cons (match-string 4) names
)))
1260 (defun org-babel-next-src-block (&optional arg
)
1261 "Jump to the next source block.
1262 With optional prefix argument ARG, jump forward ARG many source blocks."
1264 (when (looking-at org-babel-src-block-regexp
) (forward-char 1))
1266 (re-search-forward org-babel-src-block-regexp nil nil
(or arg
1))
1267 (error (error "No further code blocks")))
1268 (goto-char (match-beginning 0)) (org-show-context))
1271 (defun org-babel-previous-src-block (&optional arg
)
1272 "Jump to the previous source block.
1273 With optional prefix argument ARG, jump backward ARG many source blocks."
1276 (re-search-backward org-babel-src-block-regexp nil nil
(or arg
1))
1277 (error (error "No previous code blocks")))
1278 (goto-char (match-beginning 0)) (org-show-context))
1280 (defvar org-babel-load-languages
)
1283 (defun org-babel-mark-block ()
1284 "Mark current src block"
1290 (looking-at org-babel-src-block-regexp
))
1291 (push-mark (match-end 5) nil t
)
1292 (goto-char (match-beginning 5))))
1293 (org-babel-where-is-src-block-head)))
1295 (defun org-babel-demarcate-block (&optional arg
)
1296 "Wrap or split the code in the region or on the point.
1297 When called from inside of a code block the current block is
1298 split. When called from outside of a code block a new code block
1299 is created. In both cases if the region is demarcated and if the
1300 region is not active then the point is demarcated."
1302 (let ((info (org-babel-get-src-block-info 'light
))
1303 (stars (concat (make-string (or (org-current-level) 1) ?
*) " ")))
1309 (let ((lang (nth 0 info
))
1310 (indent (make-string (nth 5 info
) ?
)))
1311 (when (string-match "^[[:space:]]*$"
1312 (buffer-substring (point-at-bol)
1314 (delete-region (point-at-bol) (point-at-eol)))
1315 (insert (concat (if (looking-at "^") "" "\n")
1316 indent
"#+end_src\n"
1317 (if arg stars indent
) "\n"
1318 indent
"#+begin_src " lang
1319 (if (looking-at "[\n\r]") "" "\n")))))
1320 (move-end-of-line 2))
1321 (sort (if (region-active-p) (list (mark) (point)) (list (point))) #'>))
1322 (let ((start (point))
1323 (lang (org-icompleting-read "Lang: "
1324 (mapcar (lambda (el) (symbol-name (car el
)))
1325 org-babel-load-languages
)))
1326 (body (delete-and-extract-region
1327 (if (region-active-p) (mark) (point)) (point))))
1328 (insert (concat (if (looking-at "^") "" "\n")
1329 (if arg
(concat stars
"\n") "")
1330 "#+begin_src " lang
"\n"
1332 (if (or (= (length body
) 0)
1333 (string-match "[\r\n]$" body
)) "" "\n")
1335 (goto-char start
) (move-end-of-line 1)))))
1337 (defvar org-babel-lob-one-liner-regexp
)
1338 (defvar org-babel-inline-lob-one-liner-regexp
)
1339 (defun org-babel-where-is-src-block-result (&optional insert info hash indent
)
1340 "Find where the current source block results begin.
1341 Return the point at the beginning of the result of the current
1342 source block. Specifically at the beginning of the results line.
1343 If no result exists for this block then create a results line
1344 following the source block."
1346 (let* ((on-lob-line (save-excursion
1347 (beginning-of-line 1)
1348 (looking-at org-babel-lob-one-liner-regexp
)))
1349 (inlinep (save-excursion
1350 (re-search-backward "[ \f\t\n\r\v]" nil t
)
1351 (when (looking-at org-babel-inline-src-block-regexp
)
1353 (name (if on-lob-line
1354 (nth 0 (org-babel-lob-get-info))
1355 (nth 4 (or info
(org-babel-get-src-block-info)))))
1356 (head (unless on-lob-line
(org-babel-where-is-src-block-head)))
1358 (when head
(goto-char head
))
1360 found
;; was there a result (before we potentially insert one)
1365 ;; - return t if it is found, else return nil
1366 ;; - if it does not need to be rebuilt, then don't set end
1367 ;; - if it does need to be rebuilt then do set end
1368 name
(setq beg
(org-babel-find-named-result name
))
1370 (when (and hash
(not (string= hash
(match-string 3))))
1371 (goto-char beg
) (setq end beg
) ;; beginning of result
1373 (delete-region end
(org-babel-result-end)) nil
)))
1376 ;; - return t if it is found, else return nil
1377 ;; - if it is found, and the hash doesn't match, delete and set end
1378 (or on-lob-line
(re-search-forward "^[ \t]*#\\+end_src" nil t
))
1379 (progn (end-of-line 1)
1380 (if (eobp) (insert "\n") (forward-char 1))
1383 (progn ;; unnamed results line already exists
1384 (re-search-forward "[^ \f\t\n\r\v]" nil t
)
1385 (beginning-of-line 1)
1387 (concat org-babel-result-regexp
"\n")))
1389 ;; must remove and rebuild if hash!=old-hash
1390 (if (and hash
(not (string= hash
(match-string 3))))
1394 end
(org-babel-result-end)))
1395 (setq end nil
)))))))))
1396 (if (and insert end
)
1400 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1405 (org-number-sequence 1 indent
) "")
1408 (when hash
(concat "["hash
"]"))
1410 (when name
(concat " " name
)) "\n"))
1411 (unless beg
(insert "\n") (backward-char))
1412 (beginning-of-line 0)
1413 (if hash
(org-babel-hide-hash))
1417 (defvar org-block-regexp
)
1418 (defun org-babel-read-result ()
1419 "Read the result at `point' into emacs-lisp."
1420 (let ((case-fold-search t
) result-string
)
1422 ((org-at-table-p) (org-babel-read-table))
1423 ((org-at-item-p) (org-babel-read-list))
1424 ((looking-at org-bracket-link-regexp
) (org-babel-read-link))
1425 ((looking-at org-block-regexp
) (org-babel-trim (match-string 4)))
1426 ((looking-at "^[ \t]*: ")
1429 (mapconcat (lambda (line)
1430 (if (and (> (length line
) 1)
1431 (string-match "^[ \t]*: \\(.+\\)" line
))
1432 (match-string 1 line
)
1436 (point) (org-babel-result-end)) "[\r\n]+")
1438 (or (org-babel-number-p result-string
) result-string
))
1439 ((looking-at org-babel-result-regexp
)
1440 (save-excursion (forward-line 1) (org-babel-read-result))))))
1442 (defun org-babel-read-table ()
1443 "Read the table at `point' into emacs-lisp."
1444 (mapcar (lambda (row)
1445 (if (and (symbolp row
) (equal row
'hline
)) row
1446 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
)) row
)))
1447 (org-table-to-lisp)))
1449 (defun org-babel-read-list ()
1450 "Read the list at `point' into emacs-lisp."
1451 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
))
1452 (mapcar #'cadr
(cdr (org-list-parse-list)))))
1454 (defvar org-link-types-re
)
1455 (defun org-babel-read-link ()
1456 "Read the link at `point' into emacs-lisp.
1457 If the path of the link is a file path it is expanded using
1458 `expand-file-name'."
1459 (let* ((case-fold-search t
)
1460 (raw (and (looking-at org-bracket-link-regexp
)
1461 (org-babel-clean-text-properties (match-string 1))))
1462 (type (and (string-match org-link-types-re raw
)
1463 (match-string 1 raw
))))
1465 ((not type
) (expand-file-name raw
))
1466 ((string= type
"file")
1467 (and (string-match "file\\(.*\\):\\(.+\\)" raw
)
1468 (expand-file-name (match-string 2 raw
))))
1471 (defun org-babel-format-result (result &optional sep
)
1472 "Format RESULT for writing to file."
1473 (flet ((echo-res (result)
1474 (if (stringp result
) result
(format "%S" result
))))
1483 (echo-res result
))))
1485 (defun org-babel-insert-result
1486 (result &optional result-params info hash indent lang
)
1487 "Insert RESULT into the current buffer.
1488 By default RESULT is inserted after the end of the
1489 current source block. With optional argument RESULT-PARAMS
1490 controls insertion of results in the org-mode file.
1491 RESULT-PARAMS can take the following values...
1493 replace - (default option) insert results after the source block
1494 replacing any previously inserted results
1496 silent -- no results are inserted
1498 file ---- the results are interpreted as a file path, and are
1499 inserted into the buffer using the Org-mode file syntax
1501 list ---- the results are interpreted as an Org-mode list.
1503 raw ----- results are added directly to the Org-mode file. This
1504 is a good option if you code block will output org-mode
1507 org ----- similar in effect to raw, only the results are wrapped
1508 in an org code block. Similar to the raw option, on
1509 export the results will be interpreted as org-formatted
1510 text, however by wrapping the results in an org code
1511 block they can be replaced upon re-execution of the
1514 html ---- results are added inside of a #+BEGIN_HTML block. This
1515 is a good option if you code block will output html
1518 latex --- results are added inside of a #+BEGIN_LATEX block.
1519 This is a good option if you code block will output
1520 latex formatted text.
1522 code ---- the results are extracted in the syntax of the source
1523 code of the language being evaluated and are added
1524 inside of a #+BEGIN_SRC block with the source-code
1525 language set appropriately. Note this relies on the
1526 optional LANG argument."
1527 (if (stringp result
)
1529 (setq result
(org-babel-clean-text-properties result
))
1530 (when (member "file" result-params
)
1531 (setq result
(org-babel-result-to-file result
))))
1532 (unless (listp result
) (setq result
(format "%S" result
))))
1533 (if (and result-params
(member "silent" result-params
))
1535 (message (replace-regexp-in-string "%" "%%" (format "%S" result
)))
1540 (or (= (point) (point-at-bol))
1541 (re-search-backward "[ \f\t\n\r\v]" nil t
))
1542 (when (or (looking-at org-babel-inline-src-block-regexp
)
1543 (looking-at org-babel-inline-lob-one-liner-regexp
))
1544 (goto-char (match-end 0))
1545 (insert (if (listp result
) "\n" " "))
1547 (existing-result (unless inlinep
1548 (org-babel-where-is-src-block-result
1549 t info hash indent
)))
1551 (cdr (assoc :results_switches
(nth 2 info
))))
1553 (when (and (stringp result
) ; ensure results end in a newline
1555 (> (length result
) 0)
1556 (not (or (string-equal (substring result -
1) "\n")
1557 (string-equal (substring result -
1) "\r"))))
1558 (setq result
(concat result
"\n")))
1559 (if (not existing-result
)
1560 (setq beg
(or inlinep
(point)))
1561 (goto-char existing-result
)
1563 (re-search-forward "#" nil t
)
1564 (setq indent
(- (current-column) 1)))
1568 ((member "replace" result-params
)
1569 (delete-region (point) (org-babel-result-end)))
1570 ((member "append" result-params
)
1571 (goto-char (org-babel-result-end)) (setq beg
(point-marker)))
1572 ((member "prepend" result-params
)))) ; already there
1573 (setq results-switches
1574 (if results-switches
(concat " " results-switches
) ""))
1575 ;; insert results based on type
1577 ;; do nothing for an empty result
1578 ((= (length result
) 0))
1579 ;; insert a list if preferred
1580 ((member "list" result-params
)
1583 (org-list-to-generic
1586 (lambda (el) (list nil
(if (stringp el
) el
(format "%S" el
))))
1587 (if (listp result
) result
(list result
))))
1588 '(:splicep nil
:istart
"- " :iend
"\n")))
1590 ;; assume the result is a table if it's not a string
1591 ((not (stringp result
))
1593 (insert (concat (orgtbl-to-orgtbl
1594 (if (or (eq 'hline
(car result
))
1595 (and (listp (car result
))
1596 (listp (cdr (car result
)))))
1597 result
(list result
))
1598 '(:fmt
(lambda (cell) (format "%s" cell
)))) "\n"))
1599 (goto-char beg
) (when (org-at-table-p) (org-table-align)))
1600 ((member "file" result-params
)
1602 (t (goto-char beg
) (insert result
)))
1603 (when (listp result
) (goto-char (org-table-end)))
1604 (setq end
(point-marker))
1605 ;; possibly wrap result
1606 (flet ((wrap (start finish
)
1607 (goto-char beg
) (insert (concat start
"\n"))
1608 (goto-char end
) (insert (concat finish
"\n"))
1609 (setq end
(point-marker))))
1611 ((member "html" result-params
)
1612 (wrap "#+BEGIN_HTML" "#+END_HTML"))
1613 ((member "latex" result-params
)
1614 (wrap "#+BEGIN_LaTeX" "#+END_LaTeX"))
1615 ((member "code" result-params
)
1616 (wrap (format "#+BEGIN_SRC %s%s" (or lang
"none") results-switches
)
1618 ((member "org" result-params
)
1619 (wrap "#+BEGIN_ORG" "#+END_ORG"))
1620 ((member "raw" result-params
)
1621 (goto-char beg
) (if (org-at-table-p) (org-cycle)))
1622 ((member "wrap" result-params
)
1623 (when (and (stringp result
) (not (member "file" result-params
)))
1624 (org-babel-examplize-region beg end results-switches
))
1625 (wrap "#+BEGIN_RESULT" "#+END_RESULT"))
1626 ((and (stringp result
) (not (member "file" result-params
)))
1627 (org-babel-examplize-region beg end results-switches
)
1628 (setq end
(point)))))
1629 ;; possibly indent the results to match the #+results line
1630 (when (and (not inlinep
) (numberp indent
) indent
(> indent
0)
1631 ;; in this case `table-align' does the work for us
1632 (not (and (listp result
)
1633 (member "append" result-params
))))
1634 (indent-rigidly beg end indent
))))
1635 (if (= (length result
) 0)
1636 (if (member "value" result-params
)
1637 (message "Code block returned no value.")
1638 (message "Code block produced no output."))
1639 (message "Code block evaluation complete."))))
1641 (defun org-babel-remove-result (&optional info
)
1642 "Remove the result of the current source block."
1644 (let ((location (org-babel-where-is-src-block-result nil info
)) start
)
1647 (goto-char location
) (setq start
(point)) (forward-line 1)
1648 (delete-region start
(org-babel-result-end))))))
1650 (defun org-babel-result-end ()
1651 "Return the point at the end of the current set of results"
1654 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
1655 ((org-at-item-p) (let* ((struct (org-list-struct))
1656 (prvs (org-list-prevs-alist struct
)))
1657 (org-list-get-list-end (point-at-bol) struct prvs
)))
1659 (let ((case-fold-search t
)
1660 (blocks-re (regexp-opt
1661 (list "latex" "html" "example" "src" "result" "org"))))
1662 (if (looking-at (concat "[ \t]*#\\+begin_" blocks-re
))
1663 (progn (re-search-forward (concat "[ \t]*#\\+end_" blocks-re
) nil t
)
1665 (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
1669 (defun org-babel-result-to-file (result)
1670 "Convert RESULT into an `org-mode' link.
1671 If the `default-directory' is different from the containing
1672 file's directory then expand relative links."
1673 (flet ((cond-exp (file)
1674 (if (and default-directory
1676 (not (string= (expand-file-name default-directory
)
1678 (file-name-directory buffer-file-name
)))))
1679 (expand-file-name file default-directory
)
1681 (if (stringp result
)
1682 (format "[[file:%s]]" (cond-exp result
))
1683 (when (and (listp result
) (= 2 (length result
))
1684 (stringp (car result
)) (stringp (cadr result
)))
1685 (format "[[file:%s][%s]]" (car result
) (cadr result
))))))
1687 (defun org-babel-examplize-region (beg end
&optional results-switches
)
1688 "Comment out region using the inline '==' or ': ' org example quote."
1690 (flet ((chars-between (b e
) (string-match "[\\S]" (buffer-substring b e
))))
1691 (if (or (chars-between (save-excursion (goto-char beg
) (point-at-bol)) beg
)
1692 (chars-between end
(save-excursion (goto-char end
) (point-at-eol))))
1695 (insert (format "=%s=" (prog1 (buffer-substring beg end
)
1696 (delete-region beg end
)))))
1697 (let ((size (count-lines beg end
)))
1699 (cond ((= size
0)) ; do nothing for an empty result
1700 ((< size org-babel-min-lines-for-block-output
)
1703 (beginning-of-line 1) (insert ": ") (forward-line 1)))
1706 (insert (if results-switches
1707 (format "#+begin_example%s\n" results-switches
)
1708 "#+begin_example\n"))
1709 (if (markerp end
) (goto-char end
) (forward-char (- end beg
)))
1710 (insert "#+end_example\n"))))))))
1712 (defun org-babel-update-block-body (new-body)
1713 "Update the body of the current code block to NEW-BODY."
1714 (if (not (org-babel-where-is-src-block-head))
1715 (error "not in source block")
1717 (replace-match (concat (org-babel-trim new-body
) "\n") nil t nil
5))
1718 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
1720 (defun org-babel-merge-params (&rest plists
)
1721 "Combine all parameter association lists in PLISTS.
1722 Later elements of PLISTS override the values of previous elements.
1723 This takes into account some special considerations for certain
1724 parameters when merging lists."
1725 (let ((results-exclusive-groups
1726 '(("file" "list" "vector" "table" "scalar" "raw" "org"
1727 "html" "latex" "code" "pp" "wrap")
1728 ("replace" "silent" "append" "prepend")
1729 ("output" "value")))
1730 (exports-exclusive-groups
1731 '(("code" "results" "both" "none")))
1733 params results exports tangle noweb cache vars shebang comments padline
)
1734 (flet ((e-merge (exclusive-groups &rest result-params
)
1735 ;; maintain exclusivity of mutually exclusive parameters
1737 (mapc (lambda (new-params)
1738 (mapc (lambda (new-param)
1739 (mapc (lambda (exclusive-group)
1740 (when (member new-param exclusive-group
)
1741 (mapcar (lambda (excluded-param)
1748 (setq output
(org-uniquify
1749 (cons new-param output
))))
1759 (let ((name (if (listp (cdr pair
))
1761 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
1763 (intern (match-string 1 (cdr pair
)))))))
1767 (if (member name
(mapcar #'car vars
))
1771 (unless (equal (car p
) name
) p
))
1774 (list (cons name pair
))))
1775 ;; if no name is given, then assign to variables in order
1776 (prog1 (setf (cddr (nth variable-index vars
))
1777 (concat (symbol-name
1778 (car (nth variable-index vars
)))
1780 (incf variable-index
)))))
1782 (setq results
(e-merge results-exclusive-groups
1785 (let ((r (cdr pair
)))
1786 (if (stringp r
) r
(eval r
)))))))
1789 (setq results
(e-merge results-exclusive-groups
1791 (unless (or (member "both" exports
)
1792 (member "none" exports
)
1793 (member "code" exports
))
1794 (setq exports
(e-merge exports-exclusive-groups
1795 exports
'("results"))))
1796 (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))
1798 (setq exports
(e-merge exports-exclusive-groups
1799 exports
(split-string (cdr pair
)))))
1800 (:tangle
;; take the latest -- always overwrite
1801 (setq tangle
(or (list (cdr pair
)) tangle
)))
1803 (setq noweb
(e-merge '(("yes" "no" "tangle")) noweb
1804 (split-string (or (cdr pair
) "")))))
1806 (setq cache
(e-merge '(("yes" "no")) cache
1807 (split-string (or (cdr pair
) "")))))
1809 (setq padline
(e-merge '(("yes" "no")) padline
1810 (split-string (or (cdr pair
) "")))))
1811 (:shebang
;; take the latest -- always overwrite
1812 (setq shebang
(or (list (cdr pair
)) shebang
)))
1814 (setq comments
(e-merge '(("yes" "no")) comments
1815 (split-string (or (cdr pair
) "")))))
1816 (t ;; replace: this covers e.g. :session
1817 (setq params
(cons pair
(assq-delete-all (car pair
) params
))))))
1820 (setq vars
(reverse vars
))
1821 (while vars
(setq params
(cons (cons :var
(cddr (pop vars
))) params
)))
1824 (let ((key (intern (concat ":" (symbol-name hd
))))
1826 (setf params
(cons (cons key
(mapconcat 'identity val
" ")) params
))))
1827 '(results exports tangle noweb padline cache shebang comments
))
1830 (defun org-babel-expand-noweb-references (&optional info parent-buffer
)
1831 "Expand Noweb references in the body of the current source code block.
1833 For example the following reference would be replaced with the
1834 body of the source-code block named 'example-block'.
1838 Note that any text preceding the <<foo>> construct on a line will
1839 be interposed between the lines of the replacement text. So for
1840 example if <<foo>> is placed behind a comment, then the entire
1841 replacement text will also be commented.
1843 This function must be called from inside of the buffer containing
1844 the source-code block which holds BODY.
1846 In addition the following syntax can be used to insert the
1847 results of evaluating the source-code block named 'example-block'.
1851 Any optional arguments can be passed to example-block by placing
1852 the arguments inside the parenthesis following the convention
1853 defined by `org-babel-lob'. For example
1855 <<example-block(a=9)>>
1857 would set the value of argument \"a\" equal to \"9\". Note that
1858 these arguments are not evaluated in the current source-code
1859 block but are passed literally to the \"example-block\"."
1860 (let* ((parent-buffer (or parent-buffer
(current-buffer)))
1861 (info (or info
(org-babel-get-src-block-info)))
1864 (comment (string= "noweb" (cdr (assoc :comments
(nth 2 info
)))))
1865 (new-body "") index source-name evaluate prefix blocks-in-buffer
)
1866 (flet ((nb-add (text) (setq new-body
(concat new-body text
)))
1869 (funcall (intern (concat lang
"-mode")))
1870 (comment-region (point) (progn (insert text
) (point)))
1871 (org-babel-trim (buffer-string))))
1872 (blocks () ;; return the info lists of all blocks in this buffer
1876 (org-babel-map-src-blocks nil
1877 (setq infos
(cons (org-babel-get-src-block-info 'light
)
1881 (insert body
) (goto-char (point-min))
1882 (setq index
(point))
1883 (while (and (re-search-forward "<<\\(.+?\\)>>" nil t
))
1884 (save-match-data (setf source-name
(match-string 1)))
1885 (save-match-data (setq evaluate
(string-match "\(.*\)" source-name
)))
1888 (buffer-substring (match-beginning 0)
1890 (beginning-of-line 1) (point)))))
1891 ;; add interval to new-body (removing noweb reference)
1892 (goto-char (match-beginning 0))
1893 (nb-add (buffer-substring index
(point)))
1894 (goto-char (match-end 0))
1895 (setq index
(point))
1897 (with-current-buffer parent-buffer
1898 (mapconcat ;; interpose PREFIX between every line
1902 (let ((raw (org-babel-ref-resolve source-name
)))
1903 (if (stringp raw
) raw
(format "%S" raw
)))
1905 ;; retrieve from the library of babel
1906 (nth 2 (assoc (intern source-name
)
1907 org-babel-library-of-babel
))
1908 ;; return the contents of headlines literally
1910 (when (org-babel-ref-goto-headline-id source-name
)
1911 (org-babel-ref-headline-body)))
1912 ;; find the expansion of reference in this buffer
1915 (when (string= source-name
1916 (or (cdr (assoc :noweb-ref
(nth 2 i
)))
1918 (let ((body (org-babel-expand-noweb-references i
)))
1921 (concat (c-wrap (car cs
)) "\n"
1922 body
"\n" (c-wrap (cadr cs
))))
1923 (org-babel-tangle-comment-links i
))
1925 (or blocks-in-buffer
1926 (setq blocks-in-buffer
(blocks)))
1928 ;; possibly raise an error if named block doesn't exist
1929 (if (member lang org-babel-noweb-error-langs
)
1931 "<<" source-name
">> "
1932 "could not be resolved (see "
1933 "`org-babel-noweb-error-langs')"))
1935 "[\n\r]") (concat "\n" prefix
)))))
1936 (nb-add (buffer-substring index
(point-max)))))
1939 (defun org-babel-clean-text-properties (text)
1940 "Strip all properties from text return."
1942 (set-text-properties 0 (length text
) nil text
) text
))
1944 (defun org-babel-strip-protective-commas (body)
1945 "Strip protective commas from bodies of source blocks."
1946 (replace-regexp-in-string "^,#" "#" body
))
1948 (defun org-babel-script-escape (str &optional force
)
1949 "Safely convert tables into elisp lists."
1950 (let (in-single in-double out
)
1951 ((lambda (escaped) (condition-case nil
(org-babel-read escaped
) (error escaped
)))
1955 (or (and (string-equal "[" (substring str
0 1))
1956 (string-equal "]" (substring str -
1)))
1957 (and (string-equal "{" (substring str
0 1))
1958 (string-equal "}" (substring str -
1))))))
1968 (91 (if (or in-double in-single
) ; [
1971 (93 (if (or in-double in-single
) ; ]
1974 (123 (if (or in-double in-single
) ; {
1977 (125 (if (or in-double in-single
) ; }
1980 (44 (if (or in-double in-single
) ; ,
1981 (cons 44 out
) (cons 32 out
)))
1982 (39 (if in-double
; '
1984 (setq in-single
(not in-single
)) (cons 34 out
)))
1985 (34 (if in-single
; "
1986 (append (list 34 32) out
)
1987 (setq in-double
(not in-double
)) (cons 34 out
)))
1988 (t (cons ch out
)))))
1989 (string-to-list str
))
1990 (apply #'string
(reverse out
)))))
1993 (defun org-babel-read (cell &optional inhibit-lisp-eval
)
1994 "Convert the string value of CELL to a number if appropriate.
1995 Otherwise if cell looks like lisp (meaning it starts with a
1996 \"(\", \"'\", \"`\" or a \"[\") then read it as lisp, otherwise
1997 return it unmodified as a string. Optional argument NO-LISP-EVAL
1998 inhibits lisp evaluation for situations in which is it not
2000 (if (and (stringp cell
) (not (equal cell
"")))
2001 (or (org-babel-number-p cell
)
2002 (if (and (not inhibit-lisp-eval
)
2003 (member (substring cell
0 1) '("(" "'" "`" "[")))
2005 (if (string= (substring cell
0 1) "\"")
2007 (progn (set-text-properties 0 (length cell
) nil cell
) cell
))))
2010 (defun org-babel-number-p (string)
2011 "If STRING represents a number return it's value."
2012 (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string
)
2013 (= (length (substring string
(match-beginning 0)
2016 (string-to-number string
)))
2018 (defun org-babel-import-elisp-from-file (file-name &optional separator
)
2019 "Read the results located at FILE-NAME into an elisp table.
2020 If the table is trivial, then return it as a scalar."
2022 (save-window-excursion
2026 (org-table-import file-name separator
)
2027 (delete-file file-name
)
2028 (setq result
(mapcar (lambda (row)
2029 (mapcar #'org-babel-string-read row
))
2030 (org-table-to-lisp))))
2032 (if (null (cdr result
)) ;; if result is trivial vector, then scalarize it
2033 (if (consp (car result
))
2034 (if (null (cdr (car result
)))
2040 (defun org-babel-string-read (cell)
2041 "Strip nested \"s from around strings."
2042 (org-babel-read (or (and (stringp cell
)
2043 (string-match "\\\"\\(.+\\)\\\"" cell
)
2044 (match-string 1 cell
))
2047 (defun org-babel-reverse-string (string)
2048 "Return the reverse of STRING."
2049 (apply 'string
(reverse (string-to-list string
))))
2051 (defun org-babel-chomp (string &optional regexp
)
2052 "Strip trailing spaces and carriage returns from STRING.
2053 Default regexp used is \"[ \f\t\n\r\v]\" but can be
2054 overwritten by specifying a regexp as a second argument."
2055 (let ((regexp (or regexp
"[ \f\t\n\r\v]")))
2056 (while (and (> (length string
) 0)
2057 (string-match regexp
(substring string -
1)))
2058 (setq string
(substring string
0 -
1)))
2061 (defun org-babel-trim (string &optional regexp
)
2062 "Strip leading and trailing spaces and carriage returns from STRING.
2063 Like `org-babel-chomp' only it runs on both the front and back
2065 (org-babel-chomp (org-babel-reverse-string
2066 (org-babel-chomp (org-babel-reverse-string string
) regexp
))
2069 (defvar org-babel-org-babel-call-process-region-original nil
)
2070 (defun org-babel-tramp-handle-call-process-region
2071 (start end program
&optional delete buffer display
&rest args
)
2072 "Use tramp to handle call-process-region.
2073 Fixes a bug in `tramp-handle-call-process-region'."
2074 (if (and (featurep 'tramp
) (file-remote-p default-directory
))
2075 (let ((tmpfile (tramp-compat-make-temp-file "")))
2076 (write-region start end tmpfile
)
2077 (when delete
(delete-region start end
))
2079 ;; (apply 'call-process program tmpfile buffer display args)
2081 (apply 'process-file program tmpfile buffer display args
)
2082 (delete-file tmpfile
)))
2083 ;; org-babel-call-process-region-original is the original emacs
2084 ;; definition. It is in scope from the let binding in
2085 ;; org-babel-execute-src-block
2086 (apply org-babel-call-process-region-original
2087 start end program delete buffer display args
)))
2089 (defun org-babel-local-file-name (file)
2090 "Return the local name component of FILE."
2091 (if (file-remote-p file
)
2093 (with-parsed-tramp-file-name file nil
2097 (defun org-babel-process-file-name (name &optional no-quote-p
)
2098 "Prepare NAME to be used in an external process.
2099 If NAME specifies a remote location, the remote portion of the
2100 name is removed, since in that case the process will be executing
2101 remotely. The file name is then processed by
2102 `expand-file-name'. Unless second argument NO-QUOTE-P is non-nil,
2103 the file name is additionally processed by
2104 `shell-quote-argument'"
2105 ((lambda (f) (if no-quote-p f
(shell-quote-argument f
)))
2106 (expand-file-name (org-babel-local-file-name name
))))
2108 (defvar org-babel-temporary-directory
)
2109 (unless (or noninteractive
(boundp 'org-babel-temporary-directory
))
2110 (defvar org-babel-temporary-directory
2111 (or (and (boundp 'org-babel-temporary-directory
)
2112 (file-exists-p org-babel-temporary-directory
)
2113 org-babel-temporary-directory
)
2114 (make-temp-file "babel-" t
))
2115 "Directory to hold temporary files created to execute code blocks.
2116 Used by `org-babel-temp-file'. This directory will be removed on
2119 (defun org-babel-temp-file (prefix &optional suffix
)
2120 "Create a temporary file in the `org-babel-temporary-directory'.
2121 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2122 value of `temporary-file-directory' temporarily set to the value
2123 of `org-babel-temporary-directory'."
2124 (if (file-remote-p default-directory
)
2126 (concat (file-remote-p default-directory
)
2128 prefix temporary-file-directory
)
2130 (let ((temporary-file-directory
2131 (or (and (boundp 'org-babel-temporary-directory
)
2132 (file-exists-p org-babel-temporary-directory
)
2133 org-babel-temporary-directory
)
2134 temporary-file-directory
)))
2135 (make-temp-file prefix nil suffix
))))
2137 (defun org-babel-remove-temporary-directory ()
2138 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2139 (when (and (boundp 'org-babel-temporary-directory
)
2140 (file-exists-p org-babel-temporary-directory
))
2141 ;; taken from `delete-directory' in files.el
2144 (mapc (lambda (file)
2145 ;; This test is equivalent to
2146 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2147 ;; but more efficient
2148 (if (eq t
(car (file-attributes file
)))
2149 (delete-directory file
)
2150 (delete-file file
)))
2151 ;; We do not want to delete "." and "..".
2152 (directory-files org-babel-temporary-directory
'full
2153 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2154 (delete-directory org-babel-temporary-directory
))
2156 (message "Failed to remove temporary Org-babel directory %s"
2157 (if (boundp 'org-babel-temporary-directory
)
2158 org-babel-temporary-directory
2159 "[directory not defined]"))))))
2161 (add-hook 'kill-emacs-hook
'org-babel-remove-temporary-directory
)
2165 ;; arch-tag: 01a7ebee-06c5-4ee4-a709-e660d28c0af1