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 (when (org-called-interactively-p 'interactive
) (message hash
))
755 (sha1 (format "%s-%s"
762 (when (and v
(not (and (sequencep v
)
765 ((lambda (el) (format "%S" el
))
767 ((and (listp v
) ; lists are sorted
768 (member (car arg
) '(:result-params
)))
769 (sort (copy-sequence v
) #'string
<))
770 ((and (stringp v
) ; strings are sorted
771 (member (car arg
) '(:results
:exports
)))
772 (mapconcat #'identity
(sort (split-string v
)
774 (t v
)))))) ; atomic are left untouched
778 (defun org-babel-result-hash (&optional info
)
779 "Return the in-buffer hash associated with INFO."
780 (org-babel-where-is-src-block-result nil info
)
781 (org-babel-clean-text-properties (match-string 3)))
783 (defun org-babel-hide-hash ()
784 "Hide the hash in the current results line.
785 Only the initial `org-babel-hash-show' characters of the hash
786 will remain visible."
787 (add-to-invisibility-spec '(org-babel-hide-hash . t
))
789 (when (and (re-search-forward org-babel-result-regexp nil t
)
791 (let* ((start (match-beginning 3))
792 (hide-start (+ org-babel-hash-show start
))
794 (hash (match-string 3))
796 (setq ov1
(make-overlay start hide-start
))
797 (setq ov2
(make-overlay hide-start end
))
798 (overlay-put ov2
'invisible
'org-babel-hide-hash
)
799 (overlay-put ov1
'babel-hash hash
)))))
801 (defun org-babel-hide-all-hashes ()
802 "Hide the hash in the current buffer.
803 Only the initial `org-babel-hash-show' characters of each hash
804 will remain visible. This function should be called as part of
805 the `org-mode-hook'."
807 (while (re-search-forward org-babel-result-regexp nil t
)
808 (goto-char (match-beginning 0))
809 (org-babel-hide-hash)
810 (goto-char (match-end 0)))))
811 (add-hook 'org-mode-hook
'org-babel-hide-all-hashes
)
813 (defun org-babel-hash-at-point (&optional point
)
814 "Return the value of the hash at POINT.
815 The hash is also added as the last element of the kill ring.
816 This can be called with C-c C-c."
818 (let ((hash (car (delq nil
(mapcar
819 (lambda (ol) (overlay-get ol
'babel-hash
))
820 (overlays-at (or point
(point))))))))
821 (when hash
(kill-new hash
) (message hash
))))
822 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-hash-at-point
)
824 (defun org-babel-result-hide-spec ()
825 "Hide portions of results lines.
826 Add `org-babel-hide-result' as an invisibility spec for hiding
827 portions of results lines."
828 (add-to-invisibility-spec '(org-babel-hide-result . t
)))
829 (add-hook 'org-mode-hook
'org-babel-result-hide-spec
)
831 (defvar org-babel-hide-result-overlays nil
832 "Overlays hiding results.")
834 (defun org-babel-result-hide-all ()
835 "Fold all results in the current buffer."
837 (org-babel-show-result-all)
839 (while (re-search-forward org-babel-result-regexp nil t
)
840 (save-excursion (goto-char (match-beginning 0))
841 (org-babel-hide-result-toggle-maybe)))))
843 (defun org-babel-show-result-all ()
844 "Unfold all results in the current buffer."
845 (mapc 'delete-overlay org-babel-hide-result-overlays
)
846 (setq org-babel-hide-result-overlays nil
))
849 (defun org-babel-hide-result-toggle-maybe ()
850 "Toggle visibility of result at point."
852 (let ((case-fold-search t
))
854 (beginning-of-line 1)
855 (looking-at org-babel-result-regexp
))
856 (progn (org-babel-hide-result-toggle)
857 t
) ;; to signal that we took action
858 nil
))) ;; to signal that we did not
860 (defun org-babel-hide-result-toggle (&optional force
)
861 "Toggle the visibility of the current result."
865 (if (re-search-forward org-babel-result-regexp nil t
)
866 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
867 (end (progn (goto-char (- (org-babel-result-end) 1)) (point)))
869 (if (memq t
(mapcar (lambda (overlay)
870 (eq (overlay-get overlay
'invisible
)
871 'org-babel-hide-result
))
872 (overlays-at start
)))
873 (if (or (not force
) (eq force
'off
))
875 (when (member ov org-babel-hide-result-overlays
)
876 (setq org-babel-hide-result-overlays
877 (delq ov org-babel-hide-result-overlays
)))
878 (when (eq (overlay-get ov
'invisible
)
879 'org-babel-hide-result
)
880 (delete-overlay ov
)))
881 (overlays-at start
)))
882 (setq ov
(make-overlay start end
))
883 (overlay-put ov
'invisible
'org-babel-hide-result
)
884 ;; make the block accessible to isearch
886 ov
'isearch-open-invisible
888 (when (member ov org-babel-hide-result-overlays
)
889 (setq org-babel-hide-result-overlays
890 (delq ov org-babel-hide-result-overlays
)))
891 (when (eq (overlay-get ov
'invisible
)
892 'org-babel-hide-result
)
893 (delete-overlay ov
))))
894 (push ov org-babel-hide-result-overlays
)))
895 (error "Not looking at a result line"))))
897 ;; org-tab-after-check-for-cycling-hook
898 (add-hook 'org-tab-first-hook
'org-babel-hide-result-toggle-maybe
)
899 ;; Remove overlays when changing major mode
900 (add-hook 'org-mode-hook
901 (lambda () (org-add-hook 'change-major-mode-hook
902 'org-babel-show-result-all
'append
'local
)))
904 (defvar org-file-properties
)
905 (defun org-babel-params-from-properties (&optional lang
)
906 "Retrieve parameters specified as properties.
907 Return an association list of any source block params which
908 may be specified in the properties of the current outline entry."
915 (or (org-entry-get (point) header-arg t
)
916 (org-entry-get (point) (concat ":" header-arg
) t
)))
917 (cons (intern (concat ":" header-arg
))
918 (org-babel-read val
))))
922 org-babel-header-arg-names
924 (setq sym
(intern (concat "org-babel-header-arg-names:" lang
)))
925 (and (boundp sym
) (eval sym
))))))))))
927 (defun org-babel-params-from-buffer ()
928 "Retrieve per-buffer parameters.
929 Return an association list of any source block params which
930 may be specified in the current buffer."
931 (let (local-properties)
936 (goto-char (point-min))
937 (while (re-search-forward
938 (org-make-options-regexp (list "BABEL" "PROPERTIES")) nil t
)
939 (setq local-properties
940 (org-babel-merge-params
942 (org-babel-parse-header-arguments
943 (org-match-string-no-properties 2)))))
944 local-properties
)))))
946 (defvar org-src-preserve-indentation
)
947 (defun org-babel-parse-src-block-match ()
948 "Parse the results from a match of the `org-babel-src-block-regexp'."
949 (let* ((block-indentation (length (match-string 1)))
950 (lang (org-babel-clean-text-properties (match-string 2)))
951 (lang-headers (intern (concat "org-babel-default-header-args:" lang
)))
952 (switches (match-string 3))
953 (body (org-babel-clean-text-properties (match-string 5)))
954 (preserve-indentation (or org-src-preserve-indentation
955 (string-match "-i\\>" switches
))))
957 ;; get block body less properties, protective commas, and indentation
960 (insert (org-babel-strip-protective-commas body
))
961 (unless preserve-indentation
(org-do-remove-indentation))
963 (org-babel-merge-params
964 org-babel-default-header-args
965 (org-babel-params-from-buffer)
966 (org-babel-params-from-properties lang
)
967 (if (boundp lang-headers
) (eval lang-headers
) nil
)
968 (org-babel-parse-header-arguments
969 (org-babel-clean-text-properties (or (match-string 4) ""))))
973 (defun org-babel-parse-inline-src-block-match ()
974 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
975 (let* ((lang (org-babel-clean-text-properties (match-string 2)))
976 (lang-headers (intern (concat "org-babel-default-header-args:" lang
))))
978 (org-babel-strip-protective-commas
979 (org-babel-clean-text-properties (match-string 5)))
980 (org-babel-merge-params
981 org-babel-default-inline-header-args
982 (org-babel-params-from-buffer)
983 (org-babel-params-from-properties lang
)
984 (if (boundp lang-headers
) (eval lang-headers
) nil
)
985 (org-babel-parse-header-arguments
986 (org-babel-clean-text-properties (or (match-string 4) "")))))))
988 (defun org-babel-parse-header-arguments (arg-string)
989 "Parse a string of header arguments returning an alist."
990 (when (> (length arg-string
) 0)
995 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
997 (cons (intern (match-string 1 arg
))
998 (org-babel-read (org-babel-chomp (match-string 2 arg
))))
999 (cons (intern (org-babel-chomp arg
)) nil
)))
1000 (let ((balance 0) (partial nil
) (lst nil
) (last 0))
1001 (mapc (lambda (ch) ; split on [] balanced instances of [ \t]:
1002 (setq balance
(+ balance
1003 (cond ((equal 91 ch
) 1)
1006 (setq partial
(cons ch partial
))
1007 (when (and (= ch
58) (= balance
0)
1008 (or (= last
32) (= last
9)))
1009 (setq lst
(cons (apply #'string
(nreverse (cddr partial
)))
1011 (setq partial
(list ch
)))
1013 (string-to-list arg-string
))
1014 (nreverse (cons (apply #'string
(nreverse partial
)) lst
)))))))
1016 (defun org-babel-process-params (params)
1017 "Expand variables in PARAMS and add summary parameters."
1018 (let* ((vars-and-names (org-babel-disassemble-tables
1019 (mapcar (lambda (el)
1020 (if (consp (cdr el
))
1021 (cdr el
) (org-babel-ref-parse (cdr el
))))
1022 (org-babel-get-header params
:var
))
1023 (cdr (assoc :hlines params
))
1024 (cdr (assoc :colnames params
))
1025 (cdr (assoc :rownames params
))))
1026 (raw-result (or (cdr (assoc :results params
)) ""))
1027 (result-params (append
1028 (split-string (if (stringp raw-result
)
1031 (cdr (assoc :result-params params
)))))
1033 (mapcar (lambda (var) (cons :var var
)) (car vars-and-names
))
1035 (cons :colname-names
(or (cdr (assoc :colname-names params
))
1036 (cadr vars-and-names
)))
1037 (cons :rowname-names
(or (cdr (assoc :rowname-names params
))
1038 (caddr vars-and-names
)))
1039 (cons :result-params result-params
)
1040 (cons :result-type
(cond ((member "output" result-params
) 'output
)
1041 ((member "value" result-params
) 'value
)
1043 (org-babel-get-header params
:var
'other
))))
1045 ;; row and column names
1046 (defun org-babel-del-hlines (table)
1047 "Remove all 'hlines from TABLE."
1048 (remove 'hline table
))
1050 (defun org-babel-get-colnames (table)
1051 "Return the column names of TABLE.
1052 Return a cons cell, the `car' of which contains the TABLE less
1053 colnames, and the `cdr' of which contains a list of the column
1055 (if (equal 'hline
(nth 1 table
))
1056 (cons (cddr table
) (car table
))
1057 (cons (cdr table
) (car table
))))
1059 (defun org-babel-get-rownames (table)
1060 "Return the row names of TABLE.
1061 Return a cons cell, the `car' of which contains the TABLE less
1062 colnames, and the `cdr' of which contains a list of the column
1063 names. Note: this function removes any hlines in TABLE."
1064 (flet ((trans (table) (apply #'mapcar
* #'list table
)))
1065 (let* ((width (apply 'max
1066 (mapcar (lambda (el) (if (listp el
) (length el
) 0)) table
)))
1067 (table (trans (mapcar (lambda (row)
1068 (if (not (equal row
'hline
))
1072 (setq row
(cons 'hline row
)))
1075 (cons (mapcar (lambda (row) (if (equal (car row
) 'hline
) 'hline row
))
1076 (trans (cdr table
)))
1077 (remove 'hline
(car table
))))))
1079 (defun org-babel-put-colnames (table colnames
)
1080 "Add COLNAMES to TABLE if they exist."
1081 (if colnames
(apply 'list colnames
'hline table
) table
))
1083 (defun org-babel-put-rownames (table rownames
)
1084 "Add ROWNAMES to TABLE if they exist."
1086 (mapcar (lambda (row)
1088 (cons (or (pop rownames
) "") row
)
1092 (defun org-babel-pick-name (names selector
)
1093 "Select one out of an alist of row or column names.
1094 SELECTOR can be either a list of names in which case those names
1095 will be returned directly, or an index into the list NAMES in
1096 which case the indexed names will be return."
1097 (if (listp selector
)
1100 (if (and selector
(symbolp selector
) (not (equal t selector
)))
1101 (cdr (assoc selector names
))
1102 (if (integerp selector
)
1103 (nth (- selector
1) names
)
1104 (cdr (car (last names
))))))))
1106 (defun org-babel-disassemble-tables (vars hlines colnames rownames
)
1107 "Parse tables for further processing.
1108 Process the variables in VARS according to the HLINES,
1109 ROWNAMES and COLNAMES header arguments. Return a list consisting
1110 of the vars, cnames and rnames."
1111 (let (cnames rnames
)
1115 (when (listp (cdr var
))
1116 (when (and (not (equal colnames
"no"))
1117 (or colnames
(and (equal (nth 1 (cdr var
)) 'hline
)
1118 (not (member 'hline
(cddr (cdr var
)))))))
1119 (let ((both (org-babel-get-colnames (cdr var
))))
1120 (setq cnames
(cons (cons (car var
) (cdr both
))
1122 (setq var
(cons (car var
) (car both
)))))
1123 (when (and rownames
(not (equal rownames
"no")))
1124 (let ((both (org-babel-get-rownames (cdr var
))))
1125 (setq rnames
(cons (cons (car var
) (cdr both
))
1127 (setq var
(cons (car var
) (car both
)))))
1128 (when (and hlines
(not (equal hlines
"yes")))
1129 (setq var
(cons (car var
) (org-babel-del-hlines (cdr var
))))))
1134 (defun org-babel-reassemble-table (table colnames rownames
)
1135 "Add column and row names to a table.
1136 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1137 to the table for reinsertion to org-mode."
1140 (if (and colnames
(listp (car table
)) (= (length (car table
))
1142 (org-babel-put-colnames table colnames
) table
))
1143 (if (and rownames
(= (length table
) (length rownames
)))
1144 (org-babel-put-rownames table rownames
) table
))
1147 (defun org-babel-where-is-src-block-head ()
1148 "Find where the current source block begins.
1149 Return the point at the beginning of the current source
1150 block. Specifically at the beginning of the #+BEGIN_SRC line.
1151 If the point is not on a source block then return nil."
1152 (let ((initial (point)) top bottom
)
1154 (save-excursion ;; on a source name line or a #+header line
1155 (beginning-of-line 1)
1156 (and (or (looking-at org-babel-src-name-regexp
)
1157 (looking-at org-babel-multi-line-header-regexp
))
1159 (while (and (forward-line 1)
1160 (looking-at org-babel-multi-line-header-regexp
)))
1161 (looking-at org-babel-src-block-regexp
))
1163 (save-excursion ;; on a #+begin_src line
1164 (beginning-of-line 1)
1165 (and (looking-at org-babel-src-block-regexp
)
1167 (save-excursion ;; inside a src block
1169 (re-search-backward "^[ \t]*#\\+begin_src" nil t
) (setq top
(point))
1170 (re-search-forward "^[ \t]*#\\+end_src" nil t
) (setq bottom
(point))
1171 (< top initial
) (< initial bottom
)
1172 (progn (goto-char top
) (beginning-of-line 1)
1173 (looking-at org-babel-src-block-regexp
))
1177 (defun org-babel-goto-src-block-head ()
1178 "Go to the beginning of the current code block."
1181 (if head
(goto-char head
) (error "not currently in a code block")))
1182 (org-babel-where-is-src-block-head)))
1185 (defun org-babel-goto-named-src-block (name)
1186 "Go to a named source-code block."
1188 (let ((completion-ignore-case t
))
1189 (list (org-icompleting-read "source-block name: "
1190 (org-babel-src-block-names) nil t
))))
1191 (let ((point (org-babel-find-named-block name
)))
1193 ;; taken from `org-open-at-point'
1194 (progn (goto-char point
) (org-show-context))
1195 (message "source-code block '%s' not found in this buffer" name
))))
1197 (defun org-babel-find-named-block (name)
1198 "Find a named source-code block.
1199 Return the location of the source block identified by source
1200 NAME, or nil if no such block exists. Set match data according to
1201 org-babel-named-src-block-regexp."
1203 (let ((case-fold-search t
)
1204 (regexp (org-babel-named-src-block-regexp-for-name name
)) msg
)
1205 (goto-char (point-min))
1206 (when (or (re-search-forward regexp nil t
)
1207 (re-search-backward regexp nil t
))
1208 (match-beginning 0)))))
1210 (defun org-babel-src-block-names (&optional file
)
1211 "Returns the names of source blocks in FILE or the current buffer."
1213 (when file
(find-file file
)) (goto-char (point-min))
1215 (while (re-search-forward org-babel-src-name-w-name-regexp nil t
)
1216 (setq names
(cons (match-string 4) names
)))
1220 (defun org-babel-goto-named-result (name)
1221 "Go to a named result."
1223 (let ((completion-ignore-case t
))
1224 (list (org-icompleting-read "source-block name: "
1225 (org-babel-result-names) nil t
))))
1226 (let ((point (org-babel-find-named-result name
)))
1228 ;; taken from `org-open-at-point'
1229 (progn (goto-char point
) (org-show-context))
1230 (message "result '%s' not found in this buffer" name
))))
1232 (defun org-babel-find-named-result (name)
1233 "Find a named result.
1234 Return the location of the result named NAME in the current
1235 buffer or nil if no such result exists."
1237 (goto-char (point-min))
1238 (when (re-search-forward
1239 (concat org-babel-result-regexp
1240 "[ \t]" (regexp-quote name
) "[ \t\n\f\v\r]") nil t
)
1241 (beginning-of-line 0) (point))))
1243 (defun org-babel-result-names (&optional file
)
1244 "Returns the names of results in FILE or the current buffer."
1246 (when file
(find-file file
)) (goto-char (point-min))
1248 (while (re-search-forward org-babel-result-w-name-regexp nil t
)
1249 (setq names
(cons (match-string 4) names
)))
1253 (defun org-babel-next-src-block (&optional arg
)
1254 "Jump to the next source block.
1255 With optional prefix argument ARG, jump forward ARG many source blocks."
1257 (when (looking-at org-babel-src-block-regexp
) (forward-char 1))
1259 (re-search-forward org-babel-src-block-regexp nil nil
(or arg
1))
1260 (error (error "No further code blocks")))
1261 (goto-char (match-beginning 0)) (org-show-context))
1264 (defun org-babel-previous-src-block (&optional arg
)
1265 "Jump to the previous source block.
1266 With optional prefix argument ARG, jump backward ARG many source blocks."
1269 (re-search-backward org-babel-src-block-regexp nil nil
(or arg
1))
1270 (error (error "No previous code blocks")))
1271 (goto-char (match-beginning 0)) (org-show-context))
1273 (defvar org-babel-load-languages
)
1276 (defun org-babel-mark-block ()
1277 "Mark current src block"
1283 (looking-at org-babel-src-block-regexp
))
1284 (push-mark (match-end 5) nil t
)
1285 (goto-char (match-beginning 5))))
1286 (org-babel-where-is-src-block-head)))
1288 (defun org-babel-demarcate-block (&optional arg
)
1289 "Wrap or split the code in the region or on the point.
1290 When called from inside of a code block the current block is
1291 split. When called from outside of a code block a new code block
1292 is created. In both cases if the region is demarcated and if the
1293 region is not active then the point is demarcated."
1295 (let ((info (org-babel-get-src-block-info 'light
))
1296 (stars (concat (make-string (or (org-current-level) 1) ?
*) " ")))
1302 (let ((lang (nth 0 info
))
1303 (indent (make-string (nth 5 info
) ?
)))
1304 (when (string-match "^[[:space:]]*$"
1305 (buffer-substring (point-at-bol)
1307 (delete-region (point-at-bol) (point-at-eol)))
1308 (insert (concat (if (looking-at "^") "" "\n")
1309 indent
"#+end_src\n"
1310 (if arg stars indent
) "\n"
1311 indent
"#+begin_src " lang
1312 (if (looking-at "[\n\r]") "" "\n")))))
1313 (move-end-of-line 2))
1314 (sort (if (region-active-p) (list (mark) (point)) (list (point))) #'>))
1315 (let ((start (point))
1316 (lang (org-icompleting-read "Lang: "
1317 (mapcar (lambda (el) (symbol-name (car el
)))
1318 org-babel-load-languages
)))
1319 (body (delete-and-extract-region
1320 (if (region-active-p) (mark) (point)) (point))))
1321 (insert (concat (if (looking-at "^") "" "\n")
1322 (if arg
(concat stars
"\n") "")
1323 "#+begin_src " lang
"\n"
1325 (if (or (= (length body
) 0)
1326 (string-match "[\r\n]$" body
)) "" "\n")
1328 (goto-char start
) (move-end-of-line 1)))))
1330 (defvar org-babel-lob-one-liner-regexp
)
1331 (defvar org-babel-inline-lob-one-liner-regexp
)
1332 (defun org-babel-where-is-src-block-result (&optional insert info hash indent
)
1333 "Find where the current source block results begin.
1334 Return the point at the beginning of the result of the current
1335 source block. Specifically at the beginning of the results line.
1336 If no result exists for this block then create a results line
1337 following the source block."
1339 (let* ((on-lob-line (save-excursion
1340 (beginning-of-line 1)
1341 (looking-at org-babel-lob-one-liner-regexp
)))
1342 (inlinep (save-excursion
1343 (re-search-backward "[ \f\t\n\r\v]" nil t
)
1344 (when (looking-at org-babel-inline-src-block-regexp
)
1346 (name (if on-lob-line
1347 (nth 0 (org-babel-lob-get-info))
1348 (nth 4 (or info
(org-babel-get-src-block-info)))))
1349 (head (unless on-lob-line
(org-babel-where-is-src-block-head)))
1351 (when head
(goto-char head
))
1353 found
;; was there a result (before we potentially insert one)
1358 ;; - return t if it is found, else return nil
1359 ;; - if it does not need to be rebuilt, then don't set end
1360 ;; - if it does need to be rebuilt then do set end
1361 name
(setq beg
(org-babel-find-named-result name
))
1363 (when (and hash
(not (string= hash
(match-string 3))))
1364 (goto-char beg
) (setq end beg
) ;; beginning of result
1366 (delete-region end
(org-babel-result-end)) nil
)))
1369 ;; - return t if it is found, else return nil
1370 ;; - if it is found, and the hash doesn't match, delete and set end
1371 (or on-lob-line
(re-search-forward "^[ \t]*#\\+end_src" nil t
))
1372 (progn (end-of-line 1)
1373 (if (eobp) (insert "\n") (forward-char 1))
1376 (progn ;; unnamed results line already exists
1377 (re-search-forward "[^ \f\t\n\r\v]" nil t
)
1378 (beginning-of-line 1)
1380 (concat org-babel-result-regexp
"\n")))
1382 ;; must remove and rebuild if hash!=old-hash
1383 (if (and hash
(not (string= hash
(match-string 3))))
1387 end
(org-babel-result-end)))
1388 (setq end nil
)))))))))
1389 (if (and insert end
)
1393 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1398 (org-number-sequence 1 indent
) "")
1401 (when hash
(concat "["hash
"]"))
1403 (when name
(concat " " name
)) "\n"))
1404 (unless beg
(insert "\n") (backward-char))
1405 (beginning-of-line 0)
1406 (if hash
(org-babel-hide-hash))
1410 (defvar org-block-regexp
)
1411 (defun org-babel-read-result ()
1412 "Read the result at `point' into emacs-lisp."
1413 (let ((case-fold-search t
) result-string
)
1415 ((org-at-table-p) (org-babel-read-table))
1416 ((org-at-item-p) (org-babel-read-list))
1417 ((looking-at org-bracket-link-regexp
) (org-babel-read-link))
1418 ((looking-at org-block-regexp
) (org-babel-trim (match-string 4)))
1419 ((looking-at "^[ \t]*: ")
1422 (mapconcat (lambda (line)
1423 (if (and (> (length line
) 1)
1424 (string-match "^[ \t]*: \\(.+\\)" line
))
1425 (match-string 1 line
)
1429 (point) (org-babel-result-end)) "[\r\n]+")
1431 (or (org-babel-number-p result-string
) result-string
))
1432 ((looking-at org-babel-result-regexp
)
1433 (save-excursion (forward-line 1) (org-babel-read-result))))))
1435 (defun org-babel-read-table ()
1436 "Read the table at `point' into emacs-lisp."
1437 (mapcar (lambda (row)
1438 (if (and (symbolp row
) (equal row
'hline
)) row
1439 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
)) row
)))
1440 (org-table-to-lisp)))
1442 (defun org-babel-read-list ()
1443 "Read the list at `point' into emacs-lisp."
1444 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
))
1445 (mapcar #'cadr
(cdr (org-list-parse-list)))))
1447 (defvar org-link-types-re
)
1448 (defun org-babel-read-link ()
1449 "Read the link at `point' into emacs-lisp.
1450 If the path of the link is a file path it is expanded using
1451 `expand-file-name'."
1452 (let* ((case-fold-search t
)
1453 (raw (and (looking-at org-bracket-link-regexp
)
1454 (org-babel-clean-text-properties (match-string 1))))
1455 (type (and (string-match org-link-types-re raw
)
1456 (match-string 1 raw
))))
1458 ((not type
) (expand-file-name raw
))
1459 ((string= type
"file")
1460 (and (string-match "file\\(.*\\):\\(.+\\)" raw
)
1461 (expand-file-name (match-string 2 raw
))))
1464 (defun org-babel-format-result (result &optional sep
)
1465 "Format RESULT for writing to file."
1466 (flet ((echo-res (result)
1467 (if (stringp result
) result
(format "%S" result
))))
1476 (echo-res result
))))
1478 (defun org-babel-insert-result
1479 (result &optional result-params info hash indent lang
)
1480 "Insert RESULT into the current buffer.
1481 By default RESULT is inserted after the end of the
1482 current source block. With optional argument RESULT-PARAMS
1483 controls insertion of results in the org-mode file.
1484 RESULT-PARAMS can take the following values...
1486 replace - (default option) insert results after the source block
1487 replacing any previously inserted results
1489 silent -- no results are inserted
1491 file ---- the results are interpreted as a file path, and are
1492 inserted into the buffer using the Org-mode file syntax
1494 list ---- the results are interpreted as an Org-mode list.
1496 raw ----- results are added directly to the Org-mode file. This
1497 is a good option if you code block will output org-mode
1500 org ----- similar in effect to raw, only the results are wrapped
1501 in an org code block. Similar to the raw option, on
1502 export the results will be interpreted as org-formatted
1503 text, however by wrapping the results in an org code
1504 block they can be replaced upon re-execution of the
1507 html ---- results are added inside of a #+BEGIN_HTML block. This
1508 is a good option if you code block will output html
1511 latex --- results are added inside of a #+BEGIN_LATEX block.
1512 This is a good option if you code block will output
1513 latex formatted text.
1515 code ---- the results are extracted in the syntax of the source
1516 code of the language being evaluated and are added
1517 inside of a #+BEGIN_SRC block with the source-code
1518 language set appropriately. Note this relies on the
1519 optional LANG argument."
1520 (if (stringp result
)
1522 (setq result
(org-babel-clean-text-properties result
))
1523 (when (member "file" result-params
)
1524 (setq result
(org-babel-result-to-file result
))))
1525 (unless (listp result
) (setq result
(format "%S" result
))))
1526 (if (and result-params
(member "silent" result-params
))
1528 (message (replace-regexp-in-string "%" "%%" (format "%S" result
)))
1533 (or (= (point) (point-at-bol))
1534 (re-search-backward "[ \f\t\n\r\v]" nil t
))
1535 (when (or (looking-at org-babel-inline-src-block-regexp
)
1536 (looking-at org-babel-inline-lob-one-liner-regexp
))
1537 (goto-char (match-end 0))
1538 (insert (if (listp result
) "\n" " "))
1540 (existing-result (unless inlinep
1541 (org-babel-where-is-src-block-result
1542 t info hash indent
)))
1544 (cdr (assoc :results_switches
(nth 2 info
))))
1546 (when (and (stringp result
) ; ensure results end in a newline
1548 (> (length result
) 0)
1549 (not (or (string-equal (substring result -
1) "\n")
1550 (string-equal (substring result -
1) "\r"))))
1551 (setq result
(concat result
"\n")))
1552 (if (not existing-result
)
1553 (setq beg
(or inlinep
(point)))
1554 (goto-char existing-result
)
1556 (re-search-forward "#" nil t
)
1557 (setq indent
(- (current-column) 1)))
1561 ((member "replace" result-params
)
1562 (delete-region (point) (org-babel-result-end)))
1563 ((member "append" result-params
)
1564 (goto-char (org-babel-result-end)) (setq beg
(point-marker)))
1565 ((member "prepend" result-params
)))) ; already there
1566 (setq results-switches
1567 (if results-switches
(concat " " results-switches
) ""))
1568 ;; insert results based on type
1570 ;; do nothing for an empty result
1571 ((= (length result
) 0))
1572 ;; insert a list if preferred
1573 ((member "list" result-params
)
1576 (org-list-to-generic
1579 (lambda (el) (list nil
(if (stringp el
) el
(format "%S" el
))))
1580 (if (listp result
) result
(list result
))))
1581 '(:splicep nil
:istart
"- " :iend
"\n")))
1583 ;; assume the result is a table if it's not a string
1584 ((not (stringp result
))
1586 (insert (concat (orgtbl-to-orgtbl
1587 (if (or (eq 'hline
(car result
))
1588 (and (listp (car result
))
1589 (listp (cdr (car result
)))))
1590 result
(list result
))
1591 '(:fmt
(lambda (cell) (format "%s" cell
)))) "\n"))
1592 (goto-char beg
) (when (org-at-table-p) (org-table-align)))
1593 ((member "file" result-params
)
1595 (t (goto-char beg
) (insert result
)))
1596 (when (listp result
) (goto-char (org-table-end)))
1597 (setq end
(point-marker))
1598 ;; possibly wrap result
1599 (flet ((wrap (start finish
)
1600 (goto-char beg
) (insert (concat start
"\n"))
1601 (goto-char end
) (insert (concat finish
"\n"))
1602 (setq end
(point-marker))))
1604 ((member "html" result-params
)
1605 (wrap "#+BEGIN_HTML" "#+END_HTML"))
1606 ((member "latex" result-params
)
1607 (wrap "#+BEGIN_LaTeX" "#+END_LaTeX"))
1608 ((member "code" result-params
)
1609 (wrap (format "#+BEGIN_SRC %s%s" (or lang
"none") results-switches
)
1611 ((member "org" result-params
)
1612 (wrap "#+BEGIN_ORG" "#+END_ORG"))
1613 ((member "raw" result-params
)
1614 (goto-char beg
) (if (org-at-table-p) (org-cycle)))
1615 ((member "wrap" result-params
)
1616 (when (and (stringp result
) (not (member "file" result-params
)))
1617 (org-babel-examplize-region beg end results-switches
))
1618 (wrap "#+BEGIN_RESULT" "#+END_RESULT"))
1619 ((and (stringp result
) (not (member "file" result-params
)))
1620 (org-babel-examplize-region beg end results-switches
)
1621 (setq end
(point)))))
1622 ;; possibly indent the results to match the #+results line
1623 (when (and (not inlinep
) (numberp indent
) indent
(> indent
0)
1624 ;; in this case `table-align' does the work for us
1625 (not (and (listp result
)
1626 (member "append" result-params
))))
1627 (indent-rigidly beg end indent
))))
1628 (if (= (length result
) 0)
1629 (if (member "value" result-params
)
1630 (message "Code block returned no value.")
1631 (message "Code block produced no output."))
1632 (message "Code block evaluation complete."))))
1634 (defun org-babel-remove-result (&optional info
)
1635 "Remove the result of the current source block."
1637 (let ((location (org-babel-where-is-src-block-result nil info
)) start
)
1640 (goto-char location
) (setq start
(point)) (forward-line 1)
1641 (delete-region start
(org-babel-result-end))))))
1643 (defun org-babel-result-end ()
1644 "Return the point at the end of the current set of results"
1647 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
1648 ((org-at-item-p) (let* ((struct (org-list-struct))
1649 (prvs (org-list-prevs-alist struct
)))
1650 (org-list-get-list-end (point-at-bol) struct prvs
)))
1652 (let ((case-fold-search t
)
1653 (blocks-re (regexp-opt
1654 (list "latex" "html" "example" "src" "result" "org"))))
1655 (if (looking-at (concat "[ \t]*#\\+begin_" blocks-re
))
1656 (progn (re-search-forward (concat "[ \t]*#\\+end_" blocks-re
) nil t
)
1658 (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
1662 (defun org-babel-result-to-file (result)
1663 "Convert RESULT into an `org-mode' link.
1664 If the `default-directory' is different from the containing
1665 file's directory then expand relative links."
1666 (flet ((cond-exp (file)
1667 (if (and default-directory
1669 (not (string= (expand-file-name default-directory
)
1671 (file-name-directory buffer-file-name
)))))
1672 (expand-file-name file default-directory
)
1674 (if (stringp result
)
1675 (format "[[file:%s]]" (cond-exp result
))
1676 (when (and (listp result
) (= 2 (length result
))
1677 (stringp (car result
)) (stringp (cadr result
)))
1678 (format "[[file:%s][%s]]" (car result
) (cadr result
))))))
1680 (defun org-babel-examplize-region (beg end
&optional results-switches
)
1681 "Comment out region using the inline '==' or ': ' org example quote."
1683 (flet ((chars-between (b e
) (string-match "[\\S]" (buffer-substring b e
))))
1684 (if (or (chars-between (save-excursion (goto-char beg
) (point-at-bol)) beg
)
1685 (chars-between end
(save-excursion (goto-char end
) (point-at-eol))))
1688 (insert (format "=%s=" (prog1 (buffer-substring beg end
)
1689 (delete-region beg end
)))))
1690 (let ((size (count-lines beg end
)))
1692 (cond ((= size
0)) ; do nothing for an empty result
1693 ((< size org-babel-min-lines-for-block-output
)
1696 (beginning-of-line 1) (insert ": ") (forward-line 1)))
1699 (insert (if results-switches
1700 (format "#+begin_example%s\n" results-switches
)
1701 "#+begin_example\n"))
1702 (if (markerp end
) (goto-char end
) (forward-char (- end beg
)))
1703 (insert "#+end_example\n"))))))))
1705 (defun org-babel-update-block-body (new-body)
1706 "Update the body of the current code block to NEW-BODY."
1707 (if (not (org-babel-where-is-src-block-head))
1708 (error "not in source block")
1710 (replace-match (concat (org-babel-trim new-body
) "\n") nil t nil
5))
1711 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
1713 (defun org-babel-merge-params (&rest plists
)
1714 "Combine all parameter association lists in PLISTS.
1715 Later elements of PLISTS override the values of previous elements.
1716 This takes into account some special considerations for certain
1717 parameters when merging lists."
1718 (let ((results-exclusive-groups
1719 '(("file" "list" "vector" "table" "scalar" "raw" "org"
1720 "html" "latex" "code" "pp" "wrap")
1721 ("replace" "silent" "append" "prepend")
1722 ("output" "value")))
1723 (exports-exclusive-groups
1724 '(("code" "results" "both" "none")))
1726 params results exports tangle noweb cache vars shebang comments padline
)
1727 (flet ((e-merge (exclusive-groups &rest result-params
)
1728 ;; maintain exclusivity of mutually exclusive parameters
1730 (mapc (lambda (new-params)
1731 (mapc (lambda (new-param)
1732 (mapc (lambda (exclusive-group)
1733 (when (member new-param exclusive-group
)
1734 (mapcar (lambda (excluded-param)
1741 (setq output
(org-uniquify
1742 (cons new-param output
))))
1752 (let ((name (if (listp (cdr pair
))
1754 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
1756 (intern (match-string 1 (cdr pair
)))))))
1760 (if (member name
(mapcar #'car vars
))
1764 (unless (equal (car p
) name
) p
))
1767 (list (cons name pair
))))
1768 ;; if no name is given, then assign to variables in order
1769 (prog1 (setf (cddr (nth variable-index vars
))
1770 (concat (symbol-name
1771 (car (nth variable-index vars
)))
1773 (incf variable-index
)))))
1775 (setq results
(e-merge results-exclusive-groups
1778 (let ((r (cdr pair
)))
1779 (if (stringp r
) r
(eval r
)))))))
1782 (setq results
(e-merge results-exclusive-groups
1784 (unless (or (member "both" exports
)
1785 (member "none" exports
)
1786 (member "code" exports
))
1787 (setq exports
(e-merge exports-exclusive-groups
1788 exports
'("results"))))
1789 (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))
1791 (setq exports
(e-merge exports-exclusive-groups
1792 exports
(split-string (cdr pair
)))))
1793 (:tangle
;; take the latest -- always overwrite
1794 (setq tangle
(or (list (cdr pair
)) tangle
)))
1796 (setq noweb
(e-merge '(("yes" "no" "tangle")) noweb
1797 (split-string (or (cdr pair
) "")))))
1799 (setq cache
(e-merge '(("yes" "no")) cache
1800 (split-string (or (cdr pair
) "")))))
1802 (setq padline
(e-merge '(("yes" "no")) padline
1803 (split-string (or (cdr pair
) "")))))
1804 (:shebang
;; take the latest -- always overwrite
1805 (setq shebang
(or (list (cdr pair
)) shebang
)))
1807 (setq comments
(e-merge '(("yes" "no")) comments
1808 (split-string (or (cdr pair
) "")))))
1809 (t ;; replace: this covers e.g. :session
1810 (setq params
(cons pair
(assq-delete-all (car pair
) params
))))))
1813 (setq vars
(reverse vars
))
1814 (while vars
(setq params
(cons (cons :var
(cddr (pop vars
))) params
)))
1817 (let ((key (intern (concat ":" (symbol-name hd
))))
1819 (setf params
(cons (cons key
(mapconcat 'identity val
" ")) params
))))
1820 '(results exports tangle noweb padline cache shebang comments
))
1823 (defun org-babel-expand-noweb-references (&optional info parent-buffer
)
1824 "Expand Noweb references in the body of the current source code block.
1826 For example the following reference would be replaced with the
1827 body of the source-code block named 'example-block'.
1831 Note that any text preceding the <<foo>> construct on a line will
1832 be interposed between the lines of the replacement text. So for
1833 example if <<foo>> is placed behind a comment, then the entire
1834 replacement text will also be commented.
1836 This function must be called from inside of the buffer containing
1837 the source-code block which holds BODY.
1839 In addition the following syntax can be used to insert the
1840 results of evaluating the source-code block named 'example-block'.
1844 Any optional arguments can be passed to example-block by placing
1845 the arguments inside the parenthesis following the convention
1846 defined by `org-babel-lob'. For example
1848 <<example-block(a=9)>>
1850 would set the value of argument \"a\" equal to \"9\". Note that
1851 these arguments are not evaluated in the current source-code
1852 block but are passed literally to the \"example-block\"."
1853 (let* ((parent-buffer (or parent-buffer
(current-buffer)))
1854 (info (or info
(org-babel-get-src-block-info)))
1857 (comment (string= "noweb" (cdr (assoc :comments
(nth 2 info
)))))
1858 (new-body "") index source-name evaluate prefix blocks-in-buffer
)
1859 (flet ((nb-add (text) (setq new-body
(concat new-body text
)))
1862 (funcall (intern (concat lang
"-mode")))
1863 (comment-region (point) (progn (insert text
) (point)))
1864 (org-babel-trim (buffer-string))))
1865 (blocks () ;; return the info lists of all blocks in this buffer
1869 (org-babel-map-src-blocks nil
1870 (setq infos
(cons (org-babel-get-src-block-info 'light
)
1874 (insert body
) (goto-char (point-min))
1875 (setq index
(point))
1876 (while (and (re-search-forward "<<\\(.+?\\)>>" nil t
))
1877 (save-match-data (setf source-name
(match-string 1)))
1878 (save-match-data (setq evaluate
(string-match "\(.*\)" source-name
)))
1881 (buffer-substring (match-beginning 0)
1883 (beginning-of-line 1) (point)))))
1884 ;; add interval to new-body (removing noweb reference)
1885 (goto-char (match-beginning 0))
1886 (nb-add (buffer-substring index
(point)))
1887 (goto-char (match-end 0))
1888 (setq index
(point))
1890 (with-current-buffer parent-buffer
1891 (mapconcat ;; interpose PREFIX between every line
1895 (let ((raw (org-babel-ref-resolve source-name
)))
1896 (if (stringp raw
) raw
(format "%S" raw
)))
1898 ;; retrieve from the library of babel
1899 (nth 2 (assoc (intern source-name
)
1900 org-babel-library-of-babel
))
1901 ;; return the contents of headlines literally
1903 (when (org-babel-ref-goto-headline-id source-name
)
1904 (org-babel-ref-headline-body)))
1905 ;; find the expansion of reference in this buffer
1908 (when (string= source-name
1909 (or (cdr (assoc :noweb-ref
(nth 2 i
)))
1911 (let ((body (org-babel-expand-noweb-references i
)))
1914 (concat (c-wrap (car cs
)) "\n"
1915 body
"\n" (c-wrap (cadr cs
))))
1916 (org-babel-tangle-comment-links i
))
1918 (or blocks-in-buffer
1919 (setq blocks-in-buffer
(blocks)))
1921 ;; possibly raise an error if named block doesn't exist
1922 (if (member lang org-babel-noweb-error-langs
)
1924 "<<" source-name
">> "
1925 "could not be resolved (see "
1926 "`org-babel-noweb-error-langs')"))
1928 "[\n\r]") (concat "\n" prefix
)))))
1929 (nb-add (buffer-substring index
(point-max)))))
1932 (defun org-babel-clean-text-properties (text)
1933 "Strip all properties from text return."
1935 (set-text-properties 0 (length text
) nil text
) text
))
1937 (defun org-babel-strip-protective-commas (body)
1938 "Strip protective commas from bodies of source blocks."
1939 (replace-regexp-in-string "^,#" "#" body
))
1941 (defun org-babel-script-escape (str &optional force
)
1942 "Safely convert tables into elisp lists."
1943 (let (in-single in-double out
)
1944 ((lambda (escaped) (condition-case nil
(org-babel-read escaped
) (error escaped
)))
1948 (or (and (string-equal "[" (substring str
0 1))
1949 (string-equal "]" (substring str -
1)))
1950 (and (string-equal "{" (substring str
0 1))
1951 (string-equal "}" (substring str -
1))))))
1961 (91 (if (or in-double in-single
) ; [
1964 (93 (if (or in-double in-single
) ; ]
1967 (123 (if (or in-double in-single
) ; {
1970 (125 (if (or in-double in-single
) ; }
1973 (44 (if (or in-double in-single
) ; ,
1974 (cons 44 out
) (cons 32 out
)))
1975 (39 (if in-double
; '
1977 (setq in-single
(not in-single
)) (cons 34 out
)))
1978 (34 (if in-single
; "
1979 (append (list 34 32) out
)
1980 (setq in-double
(not in-double
)) (cons 34 out
)))
1981 (t (cons ch out
)))))
1982 (string-to-list str
))
1983 (apply #'string
(reverse out
)))))
1986 (defun org-babel-read (cell &optional inhibit-lisp-eval
)
1987 "Convert the string value of CELL to a number if appropriate.
1988 Otherwise if cell looks like lisp (meaning it starts with a
1989 \"(\", \"'\", \"`\" or a \"[\") then read it as lisp, otherwise
1990 return it unmodified as a string. Optional argument NO-LISP-EVAL
1991 inhibits lisp evaluation for situations in which is it not
1993 (if (and (stringp cell
) (not (equal cell
"")))
1994 (or (org-babel-number-p cell
)
1995 (if (and (not inhibit-lisp-eval
)
1996 (member (substring cell
0 1) '("(" "'" "`" "[")))
1998 (if (string= (substring cell
0 1) "\"")
2000 (progn (set-text-properties 0 (length cell
) nil cell
) cell
))))
2003 (defun org-babel-number-p (string)
2004 "If STRING represents a number return it's value."
2005 (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string
)
2006 (= (length (substring string
(match-beginning 0)
2009 (string-to-number string
)))
2011 (defun org-babel-import-elisp-from-file (file-name &optional separator
)
2012 "Read the results located at FILE-NAME into an elisp table.
2013 If the table is trivial, then return it as a scalar."
2015 (save-window-excursion
2019 (org-table-import file-name separator
)
2020 (delete-file file-name
)
2021 (setq result
(mapcar (lambda (row)
2022 (mapcar #'org-babel-string-read row
))
2023 (org-table-to-lisp))))
2025 (if (null (cdr result
)) ;; if result is trivial vector, then scalarize it
2026 (if (consp (car result
))
2027 (if (null (cdr (car result
)))
2033 (defun org-babel-string-read (cell)
2034 "Strip nested \"s from around strings."
2035 (org-babel-read (or (and (stringp cell
)
2036 (string-match "\\\"\\(.+\\)\\\"" cell
)
2037 (match-string 1 cell
))
2040 (defun org-babel-reverse-string (string)
2041 "Return the reverse of STRING."
2042 (apply 'string
(reverse (string-to-list string
))))
2044 (defun org-babel-chomp (string &optional regexp
)
2045 "Strip trailing spaces and carriage returns from STRING.
2046 Default regexp used is \"[ \f\t\n\r\v]\" but can be
2047 overwritten by specifying a regexp as a second argument."
2048 (let ((regexp (or regexp
"[ \f\t\n\r\v]")))
2049 (while (and (> (length string
) 0)
2050 (string-match regexp
(substring string -
1)))
2051 (setq string
(substring string
0 -
1)))
2054 (defun org-babel-trim (string &optional regexp
)
2055 "Strip leading and trailing spaces and carriage returns from STRING.
2056 Like `org-babel-chomp' only it runs on both the front and back
2058 (org-babel-chomp (org-babel-reverse-string
2059 (org-babel-chomp (org-babel-reverse-string string
) regexp
))
2062 (defvar org-babel-org-babel-call-process-region-original nil
)
2063 (defun org-babel-tramp-handle-call-process-region
2064 (start end program
&optional delete buffer display
&rest args
)
2065 "Use tramp to handle call-process-region.
2066 Fixes a bug in `tramp-handle-call-process-region'."
2067 (if (and (featurep 'tramp
) (file-remote-p default-directory
))
2068 (let ((tmpfile (tramp-compat-make-temp-file "")))
2069 (write-region start end tmpfile
)
2070 (when delete
(delete-region start end
))
2072 ;; (apply 'call-process program tmpfile buffer display args)
2074 (apply 'process-file program tmpfile buffer display args
)
2075 (delete-file tmpfile
)))
2076 ;; org-babel-call-process-region-original is the original emacs
2077 ;; definition. It is in scope from the let binding in
2078 ;; org-babel-execute-src-block
2079 (apply org-babel-call-process-region-original
2080 start end program delete buffer display args
)))
2082 (defun org-babel-local-file-name (file)
2083 "Return the local name component of FILE."
2084 (if (file-remote-p file
)
2086 (with-parsed-tramp-file-name file nil
2090 (defun org-babel-process-file-name (name &optional no-quote-p
)
2091 "Prepare NAME to be used in an external process.
2092 If NAME specifies a remote location, the remote portion of the
2093 name is removed, since in that case the process will be executing
2094 remotely. The file name is then processed by
2095 `expand-file-name'. Unless second argument NO-QUOTE-P is non-nil,
2096 the file name is additionally processed by
2097 `shell-quote-argument'"
2098 ((lambda (f) (if no-quote-p f
(shell-quote-argument f
)))
2099 (expand-file-name (org-babel-local-file-name name
))))
2101 (defvar org-babel-temporary-directory
)
2102 (unless (or noninteractive
(boundp 'org-babel-temporary-directory
))
2103 (defvar org-babel-temporary-directory
2104 (or (and (boundp 'org-babel-temporary-directory
)
2105 (file-exists-p org-babel-temporary-directory
)
2106 org-babel-temporary-directory
)
2107 (make-temp-file "babel-" t
))
2108 "Directory to hold temporary files created to execute code blocks.
2109 Used by `org-babel-temp-file'. This directory will be removed on
2112 (defun org-babel-temp-file (prefix &optional suffix
)
2113 "Create a temporary file in the `org-babel-temporary-directory'.
2114 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2115 value of `temporary-file-directory' temporarily set to the value
2116 of `org-babel-temporary-directory'."
2117 (if (file-remote-p default-directory
)
2119 (concat (file-remote-p default-directory
)
2121 prefix temporary-file-directory
)
2123 (let ((temporary-file-directory
2124 (or (and (boundp 'org-babel-temporary-directory
)
2125 (file-exists-p org-babel-temporary-directory
)
2126 org-babel-temporary-directory
)
2127 temporary-file-directory
)))
2128 (make-temp-file prefix nil suffix
))))
2130 (defun org-babel-remove-temporary-directory ()
2131 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2132 (when (and (boundp 'org-babel-temporary-directory
)
2133 (file-exists-p org-babel-temporary-directory
))
2134 ;; taken from `delete-directory' in files.el
2137 (mapc (lambda (file)
2138 ;; This test is equivalent to
2139 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2140 ;; but more efficient
2141 (if (eq t
(car (file-attributes file
)))
2142 (delete-directory file
)
2143 (delete-file file
)))
2144 ;; We do not want to delete "." and "..".
2145 (directory-files org-babel-temporary-directory
'full
2146 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2147 (delete-directory org-babel-temporary-directory
))
2149 (message "Failed to remove temporary Org-babel directory %s"
2150 (if (boundp 'org-babel-temporary-directory
)
2151 org-babel-temporary-directory
2152 "[directory not defined]"))))))
2154 (add-hook 'kill-emacs-hook
'org-babel-remove-temporary-directory
)
2158 ;; arch-tag: 01a7ebee-06c5-4ee4-a709-e660d28c0af1