1 ;;; ob.el --- working with code blocks in org-mode
3 ;; Copyright (C) 2009-2012 Free Software Foundation, Inc.
5 ;; Author: Eric Schulte
7 ;; Keywords: literate programming, reproducible research
8 ;; Homepage: http://orgmode.org
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
31 (defvar org-babel-call-process-region-original
)
32 (defvar org-src-lang-modes
)
33 (defvar org-babel-library-of-babel
)
34 (declare-function show-all
"outline" ())
35 (declare-function org-reduce
"org" (CL-FUNC CL-SEQ
&rest CL-KEYS
))
36 (declare-function tramp-compat-make-temp-file
"tramp-compat"
37 (filename &optional dir-flag
))
38 (declare-function tramp-dissect-file-name
"tramp" (name &optional nodefault
))
39 (declare-function tramp-file-name-user
"tramp" (vec))
40 (declare-function tramp-file-name-host
"tramp" (vec))
41 (declare-function with-parsed-tramp-file-name
"tramp" (filename var
&rest body
))
42 (declare-function org-icompleting-read
"org" (&rest args
))
43 (declare-function org-edit-src-code
"org-src"
44 (&optional context code edit-buffer-name quietp
))
45 (declare-function org-edit-src-exit
"org-src" (&optional context
))
46 (declare-function org-open-at-point
"org" (&optional in-emacs reference-buffer
))
47 (declare-function org-save-outline-visibility
"org" (use-markers &rest body
))
48 (declare-function org-outline-overlay-data
"org" (&optional use-markers
))
49 (declare-function org-set-outline-overlay-data
"org" (data))
50 (declare-function org-narrow-to-subtree
"org" ())
51 (declare-function org-entry-get
"org"
52 (pom property
&optional inherit literal-nil
))
53 (declare-function org-make-options-regexp
"org" (kwds &optional extra
))
54 (declare-function org-do-remove-indentation
"org" (&optional n
))
55 (declare-function org-show-context
"org" (&optional key
))
56 (declare-function org-at-table-p
"org" (&optional table-type
))
57 (declare-function org-cycle
"org" (&optional arg
))
58 (declare-function org-uniquify
"org" (list))
59 (declare-function org-current-level
"org" ())
60 (declare-function org-table-import
"org-table" (file arg
))
61 (declare-function org-add-hook
"org-compat"
62 (hook function
&optional append local
))
63 (declare-function org-table-align
"org-table" ())
64 (declare-function org-table-end
"org-table" (&optional table-type
))
65 (declare-function orgtbl-to-generic
"org-table" (table params
))
66 (declare-function orgtbl-to-orgtbl
"org-table" (table params
))
67 (declare-function org-babel-tangle-comment-links
"ob-tangle" (&optional info
))
68 (declare-function org-babel-lob-get-info
"ob-lob" nil
)
69 (declare-function org-babel-ref-split-args
"ob-ref" (arg-string))
70 (declare-function org-babel-ref-parse
"ob-ref" (assignment))
71 (declare-function org-babel-ref-resolve
"ob-ref" (ref))
72 (declare-function org-babel-ref-goto-headline-id
"ob-ref" (id))
73 (declare-function org-babel-ref-headline-body
"ob-ref" ())
74 (declare-function org-babel-lob-execute-maybe
"ob-lob" ())
75 (declare-function org-number-sequence
"org-compat" (from &optional to inc
))
76 (declare-function org-at-item-p
"org-list" ())
77 (declare-function org-list-parse-list
"org-list" (&optional delete
))
78 (declare-function org-list-to-generic
"org-list" (LIST PARAMS
))
79 (declare-function org-list-struct
"org-list" ())
80 (declare-function org-list-prevs-alist
"org-list" (struct))
81 (declare-function org-list-get-list-end
"org-list" (item struct prevs
))
83 (defgroup org-babel nil
84 "Code block evaluation and management in `org-mode' documents."
88 (defcustom org-confirm-babel-evaluate t
89 "Confirm before evaluation.
90 Require confirmation before interactively evaluating code
91 blocks in Org-mode buffers. The default value of this variable
92 is t, meaning confirmation is required for any code block
93 evaluation. This variable can be set to nil to inhibit any
94 future confirmation requests. This variable can also be set to a
95 function which takes two arguments the language of the code block
96 and the body of the code block. Such a function should then
97 return a non-nil value if the user should be prompted for
98 execution or nil if no prompt is required.
100 Warning: Disabling confirmation may result in accidental
101 evaluation of potentially harmful code. It may be advisable
102 remove code block execution from C-c C-c as further protection
103 against accidental code block evaluation. The
104 `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
105 remove code block execution from the C-c C-c keybinding."
107 :type
'(choice boolean function
))
108 ;; don't allow this variable to be changed through file settings
109 (put 'org-confirm-babel-evaluate
'safe-local-variable
(lambda (x) (eq x t
)))
111 (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
112 "Remove code block evaluation from the C-c C-c key binding."
116 (defcustom org-babel-results-keyword
"RESULTS"
117 "Keyword used to name results generated by code blocks.
118 Should be either RESULTS or NAME however any capitalization may
123 (defvar org-babel-src-name-regexp
124 "^[ \t]*#\\+name:[ \t]*"
125 "Regular expression used to match a source name line.")
127 (defvar org-babel-multi-line-header-regexp
128 "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
129 "Regular expression used to match multi-line header arguments.")
131 (defvar org-babel-src-name-w-name-regexp
132 (concat org-babel-src-name-regexp
134 org-babel-multi-line-header-regexp
136 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)")
137 "Regular expression matching source name lines with a name.")
139 (defvar org-babel-src-block-regexp
141 ;; (1) indentation (2) lang
142 "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
144 "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
145 ;; (4) header arguments
148 "\\([^\000]*?\n\\)?[ \t]*#\\+end_src")
149 "Regexp used to identify code blocks.")
151 (defvar org-babel-inline-src-block-regexp
153 ;; (1) replacement target (2) lang
154 "\\(?:^\\|[^-[:alnum:]]\\)\\(src_\\([^ \f\t\n\r\v]+\\)"
155 ;; (3,4) (unused, headers)
156 "\\(\\|\\[\\(.*?\\)\\]\\)"
158 "{\\([^\f\n\r\v]+?\\)}\\)")
159 "Regexp used to identify inline src-blocks.")
161 (defun org-babel-get-header (params key
&optional others
)
162 "Select only header argument of type KEY from a list.
163 Optional argument OTHERS indicates that only the header that do
164 not match KEY should be returned."
167 (lambda (p) (when (funcall (if others
#'not
#'identity
) (eq (car p
) key
)) p
))
170 (defun org-babel-get-inline-src-block-matches()
171 "Set match data if within body of an inline source block.
172 Returns non-nil if match-data set"
173 (let ((src-at-0-p (save-excursion
174 (beginning-of-line 1)
175 (string= "src" (thing-at-point 'word
))))
176 (first-line-p (= 1 (line-number-at-pos)))
178 (let ((search-for (cond ((and src-at-0-p first-line-p
"src_"))
179 (first-line-p "[ \t]src_")
180 (t "[ \f\t\n\r\v]src_")))
181 (lower-limit (if first-line-p
183 (- (point-at-bol) 1))))
185 (when (or (and src-at-0-p
(bobp))
186 (and (re-search-forward "}" (point-at-eol) t
)
187 (re-search-backward search-for lower-limit t
)
189 (when (looking-at org-babel-inline-src-block-regexp
)
192 (defvar org-babel-inline-lob-one-liner-regexp
)
193 (defun org-babel-get-lob-one-liner-matches()
194 "Set match data if on line of an lob one liner.
195 Returns non-nil if match-data set"
197 (unless (= (point) (point-at-bol)) ;; move before inline block
198 (re-search-backward "[ \f\t\n\r\v]" nil t
))
199 (if (looking-at org-babel-inline-lob-one-liner-regexp
)
203 (defun org-babel-get-src-block-info (&optional light
)
204 "Get information on the current source block.
206 Optional argument LIGHT does not resolve remote variable
207 references; a process which could likely result in the execution
208 of other code blocks.
211 (language body header-arguments-alist switches name indent)."
212 (let ((case-fold-search t
) head info name indent
)
214 (if (setq head
(org-babel-where-is-src-block-head))
217 (setq info
(org-babel-parse-src-block-match))
218 (setq indent
(car (last info
)))
219 (setq info
(butlast info
))
220 (while (and (forward-line -
1)
221 (looking-at org-babel-multi-line-header-regexp
))
223 (org-babel-merge-params
225 (org-babel-parse-header-arguments (match-string 1)))))
226 (when (looking-at org-babel-src-name-w-name-regexp
)
227 (setq name
(org-babel-clean-text-properties (match-string 3)))
228 (when (and (match-string 5) (> (length (match-string 5)) 0))
229 (setf (nth 2 info
) ;; merge functional-syntax vars and header-args
230 (org-babel-merge-params
232 (lambda (ref) (cons :var ref
))
234 (lambda (var) ;; check that each variable is initialized
235 (if (string-match ".+=.+" var
)
238 "variable \"%s\"%s must be assigned a default value"
239 var
(if name
(format " in block \"%s\"" name
) ""))))
240 (org-babel-ref-split-args (match-string 5))))
242 ;; inline source block
243 (when (org-babel-get-inline-src-block-matches)
244 (setq info
(org-babel-parse-inline-src-block-match))))
245 ;; resolve variable references and add summary parameters
246 (when (and info
(not light
))
247 (setf (nth 2 info
) (org-babel-process-params (nth 2 info
))))
248 (when info
(append info
(list name indent
)))))
250 (defvar org-current-export-file
) ; dynamically bound
251 (defun org-babel-confirm-evaluate (info)
252 "Confirm evaluation of the code block INFO.
253 This behavior can be suppressed by setting the value of
254 `org-confirm-babel-evaluate' to nil, in which case all future
255 interactive code block evaluations will proceed without any
256 confirmation from the user.
258 Note disabling confirmation may result in accidental evaluation
259 of potentially harmful code."
260 (let* ((eval (or (cdr (assoc :eval
(nth 2 info
)))
261 (when (assoc :noeval
(nth 2 info
)) "no")))
262 (query (cond ((equal eval
"query") t
)
263 ((and org-current-export-file
264 (equal eval
"query-export")) t
)
265 ((functionp org-confirm-babel-evaluate
)
266 (funcall org-confirm-babel-evaluate
267 (nth 0 info
) (nth 1 info
)))
268 (t org-confirm-babel-evaluate
))))
269 (if (or (equal eval
"never") (equal eval
"no")
270 (and org-current-export-file
(or (equal eval
"no-export")
271 (equal eval
"never-export")))
274 (format "Evaluate this%scode block%son your system? "
275 (if info
(format " %s " (nth 0 info
)) " ")
277 (format " (%s) " (nth 4 info
)) " "))))))
278 (prog1 nil
(message "Evaluation %s"
279 (if (or (equal eval
"never") (equal eval
"no")
280 (equal eval
"no-export")
281 (equal eval
"never-export"))
282 "Disabled" "Aborted")))
286 (defun org-babel-execute-safely-maybe ()
287 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
288 (org-babel-execute-maybe)))
290 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-execute-safely-maybe
)
293 (defun org-babel-execute-maybe ()
295 (or (org-babel-execute-src-block-maybe)
296 (org-babel-lob-execute-maybe)))
298 (defun org-babel-execute-src-block-maybe ()
299 "Conditionally execute a source block.
300 Detect if this is context for a Babel src-block and if so
301 then run `org-babel-execute-src-block'."
303 (let ((info (org-babel-get-src-block-info)))
305 (progn (org-babel-eval-wipe-error-buffer)
306 (org-babel-execute-src-block current-prefix-arg info
) t
) nil
)))
309 (defun org-babel-view-src-block-info ()
310 "Display information on the current source block.
311 This includes header arguments, language and name, and is largely
312 a window into the `org-babel-get-src-block-info' function."
314 (let ((info (org-babel-get-src-block-info 'light
)))
315 (flet ((full (it) (> (length it
) 0))
316 (printf (fmt &rest args
) (princ (apply #'format fmt args
))))
318 (with-help-window (help-buffer)
319 (let ((name (nth 4 info
))
321 (switches (nth 3 info
))
322 (header-args (nth 2 info
)))
323 (when name
(printf "Name: %s\n" name
))
324 (when lang
(printf "Lang: %s\n" lang
))
325 (when (full switches
) (printf "Switches: %s\n" switches
))
326 (printf "Header Arguments:\n")
327 (dolist (pair (sort header-args
328 (lambda (a b
) (string< (symbol-name (car a
))
329 (symbol-name (car b
))))))
330 (when (full (cdr pair
))
331 (printf "\t%S%s\t%s\n"
333 (if (> (length (format "%S" (car pair
))) 7) "" "\t")
337 (defun org-babel-expand-src-block-maybe ()
338 "Conditionally expand a source block.
339 Detect if this is context for a org-babel src-block and if so
340 then run `org-babel-expand-src-block'."
342 (let ((info (org-babel-get-src-block-info)))
344 (progn (org-babel-expand-src-block current-prefix-arg info
) t
)
348 (defun org-babel-load-in-session-maybe ()
349 "Conditionally load a source block in a session.
350 Detect if this is context for a org-babel src-block and if so
351 then run `org-babel-load-in-session'."
353 (let ((info (org-babel-get-src-block-info)))
355 (progn (org-babel-load-in-session current-prefix-arg info
) t
)
358 (add-hook 'org-metaup-hook
'org-babel-load-in-session-maybe
)
361 (defun org-babel-pop-to-session-maybe ()
362 "Conditionally pop to a session.
363 Detect if this is context for a org-babel src-block and if so
364 then run `org-babel-pop-to-session'."
366 (let ((info (org-babel-get-src-block-info)))
367 (if info
(progn (org-babel-pop-to-session current-prefix-arg info
) t
) nil
)))
369 (add-hook 'org-metadown-hook
'org-babel-pop-to-session-maybe
)
371 (defconst org-babel-common-header-args-w-values
372 '((cache .
((no yes
)))
374 (colnames .
((nil no yes
)))
375 (comments .
((no link yes org both noweb
)))
377 (eval .
((never query
)))
378 (exports .
((code results both none
)))
380 (hlines .
((no yes
)))
381 (mkdirp .
((yes no
)))
384 (noweb .
((yes no tangle
)))
387 (padline .
((yes no
)))
388 (results .
((file list vector table scalar verbatim
)
389 (raw org html latex code pp wrap
)
390 (replace silent append prepend
)
392 (rownames .
((no yes
)))
396 (tangle .
((tangle yes no
:any
)))
400 (defconst org-babel-header-arg-names
401 (mapcar #'car org-babel-common-header-args-w-values
)
402 "Common header arguments used by org-babel.
403 Note that individual languages may define their own language
404 specific header arguments as well.")
406 (defvar org-babel-default-header-args
407 '((:session .
"none") (:results .
"replace") (:exports .
"code")
408 (:cache .
"no") (:noweb .
"no") (:hlines .
"no") (:tangle .
"no")
409 (:padnewline .
"yes"))
410 "Default arguments to use when evaluating a source block.")
412 (defvar org-babel-default-inline-header-args
413 '((:session .
"none") (:results .
"replace") (:exports .
"results"))
414 "Default arguments to use when evaluating an inline source block.")
416 (defvar org-babel-data-names
'("TBLNAME" "RESULTS" "NAME"))
418 (defvar org-babel-result-regexp
419 (concat "^[ \t]*#\\+"
420 (regexp-opt org-babel-data-names t
)
421 "\\(\\[\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*")
422 "Regular expression used to match result lines.
423 If the results are associated with a hash key then the hash will
424 be saved in the second match data.")
426 (defvar org-babel-result-w-name-regexp
427 (concat org-babel-result-regexp
428 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
430 (defvar org-babel-min-lines-for-block-output
10
431 "The minimum number of lines for block output.
432 If number of lines of output is equal to or exceeds this
433 value, the output is placed in a #+begin_example...#+end_example
434 block. Otherwise the output is marked as literal by inserting
435 colons at the starts of the lines. This variable only takes
436 effect if the :results output option is in effect.")
438 (defvar org-babel-noweb-error-langs nil
439 "Languages for which Babel will raise literate programming errors.
440 List of languages for which errors should be raised when the
441 source code block satisfying a noweb reference in this language
442 can not be resolved.")
444 (defvar org-babel-hash-show
4
445 "Number of initial characters to show of a hidden results hash.")
447 (defvar org-babel-after-execute-hook nil
448 "Hook for functions to be called after `org-babel-execute-src-block'")
450 (defun org-babel-named-src-block-regexp-for-name (name)
451 "This generates a regexp used to match a src block named NAME."
452 (concat org-babel-src-name-regexp
(regexp-quote name
)
453 "\\([ \t]\\|$\\|(\\)" ".*[\r\n]"
454 (substring org-babel-src-block-regexp
1)))
456 (defun org-babel-named-data-regexp-for-name (name)
457 "This generates a regexp used to match data named NAME."
458 (concat org-babel-result-regexp
(regexp-quote name
) "\\([ \t]\\|$\\)"))
461 (defvar call-process-region
)
464 (defun org-babel-execute-src-block (&optional arg info params
)
465 "Execute the current source code block.
466 Insert the results of execution into the buffer. Source code
467 execution and the collection and formatting of results can be
468 controlled through a variety of header arguments.
470 With prefix argument ARG, force re-execution even if an existing
471 result cached in the buffer would otherwise have been returned.
473 Optionally supply a value for INFO in the form returned by
474 `org-babel-get-src-block-info'.
476 Optionally supply a value for PARAMS which will be merged with
477 the header arguments specified at the front of the source code
480 (let ((info (or info
(org-babel-get-src-block-info))))
481 (when (org-babel-confirm-evaluate
483 (setf (nth 2 i
) (org-babel-merge-params (nth 2 info
) params
))
485 (let* ((lang (nth 0 info
))
487 (org-babel-process-params
488 (org-babel-merge-params (nth 2 info
) params
))
490 (cache?
(and (not arg
) (cdr (assoc :cache params
))
491 (string= "yes" (cdr (assoc :cache params
)))))
492 (result-params (cdr (assoc :result-params params
)))
493 (new-hash (when cache?
(org-babel-sha1-hash info
)))
494 (old-hash (when cache?
(org-babel-current-result-hash)))
495 (body (setf (nth 1 info
)
496 (if (org-babel-noweb-p params
:eval
)
497 (org-babel-expand-noweb-references info
)
499 (dir (cdr (assoc :dir params
)))
501 (or (and dir
(file-name-as-directory dir
)) default-directory
))
502 (org-babel-call-process-region-original
503 (if (boundp 'org-babel-call-process-region-original
)
504 org-babel-call-process-region-original
505 (symbol-function 'call-process-region
)))
506 (indent (car (last info
)))
509 (flet ((call-process-region (&rest args
)
510 (apply 'org-babel-tramp-handle-call-process-region args
)))
511 (flet ((lang-check (f)
512 (let ((f (intern (concat "org-babel-execute:" f
))))
513 (when (fboundp f
) f
))))
515 (or (lang-check lang
)
516 (lang-check (symbol-name
517 (cdr (assoc lang org-src-lang-modes
))))
518 (error "No org-babel-execute function for %s!" lang
))))
519 (if (and (not arg
) new-hash
(equal new-hash old-hash
))
520 (save-excursion ;; return cached result
521 (goto-char (org-babel-where-is-src-block-result nil info
))
522 (end-of-line 1) (forward-char 1)
523 (setq result
(org-babel-read-result))
524 (message (replace-regexp-in-string
525 "%" "%%" (format "%S" result
))) result
)
526 (message "executing %s code block%s..."
528 (if (nth 4 info
) (format " (%s)" (nth 4 info
)) ""))
531 (if (and (eq (cdr (assoc :result-type params
)) 'value
)
532 (or (member "vector" result-params
)
533 (member "table" result-params
))
534 (not (listp result
)))
535 (list (list result
)) result
))
536 (funcall cmd body params
)))
537 ;; if non-empty result and :file then write to :file
538 (when (cdr (assoc :file params
))
540 (with-temp-file (cdr (assoc :file params
))
542 (org-babel-format-result
543 result
(cdr (assoc :sep
(nth 2 info
)))))))
544 (setq result
(cdr (assoc :file params
))))
545 (org-babel-insert-result
546 result result-params info new-hash indent lang
)
547 (run-hooks 'org-babel-after-execute-hook
)
549 (setq call-process-region
'org-babel-call-process-region-original
))))))
551 (defun org-babel-expand-body:generic
(body params
&optional var-lines
)
552 "Expand BODY with PARAMS.
553 Expand a block of code with org-babel according to its header
554 arguments. This generic implementation of body expansion is
555 called for languages which have not defined their own specific
556 org-babel-expand-body:lang function."
557 (mapconcat #'identity
(append var-lines
(list body
)) "\n"))
560 (defun org-babel-expand-src-block (&optional arg info params
)
561 "Expand the current source code block.
562 Expand according to the source code block's header
563 arguments and pop open the results in a preview buffer."
565 (let* ((info (or info
(org-babel-get-src-block-info)))
567 (params (setf (nth 2 info
)
568 (sort (org-babel-merge-params (nth 2 info
) params
)
569 (lambda (el1 el2
) (string< (symbol-name (car el1
))
570 (symbol-name (car el2
)))))))
571 (body (setf (nth 1 info
)
572 (if (org-babel-noweb-p params
:eval
)
573 (org-babel-expand-noweb-references info
) (nth 1 info
))))
574 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
575 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
578 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
579 (org-babel-expand-body:generic
580 body params
(and (fboundp assignments-cmd
)
581 (funcall assignments-cmd params
))))))
583 nil expanded
(concat "*Org-Babel Preview " (buffer-name) "[ " lang
" ]*"))))
585 (defun org-babel-edit-distance (s1 s2
)
586 "Return the edit (levenshtein) distance between strings S1 S2."
587 (let* ((l1 (length s1
))
589 (dist (map 'vector
(lambda (_) (make-vector (1+ l2
) nil
))
590 (number-sequence 1 (1+ l1
)))))
591 (flet ((in (i j
) (aref (aref dist i
) j
))
592 (mmin (&rest lst
) (apply #'min
(remove nil lst
))))
593 (setf (aref (aref dist
0) 0) 0)
594 (dolist (i (number-sequence 1 l1
))
595 (dolist (j (number-sequence 1 l2
))
596 (setf (aref (aref dist i
) j
)
597 (+ (if (equal (aref s1
(1- i
)) (aref s2
(1- j
))) 0 1)
598 (mmin (in (1- i
) j
) (in i
(1- j
)) (in (1- i
) (1- j
)))))))
602 (defun org-babel-check-src-block ()
603 "Check for misspelled header arguments in the current code block."
605 ;; TODO: report malformed code block
606 ;; TODO: report incompatible combinations of header arguments
607 ;; TODO: report uninitialized variables
608 (let ((too-close 2) ;; <- control closeness to report potential match
609 (names (mapcar #'symbol-name org-babel-header-arg-names
)))
610 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg
)) 1))
611 (and (org-babel-where-is-src-block-head)
612 (org-babel-parse-header-arguments
613 (org-babel-clean-text-properties
614 (match-string 4))))))
616 (when (and (not (string= header name
))
617 (<= (org-babel-edit-distance header name
) too-close
)
618 (not (member header names
)))
619 (error "supplied header \"%S\" is suspiciously close to \"%S\""
621 (message "No suspicious header arguments found.")))
624 (defun org-babel-insert-header-arg ()
625 "Insert a header argument selecting from lists of common args and values."
627 (let* ((lang (car (org-babel-get-src-block-info 'light
)))
628 (lang-headers (intern (concat "org-babel-header-arg-names:" lang
)))
629 (headers (append (if (boundp lang-headers
)
630 (mapcar (lambda (h) (cons h
:any
))
633 org-babel-common-header-args-w-values
))
634 (arg (org-icompleting-read
637 (lambda (header-spec) (symbol-name (car header-spec
)))
640 (let ((vals (cdr (assoc (intern arg
) headers
))))
646 (read-from-minibuffer "value: "))
650 (let ((arg (org-icompleting-read
652 (cons "default" (mapcar #'symbol-name group
)))))
653 (if (and arg
(not (string= "default" arg
)))
659 (defun org-babel-load-in-session (&optional arg info
)
660 "Load the body of the current source-code block.
661 Evaluate the header arguments for the source block before
662 entering the session. After loading the body this pops open the
665 (let* ((info (or info
(org-babel-get-src-block-info)))
667 (params (nth 2 info
))
668 (body (setf (nth 1 info
)
669 (if (org-babel-noweb-p params
:eval
)
670 (org-babel-expand-noweb-references info
)
672 (session (cdr (assoc :session params
)))
673 (dir (cdr (assoc :dir params
)))
675 (or (and dir
(file-name-as-directory dir
)) default-directory
))
676 (cmd (intern (concat "org-babel-load-session:" lang
))))
677 (unless (fboundp cmd
)
678 (error "No org-babel-load-session function for %s!" lang
))
679 (pop-to-buffer (funcall cmd session body params
))
683 (defun org-babel-initiate-session (&optional arg info
)
684 "Initiate session for current code block.
685 If called with a prefix argument then resolve any variable
686 references in the header arguments and assign these variables in
687 the session. Copy the body of the code block to the kill ring."
689 (let* ((info (or info
(org-babel-get-src-block-info (not arg
))))
692 (params (nth 2 info
))
693 (session (cdr (assoc :session params
)))
694 (dir (cdr (assoc :dir params
)))
696 (or (and dir
(file-name-as-directory dir
)) default-directory
))
697 (init-cmd (intern (format "org-babel-%s-initiate-session" lang
)))
698 (prep-cmd (intern (concat "org-babel-prep-session:" lang
))))
699 (if (and (stringp session
) (string= session
"none"))
700 (error "This block is not using a session!"))
701 (unless (fboundp init-cmd
)
702 (error "No org-babel-initiate-session function for %s!" lang
))
703 (with-temp-buffer (insert (org-babel-trim body
))
704 (copy-region-as-kill (point-min) (point-max)))
706 (unless (fboundp prep-cmd
)
707 (error "No org-babel-prep-session function for %s!" lang
))
708 (funcall prep-cmd session params
))
709 (funcall init-cmd session params
)))
712 (defun org-babel-switch-to-session (&optional arg info
)
713 "Switch to the session of the current code block.
714 Uses `org-babel-initiate-session' to start the session. If called
715 with a prefix argument then this is passed on to
716 `org-babel-initiate-session'."
718 (pop-to-buffer (org-babel-initiate-session arg info
))
721 (defalias 'org-babel-pop-to-session
'org-babel-switch-to-session
)
724 (defun org-babel-switch-to-session-with-code (&optional arg info
)
725 "Switch to code buffer and display session."
729 (let ((other-window-buffer (window-buffer (next-window))))
730 (set-window-buffer (next-window) (current-buffer))
731 (set-window-buffer (selected-window) other-window-buffer
))
733 (let ((info (org-babel-get-src-block-info))
734 (org-src-window-setup 'reorganize-frame
))
736 (org-babel-switch-to-session arg info
))
740 (defmacro org-babel-do-in-edit-buffer
(&rest body
)
741 "Evaluate BODY in edit buffer if there is a code block at point.
742 Return t if a code block was found at point, nil otherwise."
743 `(let ((org-src-window-setup 'switch-invisibly
))
744 (when (and (org-babel-where-is-src-block-head)
745 (org-edit-src-code nil nil nil
))
746 (unwind-protect (progn ,@body
)
747 (if (org-bound-and-true-p org-edit-src-from-org-mode
)
748 (org-edit-src-exit)))
750 (def-edebug-spec org-babel-do-in-edit-buffer
(body))
752 (defun org-babel-do-key-sequence-in-edit-buffer (key)
753 "Read key sequence and execute the command in edit buffer.
754 Enter a key sequence to be executed in the language major-mode
755 edit buffer. For example, TAB will alter the contents of the
756 Org-mode code block according to the effect of TAB in the
757 language major-mode buffer. For languages that support
758 interactive sessions, this can be used to send code from the Org
759 buffer to the session for evaluation using the native major-mode
760 evaluation mechanisms."
761 (interactive "kEnter key-sequence to execute in edit buffer: ")
762 (org-babel-do-in-edit-buffer
764 (key-binding (or key
(read-key-sequence nil
))))))
766 (defvar org-bracket-link-regexp
)
768 (defun org-babel-open-src-block-result (&optional re-run
)
769 "If `point' is on a src block then open the results of the
770 source code block, otherwise return nil. With optional prefix
771 argument RE-RUN the source-code block is evaluated even if
772 results already exist."
774 (let ((info (org-babel-get-src-block-info)))
777 ;; go to the results, if there aren't any then run the block
778 (goto-char (or (and (not re-run
) (org-babel-where-is-src-block-result))
779 (progn (org-babel-execute-src-block)
780 (org-babel-where-is-src-block-result))))
782 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
784 (if (looking-at org-bracket-link-regexp
)
787 (let ((r (org-babel-format-result
788 (org-babel-read-result) (cdr (assoc :sep
(nth 2 info
))))))
789 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
790 (delete-region (point-min) (point-max))
795 (defmacro org-babel-map-src-blocks
(file &rest body
)
796 "Evaluate BODY forms on each source-block in FILE.
797 If FILE is nil evaluate BODY forms on source blocks in current
798 buffer. During evaluation of BODY the following local variables
799 are set relative to the currently matched code block.
801 full-block ------- string holding the entirety of the code block
802 beg-block -------- point at the beginning of the code block
803 end-block -------- point at the end of the matched code block
804 lang ------------- string holding the language of the code block
805 beg-lang --------- point at the beginning of the lang
806 end-lang --------- point at the end of the lang
807 switches --------- string holding the switches
808 beg-switches ----- point at the beginning of the switches
809 end-switches ----- point at the end of the switches
810 header-args ------ string holding the header-args
811 beg-header-args -- point at the beginning of the header-args
812 end-header-args -- point at the end of the header-args
813 body ------------- string holding the body of the code block
814 beg-body --------- point at the beginning of the body
815 end-body --------- point at the end of the body"
817 (let ((tempvar (make-symbol "file")))
818 `(let* ((,tempvar
,file
)
819 (visited-p (or (null ,tempvar
)
820 (get-file-buffer (expand-file-name ,tempvar
))))
821 (point (point)) to-be-removed
)
822 (save-window-excursion
823 (when ,tempvar
(find-file ,tempvar
))
824 (setq to-be-removed
(current-buffer))
825 (goto-char (point-min))
826 (while (re-search-forward org-babel-src-block-regexp nil t
)
827 (goto-char (match-beginning 0))
828 (let ((full-block (match-string 0))
829 (beg-block (match-beginning 0))
830 (end-block (match-end 0))
831 (lang (match-string 2))
832 (beg-lang (match-beginning 2))
833 (end-lang (match-end 2))
834 (switches (match-string 3))
835 (beg-switches (match-beginning 3))
836 (end-switches (match-end 3))
837 (header-args (match-string 4))
838 (beg-header-args (match-beginning 4))
839 (end-header-args (match-end 4))
840 (body (match-string 5))
841 (beg-body (match-beginning 5))
842 (end-body (match-end 5)))
844 (goto-char end-block
))))
845 (unless visited-p
(kill-buffer to-be-removed
))
847 (def-edebug-spec org-babel-map-src-blocks
(form body
))
850 (defmacro org-babel-map-inline-src-blocks
(file &rest body
)
851 "Evaluate BODY forms on each inline source-block in FILE.
852 If FILE is nil evaluate BODY forms on source blocks in current
855 (let ((tempvar (make-symbol "file")))
856 `(let* ((,tempvar
,file
)
857 (visited-p (or (null ,tempvar
)
858 (get-file-buffer (expand-file-name ,tempvar
))))
859 (point (point)) to-be-removed
)
860 (save-window-excursion
861 (when ,tempvar
(find-file ,tempvar
))
862 (setq to-be-removed
(current-buffer))
863 (goto-char (point-min))
864 (while (re-search-forward org-babel-inline-src-block-regexp nil t
)
865 (goto-char (match-beginning 1))
866 (save-match-data ,@body
)
867 (goto-char (match-end 0))))
868 (unless visited-p
(kill-buffer to-be-removed
))
870 (def-edebug-spec org-babel-map-inline-src-blocks
(form body
))
872 (defvar org-babel-lob-one-liner-regexp
)
874 (defmacro org-babel-map-call-lines
(file &rest body
)
875 "Evaluate BODY forms on each call line in FILE.
876 If FILE is nil evaluate BODY forms on source blocks in current
879 (let ((tempvar (make-symbol "file")))
880 `(let* ((,tempvar
,file
)
881 (visited-p (or (null ,tempvar
)
882 (get-file-buffer (expand-file-name ,tempvar
))))
883 (point (point)) to-be-removed
)
884 (save-window-excursion
885 (when ,tempvar
(find-file ,tempvar
))
886 (setq to-be-removed
(current-buffer))
887 (goto-char (point-min))
888 (while (re-search-forward org-babel-lob-one-liner-regexp nil t
)
889 (goto-char (match-beginning 1))
890 (save-match-data ,@body
)
891 (goto-char (match-end 0))))
892 (unless visited-p
(kill-buffer to-be-removed
))
894 (def-edebug-spec org-babel-map-call-lines
(form body
))
897 (defmacro org-babel-map-executables
(file &rest body
)
899 (let ((tempvar (make-symbol "file"))
900 (rx (make-symbol "rx")))
901 `(let* ((,tempvar
,file
)
902 (,rx
(concat "\\(" org-babel-src-block-regexp
903 "\\|" org-babel-inline-src-block-regexp
904 "\\|" org-babel-lob-one-liner-regexp
"\\)"))
905 (visited-p (or (null ,tempvar
)
906 (get-file-buffer (expand-file-name ,tempvar
))))
907 (point (point)) to-be-removed
)
908 (save-window-excursion
909 (when ,tempvar
(find-file ,tempvar
))
910 (setq to-be-removed
(current-buffer))
911 (goto-char (point-min))
912 (while (re-search-forward ,rx nil t
)
913 (goto-char (match-beginning 1))
914 (when (looking-at org-babel-inline-src-block-regexp
)(forward-char 1))
915 (save-match-data ,@body
)
916 (goto-char (match-end 0))))
917 (unless visited-p
(kill-buffer to-be-removed
))
919 (def-edebug-spec org-babel-map-executables
(form body
))
922 (defun org-babel-execute-buffer (&optional arg
)
923 "Execute source code blocks in a buffer.
924 Call `org-babel-execute-src-block' on every source block in
927 (org-babel-eval-wipe-error-buffer)
928 (org-save-outline-visibility t
929 (org-babel-map-executables nil
930 (if (looking-at org-babel-lob-one-liner-regexp
)
931 (org-babel-lob-execute-maybe)
932 (org-babel-execute-src-block arg
)))))
935 (defun org-babel-execute-subtree (&optional arg
)
936 "Execute source code blocks in a subtree.
937 Call `org-babel-execute-src-block' on every source block in
938 the current subtree."
942 (org-narrow-to-subtree)
943 (org-babel-execute-buffer arg
)
947 (defun org-babel-sha1-hash (&optional info
)
948 "Generate an sha1 hash based on the value of info."
950 (let ((print-level nil
)
951 (info (or info
(org-babel-get-src-block-info))))
953 (sort (copy-sequence (nth 2 info
))
954 (lambda (a b
) (string< (car a
) (car b
)))))
956 (dolist (p '("replace" "silent" "append" "prepend"))
957 (setq lst
(remove p lst
)))
960 (let ((v (if (and (listp (cdr arg
)) (null (cddr arg
)))
961 (copy-sequence (cdr arg
))
963 (when (and v
(not (and (sequencep v
)
967 ((and (listp v
) ; lists are sorted
968 (member (car arg
) '(:result-params
)))
969 (sort (rm v
) #'string
<))
970 ((and (stringp v
) ; strings are sorted
971 (member (car arg
) '(:results
:exports
)))
972 (mapconcat #'identity
(sort (rm (split-string v
))
976 (when (org-called-interactively-p 'interactive
) (message hash
)) hash
)
977 (let ((it (format "%s-%s"
980 (delq nil
(mapcar (lambda (arg)
981 (let ((normalized (norm arg
)))
983 (format "%S" normalized
))))
988 (defun org-babel-current-result-hash ()
989 "Return the in-buffer hash associated with INFO."
990 (org-babel-where-is-src-block-result)
991 (org-babel-clean-text-properties (match-string 3)))
993 (defun org-babel-hide-hash ()
994 "Hide the hash in the current results line.
995 Only the initial `org-babel-hash-show' characters of the hash
996 will remain visible."
997 (add-to-invisibility-spec '(org-babel-hide-hash . t
))
999 (when (and (re-search-forward org-babel-result-regexp nil t
)
1001 (let* ((start (match-beginning 3))
1002 (hide-start (+ org-babel-hash-show start
))
1004 (hash (match-string 3))
1006 (setq ov1
(make-overlay start hide-start
))
1007 (setq ov2
(make-overlay hide-start end
))
1008 (overlay-put ov2
'invisible
'org-babel-hide-hash
)
1009 (overlay-put ov1
'babel-hash hash
)))))
1011 (defun org-babel-hide-all-hashes ()
1012 "Hide the hash in the current buffer.
1013 Only the initial `org-babel-hash-show' characters of each hash
1014 will remain visible. This function should be called as part of
1015 the `org-mode-hook'."
1017 (while (re-search-forward org-babel-result-regexp nil t
)
1018 (goto-char (match-beginning 0))
1019 (org-babel-hide-hash)
1020 (goto-char (match-end 0)))))
1021 (add-hook 'org-mode-hook
'org-babel-hide-all-hashes
)
1023 (defun org-babel-hash-at-point (&optional point
)
1024 "Return the value of the hash at POINT.
1025 The hash is also added as the last element of the kill ring.
1026 This can be called with C-c C-c."
1028 (let ((hash (car (delq nil
(mapcar
1029 (lambda (ol) (overlay-get ol
'babel-hash
))
1030 (overlays-at (or point
(point))))))))
1031 (when hash
(kill-new hash
) (message hash
))))
1032 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-hash-at-point
)
1034 (defun org-babel-result-hide-spec ()
1035 "Hide portions of results lines.
1036 Add `org-babel-hide-result' as an invisibility spec for hiding
1037 portions of results lines."
1038 (add-to-invisibility-spec '(org-babel-hide-result . t
)))
1039 (add-hook 'org-mode-hook
'org-babel-result-hide-spec
)
1041 (defvar org-babel-hide-result-overlays nil
1042 "Overlays hiding results.")
1044 (defun org-babel-result-hide-all ()
1045 "Fold all results in the current buffer."
1047 (org-babel-show-result-all)
1049 (while (re-search-forward org-babel-result-regexp nil t
)
1050 (save-excursion (goto-char (match-beginning 0))
1051 (org-babel-hide-result-toggle-maybe)))))
1053 (defun org-babel-show-result-all ()
1054 "Unfold all results in the current buffer."
1055 (mapc 'delete-overlay org-babel-hide-result-overlays
)
1056 (setq org-babel-hide-result-overlays nil
))
1059 (defun org-babel-hide-result-toggle-maybe ()
1060 "Toggle visibility of result at point."
1062 (let ((case-fold-search t
))
1064 (beginning-of-line 1)
1065 (looking-at org-babel-result-regexp
))
1066 (progn (org-babel-hide-result-toggle)
1067 t
) ;; to signal that we took action
1068 nil
))) ;; to signal that we did not
1070 (defun org-babel-hide-result-toggle (&optional force
)
1071 "Toggle the visibility of the current result."
1075 (if (re-search-forward org-babel-result-regexp nil t
)
1076 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
1078 (while (looking-at org-babel-multi-line-header-regexp
)
1080 (goto-char (- (org-babel-result-end) 1)) (point)))
1082 (if (memq t
(mapcar (lambda (overlay)
1083 (eq (overlay-get overlay
'invisible
)
1084 'org-babel-hide-result
))
1085 (overlays-at start
)))
1086 (if (or (not force
) (eq force
'off
))
1088 (when (member ov org-babel-hide-result-overlays
)
1089 (setq org-babel-hide-result-overlays
1090 (delq ov org-babel-hide-result-overlays
)))
1091 (when (eq (overlay-get ov
'invisible
)
1092 'org-babel-hide-result
)
1093 (delete-overlay ov
)))
1094 (overlays-at start
)))
1095 (setq ov
(make-overlay start end
))
1096 (overlay-put ov
'invisible
'org-babel-hide-result
)
1097 ;; make the block accessible to isearch
1099 ov
'isearch-open-invisible
1101 (when (member ov org-babel-hide-result-overlays
)
1102 (setq org-babel-hide-result-overlays
1103 (delq ov org-babel-hide-result-overlays
)))
1104 (when (eq (overlay-get ov
'invisible
)
1105 'org-babel-hide-result
)
1106 (delete-overlay ov
))))
1107 (push ov org-babel-hide-result-overlays
)))
1108 (error "Not looking at a result line"))))
1110 ;; org-tab-after-check-for-cycling-hook
1111 (add-hook 'org-tab-first-hook
'org-babel-hide-result-toggle-maybe
)
1112 ;; Remove overlays when changing major mode
1113 (add-hook 'org-mode-hook
1114 (lambda () (org-add-hook 'change-major-mode-hook
1115 'org-babel-show-result-all
'append
'local
)))
1117 (defvar org-file-properties
)
1118 (defun org-babel-params-from-properties (&optional lang
)
1119 "Retrieve parameters specified as properties.
1120 Return an association list of any source block params which
1121 may be specified in the properties of the current outline entry."
1124 (org-babel-parse-multiple-vars
1127 (lambda (header-arg)
1128 (and (setq val
(org-entry-get (point) header-arg t
))
1129 (cons (intern (concat ":" header-arg
))
1130 (org-babel-read val
))))
1134 org-babel-header-arg-names
1136 (setq sym
(intern (concat "org-babel-header-arg-names:"
1138 (and (boundp sym
) (eval sym
)))))))))))
1140 (defvar org-src-preserve-indentation
)
1141 (defun org-babel-parse-src-block-match ()
1142 "Parse the results from a match of the `org-babel-src-block-regexp'."
1143 (let* ((block-indentation (length (match-string 1)))
1144 (lang (org-babel-clean-text-properties (match-string 2)))
1145 (lang-headers (intern (concat "org-babel-default-header-args:" lang
)))
1146 (switches (match-string 3))
1147 (body (org-babel-clean-text-properties
1148 (let* ((body (match-string 5))
1149 (sub-length (- (length body
) 1)))
1150 (if (and (> sub-length
0)
1151 (string= "\n" (substring body sub-length
)))
1152 (substring body
0 sub-length
)
1154 (preserve-indentation (or org-src-preserve-indentation
1155 (string-match "-i\\>" switches
))))
1157 ;; get block body less properties, protective commas, and indentation
1160 (insert (org-babel-strip-protective-commas body
))
1161 (unless preserve-indentation
(org-do-remove-indentation))
1163 (org-babel-merge-params
1164 org-babel-default-header-args
1165 (org-babel-params-from-properties lang
)
1166 (if (boundp lang-headers
) (eval lang-headers
) nil
)
1167 (org-babel-parse-header-arguments
1168 (org-babel-clean-text-properties (or (match-string 4) ""))))
1170 block-indentation
)))
1172 (defun org-babel-parse-inline-src-block-match ()
1173 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
1174 (let* ((lang (org-babel-clean-text-properties (match-string 2)))
1175 (lang-headers (intern (concat "org-babel-default-header-args:" lang
))))
1177 (org-babel-strip-protective-commas
1178 (org-babel-clean-text-properties (match-string 5)))
1179 (org-babel-merge-params
1180 org-babel-default-inline-header-args
1181 (org-babel-params-from-properties lang
)
1182 (if (boundp lang-headers
) (eval lang-headers
) nil
)
1183 (org-babel-parse-header-arguments
1184 (org-babel-clean-text-properties (or (match-string 4) "")))))))
1186 (defun org-babel-balanced-split (string alts
)
1187 "Split STRING on instances of ALTS.
1188 ALTS is a cons of two character options where each option may be
1189 either the numeric code of a single character or a list of
1190 character alternatives. For example to split on balanced
1191 instances of \"[ \t]:\" set ALTS to '((32 9) . 58)."
1192 (flet ((matches (ch spec
) (if (listp spec
) (member ch spec
) (equal spec ch
)))
1195 (and (matches ch
(cdr alts
))
1196 (matches last
(car alts
)))
1197 (matches ch alts
))))
1198 (let ((balance 0) (quote nil
) (partial nil
) (lst nil
) (last 0))
1199 (mapc (lambda (ch) ; split on [], (), "" balanced instances of [ \t]:
1200 (setq balance
(+ balance
1201 (cond ((or (equal 91 ch
) (equal 40 ch
)) 1)
1202 ((or (equal 93 ch
) (equal 41 ch
)) -
1)
1204 (when (and (equal 34 ch
) (not (equal 92 last
)))
1205 (setq quote
(not quote
)))
1206 (setq partial
(cons ch partial
))
1207 (when (and (= balance
0) (not quote
) (matched ch last
))
1208 (setq lst
(cons (apply #'string
(nreverse
1215 (string-to-list string
))
1216 (nreverse (cons (apply #'string
(nreverse partial
)) lst
)))))
1218 (defun org-babel-join-splits-near-ch (ch list
)
1219 "Join splits where \"=\" is on either end of the split."
1220 (flet ((last= (str) (= ch
(aref str
(1- (length str
)))))
1221 (first= (str) (= ch
(aref str
0))))
1223 (org-reduce (lambda (acc el
)
1224 (let ((head (car acc
)))
1225 (if (and head
(or (last= head
) (first= el
)))
1226 (cons (concat head el
) (cdr acc
))
1228 list
:initial-value nil
))))
1230 (defun org-babel-parse-header-arguments (arg-string)
1231 "Parse a string of header arguments returning an alist."
1232 (when (> (length arg-string
) 0)
1233 (org-babel-parse-multiple-vars
1238 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1240 (cons (intern (match-string 1 arg
))
1241 (org-babel-read (org-babel-chomp (match-string 2 arg
))))
1242 (cons (intern (org-babel-chomp arg
)) nil
)))
1244 (cons (car raw
) (mapcar (lambda (r) (concat ":" r
)) (cdr raw
))))
1245 (org-babel-balanced-split arg-string
'((32 9) .
58))))))))
1247 (defun org-babel-parse-multiple-vars (header-arguments)
1248 "Expand multiple variable assignments behind a single :var keyword.
1250 This allows expression of multiple variables with one :var as
1253 #+PROPERTY: var foo=1, bar=2"
1255 (mapc (lambda (pair)
1256 (if (eq (car pair
) :var
)
1257 (mapcar (lambda (v) (push (cons :var
(org-babel-trim v
)) results
))
1258 (org-babel-join-splits-near-ch
1259 61 (org-babel-balanced-split (cdr pair
) 32)))
1260 (push pair results
)))
1262 (nreverse results
)))
1264 (defun org-babel-process-params (params)
1265 "Expand variables in PARAMS and add summary parameters."
1266 (let* ((processed-vars (mapcar (lambda (el)
1267 (if (consp (cdr el
))
1269 (org-babel-ref-parse (cdr el
))))
1270 (org-babel-get-header params
:var
)))
1271 (vars-and-names (if (and (assoc :colname-names params
)
1272 (assoc :rowname-names params
))
1273 (list processed-vars
)
1274 (org-babel-disassemble-tables
1276 (cdr (assoc :hlines params
))
1277 (cdr (assoc :colnames params
))
1278 (cdr (assoc :rownames params
)))))
1279 (raw-result (or (cdr (assoc :results params
)) ""))
1280 (result-params (append
1281 (split-string (if (stringp raw-result
)
1284 (cdr (assoc :result-params params
)))))
1286 (mapcar (lambda (var) (cons :var var
)) (car vars-and-names
))
1288 (cons :colname-names
(or (cdr (assoc :colname-names params
))
1289 (cadr vars-and-names
)))
1290 (cons :rowname-names
(or (cdr (assoc :rowname-names params
))
1291 (caddr vars-and-names
)))
1292 (cons :result-params result-params
)
1293 (cons :result-type
(cond ((member "output" result-params
) 'output
)
1294 ((member "value" result-params
) 'value
)
1296 (org-babel-get-header params
:var
'other
))))
1298 ;; row and column names
1299 (defun org-babel-del-hlines (table)
1300 "Remove all 'hlines from TABLE."
1301 (remove 'hline table
))
1303 (defun org-babel-get-colnames (table)
1304 "Return the column names of TABLE.
1305 Return a cons cell, the `car' of which contains the TABLE less
1306 colnames, and the `cdr' of which contains a list of the column
1308 (if (equal 'hline
(nth 1 table
))
1309 (cons (cddr table
) (car table
))
1310 (cons (cdr table
) (car table
))))
1312 (defun org-babel-get-rownames (table)
1313 "Return the row names of TABLE.
1314 Return a cons cell, the `car' of which contains the TABLE less
1315 colnames, and the `cdr' of which contains a list of the column
1316 names. Note: this function removes any hlines in TABLE."
1317 (flet ((trans (table) (apply #'mapcar
* #'list table
)))
1318 (let* ((width (apply 'max
1319 (mapcar (lambda (el) (if (listp el
) (length el
) 0)) table
)))
1320 (table (trans (mapcar (lambda (row)
1321 (if (not (equal row
'hline
))
1325 (setq row
(cons 'hline row
)))
1328 (cons (mapcar (lambda (row) (if (equal (car row
) 'hline
) 'hline row
))
1329 (trans (cdr table
)))
1330 (remove 'hline
(car table
))))))
1332 (defun org-babel-put-colnames (table colnames
)
1333 "Add COLNAMES to TABLE if they exist."
1334 (if colnames
(apply 'list colnames
'hline table
) table
))
1336 (defun org-babel-put-rownames (table rownames
)
1337 "Add ROWNAMES to TABLE if they exist."
1339 (mapcar (lambda (row)
1341 (cons (or (pop rownames
) "") row
)
1345 (defun org-babel-pick-name (names selector
)
1346 "Select one out of an alist of row or column names.
1347 SELECTOR can be either a list of names in which case those names
1348 will be returned directly, or an index into the list NAMES in
1349 which case the indexed names will be return."
1350 (if (listp selector
)
1353 (if (and selector
(symbolp selector
) (not (equal t selector
)))
1354 (cdr (assoc selector names
))
1355 (if (integerp selector
)
1356 (nth (- selector
1) names
)
1357 (cdr (car (last names
))))))))
1359 (defun org-babel-disassemble-tables (vars hlines colnames rownames
)
1360 "Parse tables for further processing.
1361 Process the variables in VARS according to the HLINES,
1362 ROWNAMES and COLNAMES header arguments. Return a list consisting
1363 of the vars, cnames and rnames."
1364 (let (cnames rnames
)
1368 (when (listp (cdr var
))
1369 (when (and (not (equal colnames
"no"))
1370 (or colnames
(and (equal (nth 1 (cdr var
)) 'hline
)
1371 (not (member 'hline
(cddr (cdr var
)))))))
1372 (let ((both (org-babel-get-colnames (cdr var
))))
1373 (setq cnames
(cons (cons (car var
) (cdr both
))
1375 (setq var
(cons (car var
) (car both
)))))
1376 (when (and rownames
(not (equal rownames
"no")))
1377 (let ((both (org-babel-get-rownames (cdr var
))))
1378 (setq rnames
(cons (cons (car var
) (cdr both
))
1380 (setq var
(cons (car var
) (car both
)))))
1381 (when (and hlines
(not (equal hlines
"yes")))
1382 (setq var
(cons (car var
) (org-babel-del-hlines (cdr var
))))))
1385 (reverse cnames
) (reverse rnames
))))
1387 (defun org-babel-reassemble-table (table colnames rownames
)
1388 "Add column and row names to a table.
1389 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1390 to the table for reinsertion to org-mode."
1393 (if (and colnames
(listp (car table
)) (= (length (car table
))
1395 (org-babel-put-colnames table colnames
) table
))
1396 (if (and rownames
(= (length table
) (length rownames
)))
1397 (org-babel-put-rownames table rownames
) table
))
1400 (defun org-babel-where-is-src-block-head ()
1401 "Find where the current source block begins.
1402 Return the point at the beginning of the current source
1403 block. Specifically at the beginning of the #+BEGIN_SRC line.
1404 If the point is not on a source block then return nil."
1405 (let ((initial (point)) top bottom
)
1407 (save-excursion ;; on a source name line or a #+header line
1408 (beginning-of-line 1)
1409 (and (or (looking-at org-babel-src-name-regexp
)
1410 (looking-at org-babel-multi-line-header-regexp
))
1412 (while (and (forward-line 1)
1413 (looking-at org-babel-multi-line-header-regexp
)))
1414 (looking-at org-babel-src-block-regexp
))
1416 (save-excursion ;; on a #+begin_src line
1417 (beginning-of-line 1)
1418 (and (looking-at org-babel-src-block-regexp
)
1420 (save-excursion ;; inside a src block
1422 (re-search-backward "^[ \t]*#\\+begin_src" nil t
) (setq top
(point))
1423 (re-search-forward "^[ \t]*#\\+end_src" nil t
) (setq bottom
(point))
1424 (< top initial
) (< initial bottom
)
1425 (progn (goto-char top
) (beginning-of-line 1)
1426 (looking-at org-babel-src-block-regexp
))
1430 (defun org-babel-goto-src-block-head ()
1431 "Go to the beginning of the current code block."
1434 (if head
(goto-char head
) (error "not currently in a code block")))
1435 (org-babel-where-is-src-block-head)))
1438 (defun org-babel-goto-named-src-block (name)
1439 "Go to a named source-code block."
1441 (let ((completion-ignore-case t
))
1442 (list (org-icompleting-read "source-block name: "
1443 (org-babel-src-block-names) nil t
))))
1444 (let ((point (org-babel-find-named-block name
)))
1446 ;; taken from `org-open-at-point'
1447 (progn (goto-char point
) (org-show-context))
1448 (message "source-code block '%s' not found in this buffer" name
))))
1450 (defun org-babel-find-named-block (name)
1451 "Find a named source-code block.
1452 Return the location of the source block identified by source
1453 NAME, or nil if no such block exists. Set match data according to
1454 org-babel-named-src-block-regexp."
1456 (let ((case-fold-search t
)
1457 (regexp (org-babel-named-src-block-regexp-for-name name
)) msg
)
1458 (goto-char (point-min))
1459 (when (or (re-search-forward regexp nil t
)
1460 (re-search-backward regexp nil t
))
1461 (match-beginning 0)))))
1463 (defun org-babel-src-block-names (&optional file
)
1464 "Returns the names of source blocks in FILE or the current buffer."
1466 (when file
(find-file file
)) (goto-char (point-min))
1468 (while (re-search-forward org-babel-src-name-w-name-regexp nil t
)
1469 (setq names
(cons (match-string 3) names
)))
1473 (defun org-babel-goto-named-result (name)
1474 "Go to a named result."
1476 (let ((completion-ignore-case t
))
1477 (list (org-icompleting-read "source-block name: "
1478 (org-babel-result-names) nil t
))))
1479 (let ((point (org-babel-find-named-result name
)))
1481 ;; taken from `org-open-at-point'
1482 (progn (goto-char point
) (org-show-context))
1483 (message "result '%s' not found in this buffer" name
))))
1485 (defun org-babel-find-named-result (name &optional point
)
1486 "Find a named result.
1487 Return the location of the result named NAME in the current
1488 buffer or nil if no such result exists."
1490 (goto-char (or point
(point-min)))
1491 (catch 'is-a-code-block
1492 (when (re-search-forward
1493 (concat org-babel-result-regexp
1494 "[ \t]" (regexp-quote name
) "[ \t\n\f\v\r]") nil t
)
1495 (when (and (string= "name" (downcase (match-string 1)))
1496 (or (looking-at org-babel-src-block-regexp
)
1497 (looking-at org-babel-multi-line-header-regexp
)))
1498 (throw 'is-a-code-block
(org-babel-find-named-result name
(point))))
1499 (beginning-of-line 0) (point)))))
1501 (defun org-babel-result-names (&optional file
)
1502 "Returns the names of results in FILE or the current buffer."
1504 (when file
(find-file file
)) (goto-char (point-min))
1506 (while (re-search-forward org-babel-result-w-name-regexp nil t
)
1507 (setq names
(cons (match-string 4) names
)))
1511 (defun org-babel-next-src-block (&optional arg
)
1512 "Jump to the next source block.
1513 With optional prefix argument ARG, jump forward ARG many source blocks."
1515 (when (looking-at org-babel-src-block-regexp
) (forward-char 1))
1517 (re-search-forward org-babel-src-block-regexp nil nil
(or arg
1))
1518 (error (error "No further code blocks")))
1519 (goto-char (match-beginning 0)) (org-show-context))
1522 (defun org-babel-previous-src-block (&optional arg
)
1523 "Jump to the previous source block.
1524 With optional prefix argument ARG, jump backward ARG many source blocks."
1527 (re-search-backward org-babel-src-block-regexp nil nil
(or arg
1))
1528 (error (error "No previous code blocks")))
1529 (goto-char (match-beginning 0)) (org-show-context))
1531 (defvar org-babel-load-languages
)
1534 (defun org-babel-mark-block ()
1535 "Mark current src block"
1541 (looking-at org-babel-src-block-regexp
))
1542 (push-mark (match-end 5) nil t
)
1543 (goto-char (match-beginning 5))))
1544 (org-babel-where-is-src-block-head)))
1546 (defun org-babel-demarcate-block (&optional arg
)
1547 "Wrap or split the code in the region or on the point.
1548 When called from inside of a code block the current block is
1549 split. When called from outside of a code block a new code block
1550 is created. In both cases if the region is demarcated and if the
1551 region is not active then the point is demarcated."
1553 (let ((info (org-babel-get-src-block-info 'light
))
1554 (headers (progn (org-babel-where-is-src-block-head)
1556 (stars (concat (make-string (or (org-current-level) 1) ?
*) " ")))
1562 (let ((lang (nth 0 info
))
1563 (indent (make-string (nth 5 info
) ?
)))
1564 (when (string-match "^[[:space:]]*$"
1565 (buffer-substring (point-at-bol)
1567 (delete-region (point-at-bol) (point-at-eol)))
1569 (if (looking-at "^") "" "\n")
1570 indent
"#+end_src\n"
1571 (if arg stars indent
) "\n"
1572 indent
"#+begin_src " lang
1573 (if (> (length headers
) 1)
1574 (concat " " headers
) headers
)
1575 (if (looking-at "[\n\r]")
1577 (concat "\n" (make-string (current-column) ?
)))))))
1578 (move-end-of-line 2))
1579 (sort (if (region-active-p) (list (mark) (point)) (list (point))) #'>))
1580 (let ((start (point))
1581 (lang (org-icompleting-read "Lang: "
1582 (mapcar (lambda (el) (symbol-name (car el
)))
1583 org-babel-load-languages
)))
1584 (body (delete-and-extract-region
1585 (if (region-active-p) (mark) (point)) (point))))
1586 (insert (concat (if (looking-at "^") "" "\n")
1587 (if arg
(concat stars
"\n") "")
1588 "#+begin_src " lang
"\n"
1590 (if (or (= (length body
) 0)
1591 (string-match "[\r\n]$" body
)) "" "\n")
1593 (goto-char start
) (move-end-of-line 1)))))
1595 (defvar org-babel-lob-one-liner-regexp
)
1596 (defun org-babel-where-is-src-block-result (&optional insert info hash indent
)
1597 "Find where the current source block results begin.
1598 Return the point at the beginning of the result of the current
1599 source block. Specifically at the beginning of the results line.
1600 If no result exists for this block then create a results line
1601 following the source block."
1603 (let* ((on-lob-line (save-excursion
1604 (beginning-of-line 1)
1605 (looking-at org-babel-lob-one-liner-regexp
)))
1606 (inlinep (when (org-babel-get-inline-src-block-matches)
1608 (name (if on-lob-line
1609 (nth 0 (org-babel-lob-get-info))
1610 (nth 4 (or info
(org-babel-get-src-block-info 'light
)))))
1611 (head (unless on-lob-line
(org-babel-where-is-src-block-head)))
1613 (when head
(goto-char head
))
1615 found
;; was there a result (before we potentially insert one)
1620 ;; - return t if it is found, else return nil
1621 ;; - if it does not need to be rebuilt, then don't set end
1622 ;; - if it does need to be rebuilt then do set end
1623 name
(setq beg
(org-babel-find-named-result name
))
1625 (when (and hash
(not (string= hash
(match-string 3))))
1626 (goto-char beg
) (setq end beg
) ;; beginning of result
1628 (delete-region end
(org-babel-result-end)) nil
)))
1631 ;; - return t if it is found, else return nil
1632 ;; - if it is found, and the hash doesn't match, delete and set end
1633 (or on-lob-line
(re-search-forward "^[ \t]*#\\+end_src" nil t
))
1634 (progn (end-of-line 1)
1635 (if (eobp) (insert "\n") (forward-char 1))
1638 (progn ;; unnamed results line already exists
1639 (re-search-forward "[^ \f\t\n\r\v]" nil t
)
1640 (beginning-of-line 1)
1642 (concat org-babel-result-regexp
"\n")))
1644 ;; must remove and rebuild if hash!=old-hash
1645 (if (and hash
(not (string= hash
(match-string 3))))
1649 end
(org-babel-result-end)))
1650 (setq end nil
)))))))))
1651 (if (and insert end
)
1655 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1660 (org-number-sequence 1 indent
) "")
1662 "#+" org-babel-results-keyword
1663 (when hash
(concat "["hash
"]"))
1665 (when name
(concat " " name
)) "\n"))
1666 (unless beg
(insert "\n") (backward-char))
1667 (beginning-of-line 0)
1668 (if hash
(org-babel-hide-hash))
1672 (defvar org-block-regexp
)
1673 (defun org-babel-read-result ()
1674 "Read the result at `point' into emacs-lisp."
1675 (let ((case-fold-search t
) result-string
)
1677 ((org-at-table-p) (org-babel-read-table))
1678 ((org-at-item-p) (org-babel-read-list))
1679 ((looking-at org-bracket-link-regexp
) (org-babel-read-link))
1680 ((looking-at org-block-regexp
) (org-babel-trim (match-string 4)))
1681 ((looking-at "^[ \t]*: ")
1684 (mapconcat (lambda (line)
1685 (if (and (> (length line
) 1)
1686 (string-match "^[ \t]*: \\(.+\\)" line
))
1687 (match-string 1 line
)
1691 (point) (org-babel-result-end)) "[\r\n]+")
1693 (or (org-babel-number-p result-string
) result-string
))
1694 ((looking-at org-babel-result-regexp
)
1695 (save-excursion (forward-line 1) (org-babel-read-result))))))
1697 (defun org-babel-read-table ()
1698 "Read the table at `point' into emacs-lisp."
1699 (mapcar (lambda (row)
1700 (if (and (symbolp row
) (equal row
'hline
)) row
1701 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
)) row
)))
1702 (org-table-to-lisp)))
1704 (defun org-babel-read-list ()
1705 "Read the list at `point' into emacs-lisp."
1706 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
))
1707 (mapcar #'cadr
(cdr (org-list-parse-list)))))
1709 (defvar org-link-types-re
)
1710 (defun org-babel-read-link ()
1711 "Read the link at `point' into emacs-lisp.
1712 If the path of the link is a file path it is expanded using
1713 `expand-file-name'."
1714 (let* ((case-fold-search t
)
1715 (raw (and (looking-at org-bracket-link-regexp
)
1716 (org-babel-clean-text-properties (match-string 1))))
1717 (type (and (string-match org-link-types-re raw
)
1718 (match-string 1 raw
))))
1720 ((not type
) (expand-file-name raw
))
1721 ((string= type
"file")
1722 (and (string-match "file\\(.*\\):\\(.+\\)" raw
)
1723 (expand-file-name (match-string 2 raw
))))
1726 (defun org-babel-format-result (result &optional sep
)
1727 "Format RESULT for writing to file."
1728 (flet ((echo-res (result)
1729 (if (stringp result
) result
(format "%S" result
))))
1738 (echo-res result
))))
1740 (defun org-babel-insert-result
1741 (result &optional result-params info hash indent lang
)
1742 "Insert RESULT into the current buffer.
1743 By default RESULT is inserted after the end of the
1744 current source block. With optional argument RESULT-PARAMS
1745 controls insertion of results in the org-mode file.
1746 RESULT-PARAMS can take the following values...
1748 replace - (default option) insert results after the source block
1749 replacing any previously inserted results
1751 silent -- no results are inserted
1753 file ---- the results are interpreted as a file path, and are
1754 inserted into the buffer using the Org-mode file syntax
1756 list ---- the results are interpreted as an Org-mode list.
1758 raw ----- results are added directly to the Org-mode file. This
1759 is a good option if you code block will output org-mode
1762 wrap ---- results are added directly to the Org-mode file as with
1763 \"raw\", but are wrapped in a RESULTS drawer, allowing
1764 them to later be replaced or removed automatically.
1766 org ----- similar in effect to raw, only the results are wrapped
1767 in an org code block. Similar to the raw option, on
1768 export the results will be interpreted as org-formatted
1769 text, however by wrapping the results in an org code
1770 block they can be replaced upon re-execution of the
1773 html ---- results are added inside of a #+BEGIN_HTML block. This
1774 is a good option if you code block will output html
1777 latex --- results are added inside of a #+BEGIN_LATEX block.
1778 This is a good option if you code block will output
1779 latex formatted text.
1781 code ---- the results are extracted in the syntax of the source
1782 code of the language being evaluated and are added
1783 inside of a #+BEGIN_SRC block with the source-code
1784 language set appropriately. Note this relies on the
1785 optional LANG argument."
1786 (if (stringp result
)
1788 (setq result
(org-babel-clean-text-properties result
))
1789 (when (member "file" result-params
)
1790 (setq result
(org-babel-result-to-file result
))))
1791 (unless (listp result
) (setq result
(format "%S" result
))))
1792 (if (and result-params
(member "silent" result-params
))
1794 (message (replace-regexp-in-string "%" "%%" (format "%S" result
)))
1799 (when (or (org-babel-get-inline-src-block-matches)
1800 (org-babel-get-lob-one-liner-matches))
1801 (goto-char (match-end 0))
1802 (insert (if (listp result
) "\n" " "))
1804 (existing-result (unless inlinep
1805 (org-babel-where-is-src-block-result
1806 t info hash indent
)))
1808 (cdr (assoc :results_switches
(nth 2 info
))))
1810 (when (and (stringp result
) ; ensure results end in a newline
1812 (> (length result
) 0)
1813 (not (or (string-equal (substring result -
1) "\n")
1814 (string-equal (substring result -
1) "\r"))))
1815 (setq result
(concat result
"\n")))
1816 (if (not existing-result
)
1817 (setq beg
(or inlinep
(point)))
1818 (goto-char existing-result
)
1820 (re-search-forward "#" nil t
)
1821 (setq indent
(- (current-column) 1)))
1825 ((member "replace" result-params
)
1826 (delete-region (point) (org-babel-result-end)))
1827 ((member "append" result-params
)
1828 (goto-char (org-babel-result-end)) (setq beg
(point-marker)))
1829 ((member "prepend" result-params
)))) ; already there
1830 (setq results-switches
1831 (if results-switches
(concat " " results-switches
) ""))
1832 (flet ((wrap (start finish
)
1833 (goto-char beg
) (insert (concat start
"\n"))
1834 (goto-char end
) (insert (concat finish
"\n"))
1835 (setq end
(point-marker)))
1836 (proper-list-p (it) (and (listp it
) (null (cdr (last it
))))))
1837 ;; insert results based on type
1839 ;; do nothing for an empty result
1841 ;; insert a list if preferred
1842 ((member "list" result-params
)
1845 (org-list-to-generic
1848 (lambda (el) (list nil
(if (stringp el
) el
(format "%S" el
))))
1849 (if (listp result
) result
(list result
))))
1850 '(:splicep nil
:istart
"- " :iend
"\n")))
1852 ;; assume the result is a table if it's not a string
1853 ((proper-list-p result
)
1855 (insert (concat (orgtbl-to-orgtbl
1856 (if (or (eq 'hline
(car result
))
1857 (and (listp (car result
))
1858 (listp (cdr (car result
)))))
1859 result
(list result
))
1860 '(:fmt
(lambda (cell) (format "%s" cell
)))) "\n"))
1861 (goto-char beg
) (when (org-at-table-p) (org-table-align)))
1862 ((and (listp result
) (not (proper-list-p result
)))
1863 (insert (format "%s\n" result
)))
1864 ((member "file" result-params
)
1865 (when inlinep
(goto-char inlinep
))
1867 (t (goto-char beg
) (insert result
)))
1868 (when (proper-list-p result
) (goto-char (org-table-end)))
1869 (setq end
(point-marker))
1870 ;; possibly wrap result
1872 ((assoc :wrap
(nth 2 info
))
1873 (let ((name (or (cdr (assoc :wrap
(nth 2 info
))) "RESULTS")))
1874 (wrap (concat "#+BEGIN_" name
) (concat "#+END_" name
))))
1875 ((member "html" result-params
)
1876 (wrap "#+BEGIN_HTML" "#+END_HTML"))
1877 ((member "latex" result-params
)
1878 (wrap "#+BEGIN_LaTeX" "#+END_LaTeX"))
1879 ((member "code" result-params
)
1880 (wrap (format "#+BEGIN_SRC %s%s" (or lang
"none") results-switches
)
1882 ((member "org" result-params
)
1883 (wrap "#+BEGIN_ORG" "#+END_ORG"))
1884 ((member "raw" result-params
)
1885 (goto-char beg
) (if (org-at-table-p) (org-cycle)))
1886 ((member "wrap" result-params
)
1887 (wrap ":RESULTS:" ":END:"))
1888 ((and (not (proper-list-p result
))
1889 (not (member "file" result-params
)))
1890 (org-babel-examplize-region beg end results-switches
)
1891 (setq end
(point)))))
1892 ;; possibly indent the results to match the #+results line
1893 (when (and (not inlinep
) (numberp indent
) indent
(> indent
0)
1894 ;; in this case `table-align' does the work for us
1895 (not (and (listp result
)
1896 (member "append" result-params
))))
1897 (indent-rigidly beg end indent
))))
1899 (if (member "value" result-params
)
1900 (message "Code block returned no value.")
1901 (message "Code block produced no output."))
1902 (message "Code block evaluation complete."))))
1904 (defun org-babel-remove-result (&optional info
)
1905 "Remove the result of the current source block."
1907 (let ((location (org-babel-where-is-src-block-result nil info
)) start
)
1909 (setq start
(- location
1))
1911 (goto-char location
) (forward-line 1)
1912 (delete-region start
(org-babel-result-end))))))
1914 (defun org-babel-result-end ()
1915 "Return the point at the end of the current set of results"
1918 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
1919 ((org-at-item-p) (let* ((struct (org-list-struct))
1920 (prvs (org-list-prevs-alist struct
)))
1921 (org-list-get-list-end (point-at-bol) struct prvs
)))
1922 ((looking-at "^\\([ \t]*\\):RESULTS:")
1923 (re-search-forward (concat "^" (match-string 1) ":END:")))
1925 (let ((case-fold-search t
))
1926 (if (looking-at (concat "[ \t]*#\\+begin_\\([^ \t\n\r]+\\)"))
1927 (progn (re-search-forward (concat "[ \t]*#\\+end_" (match-string 1))
1930 (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
1934 (defun org-babel-result-to-file (result)
1935 "Convert RESULT into an `org-mode' link.
1936 If the `default-directory' is different from the containing
1937 file's directory then expand relative links."
1938 (flet ((cond-exp (file)
1939 (if (and default-directory
1941 (not (string= (expand-file-name default-directory
)
1943 (file-name-directory buffer-file-name
)))))
1944 (expand-file-name file default-directory
)
1946 (if (stringp result
)
1947 (format "[[file:%s]]" (cond-exp result
))
1948 (when (and (listp result
) (= 2 (length result
))
1949 (stringp (car result
)) (stringp (cadr result
)))
1950 (format "[[file:%s][%s]]" (car result
) (cadr result
))))))
1952 (defun org-babel-examplize-region (beg end
&optional results-switches
)
1953 "Comment out region using the inline '==' or ': ' org example quote."
1955 (flet ((chars-between (b e
) (string-match "[\\S]" (buffer-substring b e
))))
1956 (if (or (chars-between (save-excursion (goto-char beg
) (point-at-bol)) beg
)
1957 (chars-between end
(save-excursion (goto-char end
) (point-at-eol))))
1960 (insert (format "=%s=" (prog1 (buffer-substring beg end
)
1961 (delete-region beg end
)))))
1962 (let ((size (count-lines beg end
)))
1964 (cond ((= size
0)) ; do nothing for an empty result
1965 ((< size org-babel-min-lines-for-block-output
)
1968 (beginning-of-line 1) (insert ": ") (forward-line 1)))
1971 (insert (if results-switches
1972 (format "#+begin_example%s\n" results-switches
)
1973 "#+begin_example\n"))
1974 (if (markerp end
) (goto-char end
) (forward-char (- end beg
)))
1975 (insert "#+end_example\n"))))))))
1977 (defun org-babel-update-block-body (new-body)
1978 "Update the body of the current code block to NEW-BODY."
1979 (if (not (org-babel-where-is-src-block-head))
1980 (error "not in source block")
1982 (replace-match (concat (org-babel-trim new-body
) "\n") nil t nil
5))
1983 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
1985 (defun org-babel-merge-params (&rest plists
)
1986 "Combine all parameter association lists in PLISTS.
1987 Later elements of PLISTS override the values of previous elements.
1988 This takes into account some special considerations for certain
1989 parameters when merging lists."
1990 (let ((results-exclusive-groups
1991 (mapcar (lambda (group) (mapcar #'symbol-name group
))
1992 (cdr (assoc 'results org-babel-common-header-args-w-values
))))
1993 (exports-exclusive-groups
1994 (mapcar (lambda (group) (mapcar #'symbol-name group
))
1995 (cdr (assoc 'exports org-babel-common-header-args-w-values
))))
1997 params results exports tangle noweb cache vars shebang comments padline
)
1998 (flet ((e-merge (exclusive-groups &rest result-params
)
1999 ;; maintain exclusivity of mutually exclusive parameters
2001 (mapc (lambda (new-params)
2002 (mapc (lambda (new-param)
2003 (mapc (lambda (exclusive-group)
2004 (when (member new-param exclusive-group
)
2005 (mapcar (lambda (excluded-param)
2012 (setq output
(org-uniquify
2013 (cons new-param output
))))
2023 (let ((name (if (listp (cdr pair
))
2025 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
2027 (intern (match-string 1 (cdr pair
)))))))
2031 (if (member name
(mapcar #'car vars
))
2035 (unless (equal (car p
) name
) p
))
2038 (list (cons name pair
))))
2039 ;; if no name is given and we already have named variables
2040 ;; then assign to named variables in order
2041 (if (and vars
(nth variable-index vars
))
2042 (prog1 (setf (cddr (nth variable-index vars
))
2043 (concat (symbol-name
2044 (car (nth variable-index vars
)))
2046 (incf variable-index
))
2047 (error "variable \"%s\" must be assigned a default value"
2050 (setq results
(e-merge results-exclusive-groups
2053 (let ((r (cdr pair
)))
2054 (if (stringp r
) r
(eval r
)))))))
2057 (setq results
(e-merge results-exclusive-groups
2059 (unless (or (member "both" exports
)
2060 (member "none" exports
)
2061 (member "code" exports
))
2062 (setq exports
(e-merge exports-exclusive-groups
2063 exports
'("results"))))
2064 (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))
2066 (setq exports
(e-merge exports-exclusive-groups
2067 exports
(split-string (cdr pair
)))))
2068 (:tangle
;; take the latest -- always overwrite
2069 (setq tangle
(or (list (cdr pair
)) tangle
)))
2071 (setq noweb
(e-merge '(("yes" "no" "tangle" "no-export")) noweb
2072 (split-string (or (cdr pair
) "")))))
2074 (setq cache
(e-merge '(("yes" "no")) cache
2075 (split-string (or (cdr pair
) "")))))
2077 (setq padline
(e-merge '(("yes" "no")) padline
2078 (split-string (or (cdr pair
) "")))))
2079 (:shebang
;; take the latest -- always overwrite
2080 (setq shebang
(or (list (cdr pair
)) shebang
)))
2082 (setq comments
(e-merge '(("yes" "no")) comments
2083 (split-string (or (cdr pair
) "")))))
2084 (t ;; replace: this covers e.g. :session
2085 (setq params
(cons pair
(assq-delete-all (car pair
) params
))))))
2088 (setq vars
(reverse vars
))
2089 (while vars
(setq params
(cons (cons :var
(cddr (pop vars
))) params
)))
2092 (let ((key (intern (concat ":" (symbol-name hd
))))
2094 (setf params
(cons (cons key
(mapconcat 'identity val
" ")) params
))))
2095 '(results exports tangle noweb padline cache shebang comments
))
2098 (defvar *org-babel-use-quick-and-dirty-noweb-expansion
* nil
2099 "Set to true to use regular expressions to expand noweb references.
2100 This results in much faster noweb reference expansion but does
2101 not properly allow code blocks to inherit the \":noweb-ref\"
2102 header argument from buffer or subtree wide properties.")
2104 (defun org-babel-noweb-p (params context
)
2105 "Check if PARAMS require expansion in CONTEXT.
2106 CONTEXT may be one of :tangle, :export or :eval."
2107 (flet ((intersect (as bs
)
2109 (if (member (car as
) bs
)
2111 (intersect (cdr as
) bs
)))))
2112 (intersect (case context
2113 (:tangle
'("yes" "tangle" "no-export"))
2114 (:eval
'("yes" "no-export"))
2116 (split-string (or (cdr (assoc :noweb params
)) "")))))
2118 (defun org-babel-expand-noweb-references (&optional info parent-buffer
)
2119 "Expand Noweb references in the body of the current source code block.
2121 For example the following reference would be replaced with the
2122 body of the source-code block named 'example-block'.
2126 Note that any text preceding the <<foo>> construct on a line will
2127 be interposed between the lines of the replacement text. So for
2128 example if <<foo>> is placed behind a comment, then the entire
2129 replacement text will also be commented.
2131 This function must be called from inside of the buffer containing
2132 the source-code block which holds BODY.
2134 In addition the following syntax can be used to insert the
2135 results of evaluating the source-code block named 'example-block'.
2139 Any optional arguments can be passed to example-block by placing
2140 the arguments inside the parenthesis following the convention
2141 defined by `org-babel-lob'. For example
2143 <<example-block(a=9)>>
2145 would set the value of argument \"a\" equal to \"9\". Note that
2146 these arguments are not evaluated in the current source-code
2147 block but are passed literally to the \"example-block\"."
2148 (let* ((parent-buffer (or parent-buffer
(current-buffer)))
2149 (info (or info
(org-babel-get-src-block-info)))
2152 (comment (string= "noweb" (cdr (assoc :comments
(nth 2 info
)))))
2153 (rx-prefix (concat "\\(" org-babel-src-name-regexp
"\\|"
2154 ":noweb-ref[ \t]+" "\\)"))
2155 (new-body "") index source-name evaluate prefix blocks-in-buffer
)
2156 (flet ((nb-add (text) (setq new-body
(concat new-body text
)))
2159 (funcall (intern (concat lang
"-mode")))
2160 (comment-region (point) (progn (insert text
) (point)))
2161 (org-babel-trim (buffer-string)))))
2163 (insert body
) (goto-char (point-min))
2164 (setq index
(point))
2165 (while (and (re-search-forward "<<\\(.+?\\)>>" nil t
))
2166 (save-match-data (setf source-name
(match-string 1)))
2167 (save-match-data (setq evaluate
(string-match "\(.*\)" source-name
)))
2170 (buffer-substring (match-beginning 0)
2172 (beginning-of-line 1) (point)))))
2173 ;; add interval to new-body (removing noweb reference)
2174 (goto-char (match-beginning 0))
2175 (nb-add (buffer-substring index
(point)))
2176 (goto-char (match-end 0))
2177 (setq index
(point))
2179 (with-current-buffer parent-buffer
2180 (mapconcat ;; interpose PREFIX between every line
2184 (let ((raw (org-babel-ref-resolve source-name
)))
2185 (if (stringp raw
) raw
(format "%S" raw
)))
2187 ;; retrieve from the library of babel
2188 (nth 2 (assoc (intern source-name
)
2189 org-babel-library-of-babel
))
2190 ;; return the contents of headlines literally
2192 (when (org-babel-ref-goto-headline-id source-name
)
2193 (org-babel-ref-headline-body)))
2194 ;; find the expansion of reference in this buffer
2195 (let ((rx (concat rx-prefix source-name
))
2198 (goto-char (point-min))
2199 (if *org-babel-use-quick-and-dirty-noweb-expansion
*
2200 (while (re-search-forward rx nil t
)
2201 (let* ((i (org-babel-get-src-block-info 'light
))
2202 (body (org-babel-expand-noweb-references i
))
2203 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2207 (concat (c-wrap (car cs
)) "\n"
2209 (c-wrap (cadr cs
))))
2210 (org-babel-tangle-comment-links i
))
2212 (setq expansion
(cons sep
(cons full expansion
)))))
2213 (org-babel-map-src-blocks nil
2214 (let ((i (org-babel-get-src-block-info 'light
)))
2215 (when (equal (or (cdr (assoc :noweb-ref
(nth 2 i
)))
2218 (let* ((body (org-babel-expand-noweb-references i
))
2219 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2223 (concat (c-wrap (car cs
)) "\n"
2225 (c-wrap (cadr cs
))))
2226 (org-babel-tangle-comment-links i
))
2229 (cons sep
(cons full expansion
)))))))))
2230 (mapconcat #'identity
(nreverse (cdr expansion
)) ""))
2231 ;; possibly raise an error if named block doesn't exist
2232 (if (member lang org-babel-noweb-error-langs
)
2234 "<<" source-name
">> "
2235 "could not be resolved (see "
2236 "`org-babel-noweb-error-langs')"))
2238 "[\n\r]") (concat "\n" prefix
)))))
2239 (nb-add (buffer-substring index
(point-max)))))
2242 (defun org-babel-clean-text-properties (text)
2243 "Strip all properties from text return."
2245 (set-text-properties 0 (length text
) nil text
) text
))
2247 (defun org-babel-strip-protective-commas (body)
2248 "Strip protective commas from bodies of source blocks."
2250 (replace-regexp-in-string "^,#" "#" body
)))
2252 (defun org-babel-script-escape (str &optional force
)
2253 "Safely convert tables into elisp lists."
2254 (let (in-single in-double out
)
2255 ((lambda (escaped) (condition-case nil
(org-babel-read escaped
) (error escaped
)))
2259 (or (and (string-equal "[" (substring str
0 1))
2260 (string-equal "]" (substring str -
1)))
2261 (and (string-equal "{" (substring str
0 1))
2262 (string-equal "}" (substring str -
1)))
2263 (and (string-equal "(" (substring str
0 1))
2264 (string-equal ")" (substring str -
1))))))
2274 (91 (if (or in-double in-single
) ; [
2277 (93 (if (or in-double in-single
) ; ]
2280 (123 (if (or in-double in-single
) ; {
2283 (125 (if (or in-double in-single
) ; }
2286 (44 (if (or in-double in-single
) ; ,
2287 (cons 44 out
) (cons 32 out
)))
2288 (39 (if in-double
; '
2290 (setq in-single
(not in-single
)) (cons 34 out
)))
2291 (34 (if in-single
; "
2292 (append (list 34 32) out
)
2293 (setq in-double
(not in-double
)) (cons 34 out
)))
2294 (t (cons ch out
)))))
2295 (string-to-list str
))
2296 (apply #'string
(reverse out
)))))
2299 (defun org-babel-read (cell &optional inhibit-lisp-eval
)
2300 "Convert the string value of CELL to a number if appropriate.
2301 Otherwise if cell looks like lisp (meaning it starts with a
2302 \"(\", \"'\", \"`\" or a \"[\") then read it as lisp, otherwise
2303 return it unmodified as a string. Optional argument NO-LISP-EVAL
2304 inhibits lisp evaluation for situations in which is it not
2306 (if (and (stringp cell
) (not (equal cell
"")))
2307 (or (org-babel-number-p cell
)
2308 (if (and (not inhibit-lisp-eval
)
2309 (member (substring cell
0 1) '("(" "'" "`" "[")))
2311 (if (string= (substring cell
0 1) "\"")
2313 (progn (set-text-properties 0 (length cell
) nil cell
) cell
))))
2316 (defun org-babel-number-p (string)
2317 "If STRING represents a number return its value."
2318 (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string
)
2319 (= (length (substring string
(match-beginning 0)
2322 (string-to-number string
)))
2324 (defun org-babel-import-elisp-from-file (file-name &optional separator
)
2325 "Read the results located at FILE-NAME into an elisp table.
2326 If the table is trivial, then return it as a scalar."
2328 (save-window-excursion
2332 (org-table-import file-name separator
)
2333 (delete-file file-name
)
2334 (setq result
(mapcar (lambda (row)
2335 (mapcar #'org-babel-string-read row
))
2336 (org-table-to-lisp))))
2338 (if (null (cdr result
)) ;; if result is trivial vector, then scalarize it
2339 (if (consp (car result
))
2340 (if (null (cdr (car result
)))
2346 (defun org-babel-string-read (cell)
2347 "Strip nested \"s from around strings."
2348 (org-babel-read (or (and (stringp cell
)
2349 (string-match "\\\"\\(.+\\)\\\"" cell
)
2350 (match-string 1 cell
))
2353 (defun org-babel-reverse-string (string)
2354 "Return the reverse of STRING."
2355 (apply 'string
(reverse (string-to-list string
))))
2357 (defun org-babel-chomp (string &optional regexp
)
2358 "Strip trailing spaces and carriage returns from STRING.
2359 Default regexp used is \"[ \f\t\n\r\v]\" but can be
2360 overwritten by specifying a regexp as a second argument."
2361 (let ((regexp (or regexp
"[ \f\t\n\r\v]")))
2362 (while (and (> (length string
) 0)
2363 (string-match regexp
(substring string -
1)))
2364 (setq string
(substring string
0 -
1)))
2367 (defun org-babel-trim (string &optional regexp
)
2368 "Strip leading and trailing spaces and carriage returns from STRING.
2369 Like `org-babel-chomp' only it runs on both the front and back
2371 (org-babel-chomp (org-babel-reverse-string
2372 (org-babel-chomp (org-babel-reverse-string string
) regexp
))
2375 (defvar org-babel-org-babel-call-process-region-original nil
)
2376 (defun org-babel-tramp-handle-call-process-region
2377 (start end program
&optional delete buffer display
&rest args
)
2378 "Use tramp to handle call-process-region.
2379 Fixes a bug in `tramp-handle-call-process-region'."
2380 (if (and (featurep 'tramp
) (file-remote-p default-directory
))
2381 (let ((tmpfile (tramp-compat-make-temp-file "")))
2382 (write-region start end tmpfile
)
2383 (when delete
(delete-region start end
))
2385 ;; (apply 'call-process program tmpfile buffer display args)
2387 (apply 'process-file program tmpfile buffer display args
)
2388 (delete-file tmpfile
)))
2389 ;; org-babel-call-process-region-original is the original emacs
2390 ;; definition. It is in scope from the let binding in
2391 ;; org-babel-execute-src-block
2392 (apply org-babel-call-process-region-original
2393 start end program delete buffer display args
)))
2395 (defun org-babel-local-file-name (file)
2396 "Return the local name component of FILE."
2397 (if (file-remote-p file
)
2399 (with-parsed-tramp-file-name file nil
2403 (defun org-babel-process-file-name (name &optional no-quote-p
)
2404 "Prepare NAME to be used in an external process.
2405 If NAME specifies a remote location, the remote portion of the
2406 name is removed, since in that case the process will be executing
2407 remotely. The file name is then processed by
2408 `expand-file-name'. Unless second argument NO-QUOTE-P is non-nil,
2409 the file name is additionally processed by
2410 `shell-quote-argument'"
2411 ((lambda (f) (if no-quote-p f
(shell-quote-argument f
)))
2412 (expand-file-name (org-babel-local-file-name name
))))
2414 (defvar org-babel-temporary-directory
)
2415 (unless (or noninteractive
(boundp 'org-babel-temporary-directory
))
2416 (defvar org-babel-temporary-directory
2417 (or (and (boundp 'org-babel-temporary-directory
)
2418 (file-exists-p org-babel-temporary-directory
)
2419 org-babel-temporary-directory
)
2420 (make-temp-file "babel-" t
))
2421 "Directory to hold temporary files created to execute code blocks.
2422 Used by `org-babel-temp-file'. This directory will be removed on
2425 (defun org-babel-temp-file (prefix &optional suffix
)
2426 "Create a temporary file in the `org-babel-temporary-directory'.
2427 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2428 value of `temporary-file-directory' temporarily set to the value
2429 of `org-babel-temporary-directory'."
2430 (if (file-remote-p default-directory
)
2432 (concat (file-remote-p default-directory
)
2434 prefix temporary-file-directory
)
2436 (let ((temporary-file-directory
2437 (or (and (boundp 'org-babel-temporary-directory
)
2438 (file-exists-p org-babel-temporary-directory
)
2439 org-babel-temporary-directory
)
2440 temporary-file-directory
)))
2441 (make-temp-file prefix nil suffix
))))
2443 (defun org-babel-remove-temporary-directory ()
2444 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2445 (when (and (boundp 'org-babel-temporary-directory
)
2446 (file-exists-p org-babel-temporary-directory
))
2447 ;; taken from `delete-directory' in files.el
2450 (mapc (lambda (file)
2451 ;; This test is equivalent to
2452 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2453 ;; but more efficient
2454 (if (eq t
(car (file-attributes file
)))
2455 (delete-directory file
)
2456 (delete-file file
)))
2457 ;; We do not want to delete "." and "..".
2458 (directory-files org-babel-temporary-directory
'full
2459 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2460 (delete-directory org-babel-temporary-directory
))
2462 (message "Failed to remove temporary Org-babel directory %s"
2463 (if (boundp 'org-babel-temporary-directory
)
2464 org-babel-temporary-directory
2465 "[directory not defined]"))))))
2467 (add-hook 'kill-emacs-hook
'org-babel-remove-temporary-directory
)