1 ;;; ob.el --- working with code blocks in org-mode
3 ;; Copyright (C) 2009-2012 Free Software Foundation, Inc.
5 ;; Authors: 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
))
82 (declare-function org-strip-protective-commas
"org" (beg end
))
84 (defgroup org-babel nil
85 "Code block evaluation and management in `org-mode' documents."
89 (defcustom org-confirm-babel-evaluate t
90 "Confirm before evaluation.
91 Require confirmation before interactively evaluating code
92 blocks in Org-mode buffers. The default value of this variable
93 is t, meaning confirmation is required for any code block
94 evaluation. This variable can be set to nil to inhibit any
95 future confirmation requests. This variable can also be set to a
96 function which takes two arguments the language of the code block
97 and the body of the code block. Such a function should then
98 return a non-nil value if the user should be prompted for
99 execution or nil if no prompt is required.
101 Warning: Disabling confirmation may result in accidental
102 evaluation of potentially harmful code. It may be advisable
103 remove code block execution from C-c C-c as further protection
104 against accidental code block evaluation. The
105 `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
106 remove code block execution from the C-c C-c keybinding."
108 :type
'(choice boolean function
))
109 ;; don't allow this variable to be changed through file settings
110 (put 'org-confirm-babel-evaluate
'safe-local-variable
(lambda (x) (eq x t
)))
112 (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
113 "Remove code block evaluation from the C-c C-c key binding."
117 (defcustom org-babel-results-keyword
"RESULTS"
118 "Keyword used to name results generated by code blocks.
119 Should be either RESULTS or NAME however any capitalization may
124 (defvar org-babel-src-name-regexp
125 "^[ \t]*#\\+name:[ \t]*"
126 "Regular expression used to match a source name line.")
128 (defvar org-babel-multi-line-header-regexp
129 "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
130 "Regular expression used to match multi-line header arguments.")
132 (defvar org-babel-src-name-w-name-regexp
133 (concat org-babel-src-name-regexp
135 org-babel-multi-line-header-regexp
137 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)")
138 "Regular expression matching source name lines with a name.")
140 (defvar org-babel-src-block-regexp
142 ;; (1) indentation (2) lang
143 "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
145 "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
146 ;; (4) header arguments
149 "\\([^\000]*?\n\\)?[ \t]*#\\+end_src")
150 "Regexp used to identify code blocks.")
152 (defvar org-babel-inline-src-block-regexp
154 ;; (1) replacement target (2) lang
155 "\\(?:^\\|[^-[:alnum:]]\\)\\(src_\\([^ \f\t\n\r\v]+\\)"
156 ;; (3,4) (unused, headers)
157 "\\(\\|\\[\\(.*?\\)\\]\\)"
159 "{\\([^\f\n\r\v]+?\\)}\\)")
160 "Regexp used to identify inline src-blocks.")
162 (defun org-babel-get-header (params key
&optional others
)
163 "Select only header argument of type KEY from a list.
164 Optional argument OTHERS indicates that only the header that do
165 not match KEY should be returned."
168 (lambda (p) (when (funcall (if others
#'not
#'identity
) (eq (car p
) key
)) p
))
171 (defun org-babel-get-inline-src-block-matches()
172 "Set match data if within body of an inline source block.
173 Returns non-nil if match-data set"
174 (let ((src-at-0-p (save-excursion
175 (beginning-of-line 1)
176 (string= "src" (thing-at-point 'word
))))
177 (first-line-p (= 1 (line-number-at-pos)))
179 (let ((search-for (cond ((and src-at-0-p first-line-p
"src_"))
180 (first-line-p "[[:punct:] \t]src_")
181 (t "[[:punct:] \f\t\n\r\v]src_")))
182 (lower-limit (if first-line-p
184 (- (point-at-bol) 1))))
186 (when (or (and src-at-0-p
(bobp))
187 (and (re-search-forward "}" (point-at-eol) t
)
188 (re-search-backward search-for lower-limit t
)
190 (when (looking-at org-babel-inline-src-block-regexp
)
193 (defvar org-babel-inline-lob-one-liner-regexp
)
194 (defun org-babel-get-lob-one-liner-matches()
195 "Set match data if on line of an lob one liner.
196 Returns non-nil if match-data set"
198 (unless (= (point) (point-at-bol)) ;; move before inline block
199 (re-search-backward "[ \f\t\n\r\v]" nil t
))
200 (if (looking-at org-babel-inline-lob-one-liner-regexp
)
204 (defun org-babel-get-src-block-info (&optional light
)
205 "Get information on the current source block.
207 Optional argument LIGHT does not resolve remote variable
208 references; a process which could likely result in the execution
209 of other code blocks.
212 (language body header-arguments-alist switches name indent)."
213 (let ((case-fold-search t
) head info name indent
)
215 (if (setq head
(org-babel-where-is-src-block-head))
218 (setq info
(org-babel-parse-src-block-match))
219 (setq indent
(car (last info
)))
220 (setq info
(butlast info
))
221 (while (and (forward-line -
1)
222 (looking-at org-babel-multi-line-header-regexp
))
224 (org-babel-merge-params
226 (org-babel-parse-header-arguments (match-string 1)))))
227 (when (looking-at org-babel-src-name-w-name-regexp
)
228 (setq name
(org-babel-clean-text-properties (match-string 3)))
229 (when (and (match-string 5) (> (length (match-string 5)) 0))
230 (setf (nth 2 info
) ;; merge functional-syntax vars and header-args
231 (org-babel-merge-params
233 (lambda (ref) (cons :var ref
))
235 (lambda (var) ;; check that each variable is initialized
236 (if (string-match ".+=.+" var
)
239 "variable \"%s\"%s must be assigned a default value"
240 var
(if name
(format " in block \"%s\"" name
) ""))))
241 (org-babel-ref-split-args (match-string 5))))
243 ;; inline source block
244 (when (org-babel-get-inline-src-block-matches)
245 (setq info
(org-babel-parse-inline-src-block-match))))
246 ;; resolve variable references and add summary parameters
247 (when (and info
(not light
))
248 (setf (nth 2 info
) (org-babel-process-params (nth 2 info
))))
249 (when info
(append info
(list name indent
)))))
251 (defvar org-current-export-file
) ; dynamically bound
252 (defun org-babel-confirm-evaluate (info)
253 "Confirm evaluation of the code block INFO.
254 This behavior can be suppressed by setting the value of
255 `org-confirm-babel-evaluate' to nil, in which case all future
256 interactive code block evaluations will proceed without any
257 confirmation from the user.
259 Note disabling confirmation may result in accidental evaluation
260 of potentially harmful code."
261 (let* ((eval (or (cdr (assoc :eval
(nth 2 info
)))
262 (when (assoc :noeval
(nth 2 info
)) "no")))
263 (query (cond ((equal eval
"query") t
)
264 ((and org-current-export-file
265 (equal eval
"query-export")) t
)
266 ((functionp org-confirm-babel-evaluate
)
267 (funcall org-confirm-babel-evaluate
268 (nth 0 info
) (nth 1 info
)))
269 (t org-confirm-babel-evaluate
))))
270 (if (or (equal eval
"never") (equal eval
"no")
271 (and org-current-export-file
(or (equal eval
"no-export")
272 (equal eval
"never-export")))
275 (format "Evaluate this%scode block%son your system? "
276 (if info
(format " %s " (nth 0 info
)) " ")
278 (format " (%s) " (nth 4 info
)) " "))))))
279 (prog1 nil
(message "Evaluation %s"
280 (if (or (equal eval
"never") (equal eval
"no")
281 (equal eval
"no-export")
282 (equal eval
"never-export"))
283 "Disabled" "Aborted")))
287 (defun org-babel-execute-safely-maybe ()
288 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
289 (org-babel-execute-maybe)))
291 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-execute-safely-maybe
)
294 (defun org-babel-execute-maybe ()
296 (or (org-babel-execute-src-block-maybe)
297 (org-babel-lob-execute-maybe)))
299 (defun org-babel-execute-src-block-maybe ()
300 "Conditionally execute a source block.
301 Detect if this is context for a Babel src-block and if so
302 then run `org-babel-execute-src-block'."
304 (let ((info (org-babel-get-src-block-info)))
306 (progn (org-babel-eval-wipe-error-buffer)
307 (org-babel-execute-src-block current-prefix-arg info
) t
) nil
)))
310 (defun org-babel-view-src-block-info ()
311 "Display information on the current source block.
312 This includes header arguments, language and name, and is largely
313 a window into the `org-babel-get-src-block-info' function."
315 (let ((info (org-babel-get-src-block-info 'light
)))
316 (flet ((full (it) (> (length it
) 0))
317 (printf (fmt &rest args
) (princ (apply #'format fmt args
))))
319 (with-help-window (help-buffer)
320 (let ((name (nth 4 info
))
322 (switches (nth 3 info
))
323 (header-args (nth 2 info
)))
324 (when name
(printf "Name: %s\n" name
))
325 (when lang
(printf "Lang: %s\n" lang
))
326 (when (full switches
) (printf "Switches: %s\n" switches
))
327 (printf "Header Arguments:\n")
328 (dolist (pair (sort header-args
329 (lambda (a b
) (string< (symbol-name (car a
))
330 (symbol-name (car b
))))))
331 (when (full (cdr pair
))
332 (printf "\t%S%s\t%s\n"
334 (if (> (length (format "%S" (car pair
))) 7) "" "\t")
338 (defun org-babel-expand-src-block-maybe ()
339 "Conditionally expand a source block.
340 Detect if this is context for a org-babel src-block and if so
341 then run `org-babel-expand-src-block'."
343 (let ((info (org-babel-get-src-block-info)))
345 (progn (org-babel-expand-src-block current-prefix-arg info
) t
)
349 (defun org-babel-load-in-session-maybe ()
350 "Conditionally load a source block in a session.
351 Detect if this is context for a org-babel src-block and if so
352 then run `org-babel-load-in-session'."
354 (let ((info (org-babel-get-src-block-info)))
356 (progn (org-babel-load-in-session current-prefix-arg info
) t
)
359 (add-hook 'org-metaup-hook
'org-babel-load-in-session-maybe
)
362 (defun org-babel-pop-to-session-maybe ()
363 "Conditionally pop to a session.
364 Detect if this is context for a org-babel src-block and if so
365 then run `org-babel-pop-to-session'."
367 (let ((info (org-babel-get-src-block-info)))
368 (if info
(progn (org-babel-pop-to-session current-prefix-arg info
) t
) nil
)))
370 (add-hook 'org-metadown-hook
'org-babel-pop-to-session-maybe
)
372 (defconst org-babel-common-header-args-w-values
373 '((cache .
((no yes
)))
375 (colnames .
((nil no yes
)))
376 (comments .
((no link yes org both noweb
)))
378 (eval .
((never query
)))
379 (exports .
((code results both none
)))
381 (hlines .
((no yes
)))
382 (mkdirp .
((yes no
)))
385 (noweb .
((yes no tangle
)))
388 (padline .
((yes no
)))
389 (results .
((file list vector table scalar verbatim
)
390 (raw org html latex code pp wrap
)
391 (replace silent append prepend
)
393 (rownames .
((no yes
)))
397 (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 (let ((noweb (cdr (assoc :noweb params
))))
498 (or (string= "yes" noweb
)
499 (string= "tangle" noweb
)))
500 (org-babel-expand-noweb-references info
)
502 (dir (cdr (assoc :dir params
)))
504 (or (and dir
(file-name-as-directory dir
)) default-directory
))
505 (org-babel-call-process-region-original
506 (if (boundp 'org-babel-call-process-region-original
)
507 org-babel-call-process-region-original
508 (symbol-function 'call-process-region
)))
509 (indent (car (last info
)))
512 (flet ((call-process-region (&rest args
)
513 (apply 'org-babel-tramp-handle-call-process-region args
)))
514 (flet ((lang-check (f)
515 (let ((f (intern (concat "org-babel-execute:" f
))))
516 (when (fboundp f
) f
))))
518 (or (lang-check lang
)
519 (lang-check (symbol-name
520 (cdr (assoc lang org-src-lang-modes
))))
521 (error "No org-babel-execute function for %s!" lang
))))
522 (if (and (not arg
) new-hash
(equal new-hash old-hash
))
523 (save-excursion ;; return cached result
524 (goto-char (org-babel-where-is-src-block-result nil info
))
525 (end-of-line 1) (forward-char 1)
526 (setq result
(org-babel-read-result))
527 (message (replace-regexp-in-string
528 "%" "%%" (format "%S" result
))) result
)
529 (message "executing %s code block%s..."
531 (if (nth 4 info
) (format " (%s)" (nth 4 info
)) ""))
534 (if (and (eq (cdr (assoc :result-type params
)) 'value
)
535 (or (member "vector" result-params
)
536 (member "table" result-params
))
537 (not (listp result
)))
538 (list (list result
)) result
))
539 (funcall cmd body params
)))
540 ;; if non-empty result and :file then write to :file
541 (when (cdr (assoc :file params
))
543 (with-temp-file (cdr (assoc :file params
))
545 (org-babel-format-result
546 result
(cdr (assoc :sep
(nth 2 info
)))))))
547 (setq result
(cdr (assoc :file params
))))
548 (org-babel-insert-result
549 result result-params info new-hash indent lang
)
550 (run-hooks 'org-babel-after-execute-hook
)
552 (setq call-process-region
'org-babel-call-process-region-original
))))))
554 (defun org-babel-expand-body:generic
(body params
&optional var-lines
)
555 "Expand BODY with PARAMS.
556 Expand a block of code with org-babel according to its header
557 arguments. This generic implementation of body expansion is
558 called for languages which have not defined their own specific
559 org-babel-expand-body:lang function."
560 (mapconcat #'identity
(append var-lines
(list body
)) "\n"))
563 (defun org-babel-expand-src-block (&optional arg info params
)
564 "Expand the current source code block.
565 Expand according to the source code block's header
566 arguments and pop open the results in a preview buffer."
568 (let* ((info (or info
(org-babel-get-src-block-info)))
570 (params (setf (nth 2 info
)
571 (sort (org-babel-merge-params (nth 2 info
) params
)
572 (lambda (el1 el2
) (string< (symbol-name (car el1
))
573 (symbol-name (car el2
)))))))
574 (body (setf (nth 1 info
)
575 (if (and (cdr (assoc :noweb params
))
576 (string= "yes" (cdr (assoc :noweb params
))))
577 (org-babel-expand-noweb-references info
) (nth 1 info
))))
578 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
579 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
582 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
583 (org-babel-expand-body:generic
584 body params
(and (fboundp assignments-cmd
)
585 (funcall assignments-cmd params
))))))
587 nil expanded
(concat "*Org-Babel Preview " (buffer-name) "[ " lang
" ]*"))))
589 (defun org-babel-edit-distance (s1 s2
)
590 "Return the edit (levenshtein) distance between strings S1 S2."
591 (let* ((l1 (length s1
))
593 (dist (map 'vector
(lambda (_) (make-vector (1+ l2
) nil
))
594 (number-sequence 1 (1+ l1
)))))
595 (flet ((in (i j
) (aref (aref dist i
) j
))
596 (mmin (&rest lst
) (apply #'min
(remove nil lst
))))
597 (setf (aref (aref dist
0) 0) 0)
598 (dolist (i (number-sequence 1 l1
))
599 (dolist (j (number-sequence 1 l2
))
600 (setf (aref (aref dist i
) j
)
601 (+ (if (equal (aref s1
(1- i
)) (aref s2
(1- j
))) 0 1)
602 (mmin (in (1- i
) j
) (in i
(1- j
)) (in (1- i
) (1- j
)))))))
606 (defun org-babel-check-src-block ()
607 "Check for misspelled header arguments in the current code block."
609 ;; TODO: report malformed code block
610 ;; TODO: report incompatible combinations of header arguments
611 ;; TODO: report uninitialized variables
612 (let ((too-close 2) ;; <- control closeness to report potential match
613 (names (mapcar #'symbol-name org-babel-header-arg-names
)))
614 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg
)) 1))
615 (and (org-babel-where-is-src-block-head)
616 (org-babel-parse-header-arguments
617 (org-babel-clean-text-properties
618 (match-string 4))))))
620 (when (and (not (string= header name
))
621 (<= (org-babel-edit-distance header name
) too-close
)
622 (not (member header names
)))
623 (error "supplied header \"%S\" is suspiciously close to \"%S\""
625 (message "No suspicious header arguments found.")))
628 (defun org-babel-insert-header-arg ()
629 "Insert a header argument selecting from lists of common args and values."
631 (let* ((lang (car (org-babel-get-src-block-info 'light
)))
632 (lang-headers (intern (concat "org-babel-header-arg-names:" lang
)))
633 (headers (append (if (boundp lang-headers
)
634 (mapcar (lambda (h) (cons h
:any
))
637 org-babel-common-header-args-w-values
))
638 (arg (org-icompleting-read
641 (lambda (header-spec) (symbol-name (car header-spec
)))
644 (let ((vals (cdr (assoc (intern arg
) headers
))))
650 (read-from-minibuffer "value: "))
654 (let ((arg (org-icompleting-read
656 (cons "default" (mapcar #'symbol-name group
)))))
657 (if (and arg
(not (string= "default" arg
)))
663 (defun org-babel-load-in-session (&optional arg info
)
664 "Load the body of the current source-code block.
665 Evaluate the header arguments for the source block before
666 entering the session. After loading the body this pops open the
669 (let* ((info (or info
(org-babel-get-src-block-info)))
671 (params (nth 2 info
))
672 (body (setf (nth 1 info
)
673 (if (and (cdr (assoc :noweb params
))
674 (string= "yes" (cdr (assoc :noweb params
))))
675 (org-babel-expand-noweb-references info
)
677 (session (cdr (assoc :session params
)))
678 (dir (cdr (assoc :dir params
)))
680 (or (and dir
(file-name-as-directory dir
)) default-directory
))
681 (cmd (intern (concat "org-babel-load-session:" lang
))))
682 (unless (fboundp cmd
)
683 (error "No org-babel-load-session function for %s!" lang
))
684 (pop-to-buffer (funcall cmd session body params
))
688 (defun org-babel-initiate-session (&optional arg info
)
689 "Initiate session for current code block.
690 If called with a prefix argument then resolve any variable
691 references in the header arguments and assign these variables in
692 the session. Copy the body of the code block to the kill ring."
694 (let* ((info (or info
(org-babel-get-src-block-info (not arg
))))
697 (params (nth 2 info
))
698 (session (cdr (assoc :session params
)))
699 (dir (cdr (assoc :dir params
)))
701 (or (and dir
(file-name-as-directory dir
)) default-directory
))
702 (init-cmd (intern (format "org-babel-%s-initiate-session" lang
)))
703 (prep-cmd (intern (concat "org-babel-prep-session:" lang
))))
704 (if (and (stringp session
) (string= session
"none"))
705 (error "This block is not using a session!"))
706 (unless (fboundp init-cmd
)
707 (error "No org-babel-initiate-session function for %s!" lang
))
708 (with-temp-buffer (insert (org-babel-trim body
))
709 (copy-region-as-kill (point-min) (point-max)))
711 (unless (fboundp prep-cmd
)
712 (error "No org-babel-prep-session function for %s!" lang
))
713 (funcall prep-cmd session params
))
714 (funcall init-cmd session params
)))
717 (defun org-babel-switch-to-session (&optional arg info
)
718 "Switch to the session of the current code block.
719 Uses `org-babel-initiate-session' to start the session. If called
720 with a prefix argument then this is passed on to
721 `org-babel-initiate-session'."
723 (pop-to-buffer (org-babel-initiate-session arg info
))
726 (defalias 'org-babel-pop-to-session
'org-babel-switch-to-session
)
729 (defun org-babel-switch-to-session-with-code (&optional arg info
)
730 "Switch to code buffer and display session."
734 (let ((other-window-buffer (window-buffer (next-window))))
735 (set-window-buffer (next-window) (current-buffer))
736 (set-window-buffer (selected-window) other-window-buffer
))
738 (let ((info (org-babel-get-src-block-info))
739 (org-src-window-setup 'reorganize-frame
))
741 (org-babel-switch-to-session arg info
))
745 (defmacro org-babel-do-in-edit-buffer
(&rest body
)
746 "Evaluate BODY in edit buffer if there is a code block at point.
747 Return t if a code block was found at point, nil otherwise."
748 `(let ((org-src-window-setup 'switch-invisibly
))
749 (when (and (org-babel-where-is-src-block-head)
750 (org-edit-src-code nil nil nil
))
751 (unwind-protect (progn ,@body
)
752 (if (org-bound-and-true-p org-edit-src-from-org-mode
)
753 (org-edit-src-exit)))
755 (def-edebug-spec org-babel-do-in-edit-buffer
(body))
757 (defun org-babel-do-key-sequence-in-edit-buffer (key)
758 "Read key sequence and execute the command in edit buffer.
759 Enter a key sequence to be executed in the language major-mode
760 edit buffer. For example, TAB will alter the contents of the
761 Org-mode code block according to the effect of TAB in the
762 language major-mode buffer. For languages that support
763 interactive sessions, this can be used to send code from the Org
764 buffer to the session for evaluation using the native major-mode
765 evaluation mechanisms."
766 (interactive "kEnter key-sequence to execute in edit buffer: ")
767 (org-babel-do-in-edit-buffer
769 (key-binding (or key
(read-key-sequence nil
))))))
771 (defvar org-bracket-link-regexp
)
773 (defun org-babel-open-src-block-result (&optional re-run
)
774 "If `point' is on a src block then open the results of the
775 source code block, otherwise return nil. With optional prefix
776 argument RE-RUN the source-code block is evaluated even if
777 results already exist."
779 (let ((info (org-babel-get-src-block-info)))
782 ;; go to the results, if there aren't any then run the block
783 (goto-char (or (and (not re-run
) (org-babel-where-is-src-block-result))
784 (progn (org-babel-execute-src-block)
785 (org-babel-where-is-src-block-result))))
787 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
789 (if (looking-at org-bracket-link-regexp
)
792 (let ((r (org-babel-format-result
793 (org-babel-read-result) (cdr (assoc :sep
(nth 2 info
))))))
794 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
795 (delete-region (point-min) (point-max))
800 (defmacro org-babel-map-src-blocks
(file &rest body
)
801 "Evaluate BODY forms on each source-block in FILE.
802 If FILE is nil evaluate BODY forms on source blocks in current
803 buffer. During evaluation of BODY the following local variables
804 are set relative to the currently matched code block.
806 full-block ------- string holding the entirety of the code block
807 beg-block -------- point at the beginning of the code block
808 end-block -------- point at the end of the matched code block
809 lang ------------- string holding the language of the code block
810 beg-lang --------- point at the beginning of the lang
811 end-lang --------- point at the end of the lang
812 switches --------- string holding the switches
813 beg-switches ----- point at the beginning of the switches
814 end-switches ----- point at the end of the switches
815 header-args ------ string holding the header-args
816 beg-header-args -- point at the beginning of the header-args
817 end-header-args -- point at the end of the header-args
818 body ------------- string holding the body of the code block
819 beg-body --------- point at the beginning of the body
820 end-body --------- point at the end of the body"
822 (let ((tempvar (make-symbol "file")))
823 `(let* ((,tempvar
,file
)
824 (visited-p (or (null ,tempvar
)
825 (get-file-buffer (expand-file-name ,tempvar
))))
826 (point (point)) to-be-removed
)
827 (save-window-excursion
828 (when ,tempvar
(find-file ,tempvar
))
829 (setq to-be-removed
(current-buffer))
830 (goto-char (point-min))
831 (while (re-search-forward org-babel-src-block-regexp nil t
)
832 (goto-char (match-beginning 0))
833 (let ((full-block (match-string 0))
834 (beg-block (match-beginning 0))
835 (end-block (match-end 0))
836 (lang (match-string 2))
837 (beg-lang (match-beginning 2))
838 (end-lang (match-end 2))
839 (switches (match-string 3))
840 (beg-switches (match-beginning 3))
841 (end-switches (match-end 3))
842 (header-args (match-string 4))
843 (beg-header-args (match-beginning 4))
844 (end-header-args (match-end 4))
845 (body (match-string 5))
846 (beg-body (match-beginning 5))
847 (end-body (match-end 5)))
849 (goto-char end-block
))))
850 (unless visited-p
(kill-buffer to-be-removed
))
852 (def-edebug-spec org-babel-map-src-blocks
(form body
))
855 (defmacro org-babel-map-inline-src-blocks
(file &rest body
)
856 "Evaluate BODY forms on each inline source-block in FILE.
857 If FILE is nil evaluate BODY forms on source blocks in current
860 (let ((tempvar (make-symbol "file")))
861 `(let* ((,tempvar
,file
)
862 (visited-p (or (null ,tempvar
)
863 (get-file-buffer (expand-file-name ,tempvar
))))
864 (point (point)) to-be-removed
)
865 (save-window-excursion
866 (when ,tempvar
(find-file ,tempvar
))
867 (setq to-be-removed
(current-buffer))
868 (goto-char (point-min))
869 (while (re-search-forward org-babel-inline-src-block-regexp nil t
)
870 (goto-char (match-beginning 1))
871 (save-match-data ,@body
)
872 (goto-char (match-end 0))))
873 (unless visited-p
(kill-buffer to-be-removed
))
875 (def-edebug-spec org-babel-map-inline-src-blocks
(form body
))
877 (defvar org-babel-lob-one-liner-regexp
)
879 (defmacro org-babel-map-call-lines
(file &rest body
)
880 "Evaluate BODY forms on each call line in FILE.
881 If FILE is nil evaluate BODY forms on source blocks in current
884 (let ((tempvar (make-symbol "file")))
885 `(let* ((,tempvar
,file
)
886 (visited-p (or (null ,tempvar
)
887 (get-file-buffer (expand-file-name ,tempvar
))))
888 (point (point)) to-be-removed
)
889 (save-window-excursion
890 (when ,tempvar
(find-file ,tempvar
))
891 (setq to-be-removed
(current-buffer))
892 (goto-char (point-min))
893 (while (re-search-forward org-babel-lob-one-liner-regexp nil t
)
894 (goto-char (match-beginning 1))
895 (save-match-data ,@body
)
896 (goto-char (match-end 0))))
897 (unless visited-p
(kill-buffer to-be-removed
))
899 (def-edebug-spec org-babel-map-call-lines
(form body
))
902 (defmacro org-babel-map-executables
(file &rest body
)
904 (let ((tempvar (make-symbol "file"))
905 (rx (make-symbol "rx")))
906 `(let* ((,tempvar
,file
)
907 (,rx
(concat "\\(" org-babel-src-block-regexp
908 "\\|" org-babel-inline-src-block-regexp
909 "\\|" org-babel-lob-one-liner-regexp
"\\)"))
910 (visited-p (or (null ,tempvar
)
911 (get-file-buffer (expand-file-name ,tempvar
))))
912 (point (point)) to-be-removed
)
913 (save-window-excursion
914 (when ,tempvar
(find-file ,tempvar
))
915 (setq to-be-removed
(current-buffer))
916 (goto-char (point-min))
917 (while (re-search-forward ,rx nil t
)
918 (goto-char (match-beginning 1))
919 (when (looking-at org-babel-inline-src-block-regexp
)(forward-char 1))
920 (save-match-data ,@body
)
921 (goto-char (match-end 0))))
922 (unless visited-p
(kill-buffer to-be-removed
))
924 (def-edebug-spec org-babel-map-executables
(form body
))
927 (defun org-babel-execute-buffer (&optional arg
)
928 "Execute source code blocks in a buffer.
929 Call `org-babel-execute-src-block' on every source block in
932 (org-babel-eval-wipe-error-buffer)
933 (org-save-outline-visibility t
934 (org-babel-map-executables nil
935 (if (looking-at org-babel-lob-one-liner-regexp
)
936 (org-babel-lob-execute-maybe)
937 (org-babel-execute-src-block arg
)))))
940 (defun org-babel-execute-subtree (&optional arg
)
941 "Execute source code blocks in a subtree.
942 Call `org-babel-execute-src-block' on every source block in
943 the current subtree."
947 (org-narrow-to-subtree)
948 (org-babel-execute-buffer arg
)
952 (defun org-babel-sha1-hash (&optional info
)
953 "Generate an sha1 hash based on the value of info."
955 (let ((print-level nil
)
956 (info (or info
(org-babel-get-src-block-info))))
958 (sort (copy-sequence (nth 2 info
))
959 (lambda (a b
) (string< (car a
) (car b
)))))
961 (dolist (p '("replace" "silent" "append" "prepend"))
962 (setq lst
(remove p lst
)))
965 (let ((v (if (and (listp (cdr arg
)) (null (cddr arg
)))
966 (copy-sequence (cdr arg
))
968 (when (and v
(not (and (sequencep v
)
972 ((and (listp v
) ; lists are sorted
973 (member (car arg
) '(:result-params
)))
974 (sort (rm v
) #'string
<))
975 ((and (stringp v
) ; strings are sorted
976 (member (car arg
) '(:results
:exports
)))
977 (mapconcat #'identity
(sort (rm (split-string v
))
981 (when (org-called-interactively-p 'interactive
) (message hash
)) hash
)
982 (let ((it (format "%s-%s"
985 (delq nil
(mapcar (lambda (arg)
986 (let ((normalized (norm arg
)))
988 (format "%S" normalized
))))
993 (defun org-babel-current-result-hash ()
994 "Return the in-buffer hash associated with INFO."
995 (org-babel-where-is-src-block-result)
996 (org-babel-clean-text-properties (match-string 3)))
998 (defun org-babel-hide-hash ()
999 "Hide the hash in the current results line.
1000 Only the initial `org-babel-hash-show' characters of the hash
1001 will remain visible."
1002 (add-to-invisibility-spec '(org-babel-hide-hash . t
))
1004 (when (and (re-search-forward org-babel-result-regexp nil t
)
1006 (let* ((start (match-beginning 3))
1007 (hide-start (+ org-babel-hash-show start
))
1009 (hash (match-string 3))
1011 (setq ov1
(make-overlay start hide-start
))
1012 (setq ov2
(make-overlay hide-start end
))
1013 (overlay-put ov2
'invisible
'org-babel-hide-hash
)
1014 (overlay-put ov1
'babel-hash hash
)))))
1016 (defun org-babel-hide-all-hashes ()
1017 "Hide the hash in the current buffer.
1018 Only the initial `org-babel-hash-show' characters of each hash
1019 will remain visible. This function should be called as part of
1020 the `org-mode-hook'."
1022 (while (re-search-forward org-babel-result-regexp nil t
)
1023 (goto-char (match-beginning 0))
1024 (org-babel-hide-hash)
1025 (goto-char (match-end 0)))))
1026 (add-hook 'org-mode-hook
'org-babel-hide-all-hashes
)
1028 (defun org-babel-hash-at-point (&optional point
)
1029 "Return the value of the hash at POINT.
1030 The hash is also added as the last element of the kill ring.
1031 This can be called with C-c C-c."
1033 (let ((hash (car (delq nil
(mapcar
1034 (lambda (ol) (overlay-get ol
'babel-hash
))
1035 (overlays-at (or point
(point))))))))
1036 (when hash
(kill-new hash
) (message hash
))))
1037 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-hash-at-point
)
1039 (defun org-babel-result-hide-spec ()
1040 "Hide portions of results lines.
1041 Add `org-babel-hide-result' as an invisibility spec for hiding
1042 portions of results lines."
1043 (add-to-invisibility-spec '(org-babel-hide-result . t
)))
1044 (add-hook 'org-mode-hook
'org-babel-result-hide-spec
)
1046 (defvar org-babel-hide-result-overlays nil
1047 "Overlays hiding results.")
1049 (defun org-babel-result-hide-all ()
1050 "Fold all results in the current buffer."
1052 (org-babel-show-result-all)
1054 (while (re-search-forward org-babel-result-regexp nil t
)
1055 (save-excursion (goto-char (match-beginning 0))
1056 (org-babel-hide-result-toggle-maybe)))))
1058 (defun org-babel-show-result-all ()
1059 "Unfold all results in the current buffer."
1060 (mapc 'delete-overlay org-babel-hide-result-overlays
)
1061 (setq org-babel-hide-result-overlays nil
))
1064 (defun org-babel-hide-result-toggle-maybe ()
1065 "Toggle visibility of result at point."
1067 (let ((case-fold-search t
))
1069 (beginning-of-line 1)
1070 (looking-at org-babel-result-regexp
))
1071 (progn (org-babel-hide-result-toggle)
1072 t
) ;; to signal that we took action
1073 nil
))) ;; to signal that we did not
1075 (defun org-babel-hide-result-toggle (&optional force
)
1076 "Toggle the visibility of the current result."
1080 (if (re-search-forward org-babel-result-regexp nil t
)
1081 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
1083 (while (looking-at org-babel-multi-line-header-regexp
)
1085 (goto-char (- (org-babel-result-end) 1)) (point)))
1087 (if (memq t
(mapcar (lambda (overlay)
1088 (eq (overlay-get overlay
'invisible
)
1089 'org-babel-hide-result
))
1090 (overlays-at start
)))
1091 (if (or (not force
) (eq force
'off
))
1093 (when (member ov org-babel-hide-result-overlays
)
1094 (setq org-babel-hide-result-overlays
1095 (delq ov org-babel-hide-result-overlays
)))
1096 (when (eq (overlay-get ov
'invisible
)
1097 'org-babel-hide-result
)
1098 (delete-overlay ov
)))
1099 (overlays-at start
)))
1100 (setq ov
(make-overlay start end
))
1101 (overlay-put ov
'invisible
'org-babel-hide-result
)
1102 ;; make the block accessible to isearch
1104 ov
'isearch-open-invisible
1106 (when (member ov org-babel-hide-result-overlays
)
1107 (setq org-babel-hide-result-overlays
1108 (delq ov org-babel-hide-result-overlays
)))
1109 (when (eq (overlay-get ov
'invisible
)
1110 'org-babel-hide-result
)
1111 (delete-overlay ov
))))
1112 (push ov org-babel-hide-result-overlays
)))
1113 (error "Not looking at a result line"))))
1115 ;; org-tab-after-check-for-cycling-hook
1116 (add-hook 'org-tab-first-hook
'org-babel-hide-result-toggle-maybe
)
1117 ;; Remove overlays when changing major mode
1118 (add-hook 'org-mode-hook
1119 (lambda () (org-add-hook 'change-major-mode-hook
1120 'org-babel-show-result-all
'append
'local
)))
1122 (defvar org-file-properties
)
1123 (defun org-babel-params-from-properties (&optional lang
)
1124 "Retrieve parameters specified as properties.
1125 Return an association list of any source block params which
1126 may be specified in the properties of the current outline entry."
1129 (org-babel-parse-multiple-vars
1132 (lambda (header-arg)
1133 (and (setq val
(org-entry-get (point) header-arg t
))
1134 (cons (intern (concat ":" header-arg
))
1135 (org-babel-read val
))))
1139 org-babel-header-arg-names
1141 (setq sym
(intern (concat "org-babel-header-arg-names:"
1143 (and (boundp sym
) (eval sym
)))))))))))
1145 (defvar org-src-preserve-indentation
)
1146 (defun org-babel-parse-src-block-match ()
1147 "Parse the results from a match of the `org-babel-src-block-regexp'."
1148 (let* ((block-indentation (length (match-string 1)))
1149 (lang (org-babel-clean-text-properties (match-string 2)))
1150 (lang-headers (intern (concat "org-babel-default-header-args:" lang
)))
1151 (switches (match-string 3))
1152 (body (org-babel-clean-text-properties
1153 (let* ((body (match-string 5))
1154 (sub-length (- (length body
) 1)))
1155 (if (and (> sub-length
0)
1156 (string= "\n" (substring body sub-length
)))
1157 (substring body
0 sub-length
)
1159 (preserve-indentation (or org-src-preserve-indentation
1160 (string-match "-i\\>" switches
))))
1162 ;; get block body less properties, protective commas, and indentation
1165 (insert (org-babel-strip-protective-commas body lang
))
1166 (unless preserve-indentation
(org-do-remove-indentation))
1168 (org-babel-merge-params
1169 org-babel-default-header-args
1170 (org-babel-params-from-properties lang
)
1171 (if (boundp lang-headers
) (eval lang-headers
) nil
)
1172 (org-babel-parse-header-arguments
1173 (org-babel-clean-text-properties (or (match-string 4) ""))))
1175 block-indentation
)))
1177 (defun org-babel-parse-inline-src-block-match ()
1178 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
1179 (let* ((lang (org-babel-clean-text-properties (match-string 2)))
1180 (lang-headers (intern (concat "org-babel-default-header-args:" lang
))))
1182 (org-babel-strip-protective-commas
1183 (org-babel-clean-text-properties (match-string 5)) lang
)
1184 (org-babel-merge-params
1185 org-babel-default-inline-header-args
1186 (org-babel-params-from-properties lang
)
1187 (if (boundp lang-headers
) (eval lang-headers
) nil
)
1188 (org-babel-parse-header-arguments
1189 (org-babel-clean-text-properties (or (match-string 4) "")))))))
1191 (defun org-babel-balanced-split (string alts
)
1192 "Split STRING on instances of ALTS.
1193 ALTS is a cons of two character options where each option may be
1194 either the numeric code of a single character or a list of
1195 character alternatives. For example to split on balanced
1196 instances of \"[ \t]:\" set ALTS to '((32 9) . 58)."
1197 (flet ((matches (ch spec
) (if (listp spec
) (member ch spec
) (equal spec ch
)))
1200 (and (matches ch
(cdr alts
))
1201 (matches last
(car alts
)))
1202 (matches ch alts
))))
1203 (let ((balance 0) (quote nil
) (partial nil
) (lst nil
) (last 0))
1204 (mapc (lambda (ch) ; split on [], (), "" balanced instances of [ \t]:
1205 (setq balance
(+ balance
1206 (cond ((or (equal 91 ch
) (equal 40 ch
)) 1)
1207 ((or (equal 93 ch
) (equal 41 ch
)) -
1)
1209 (when (and (equal 34 ch
) (not (equal 92 last
)))
1210 (setq quote
(not quote
)))
1211 (setq partial
(cons ch partial
))
1212 (when (and (= balance
0) (not quote
) (matched ch last
))
1213 (setq lst
(cons (apply #'string
(nreverse
1220 (string-to-list string
))
1221 (nreverse (cons (apply #'string
(nreverse partial
)) lst
)))))
1223 (defun org-babel-join-splits-near-ch (ch list
)
1224 "Join splits where \"=\" is on either end of the split."
1225 (flet ((last= (str) (= ch
(aref str
(1- (length str
)))))
1226 (first= (str) (= ch
(aref str
0))))
1228 (org-reduce (lambda (acc el
)
1229 (let ((head (car acc
)))
1230 (if (and head
(or (last= head
) (first= el
)))
1231 (cons (concat head el
) (cdr acc
))
1233 list
:initial-value nil
))))
1235 (defun org-babel-parse-header-arguments (arg-string)
1236 "Parse a string of header arguments returning an alist."
1237 (when (> (length arg-string
) 0)
1238 (org-babel-parse-multiple-vars
1243 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1245 (cons (intern (match-string 1 arg
))
1246 (org-babel-read (org-babel-chomp (match-string 2 arg
))))
1247 (cons (intern (org-babel-chomp arg
)) nil
)))
1249 (cons (car raw
) (mapcar (lambda (r) (concat ":" r
)) (cdr raw
))))
1250 (org-babel-balanced-split arg-string
'((32 9) .
58))))))))
1252 (defun org-babel-parse-multiple-vars (header-arguments)
1253 "Expand multiple variable assignments behind a single :var keyword.
1255 This allows expression of multiple variables with one :var as
1258 #+PROPERTY: var foo=1, bar=2"
1260 (mapc (lambda (pair)
1261 (if (eq (car pair
) :var
)
1262 (mapcar (lambda (v) (push (cons :var
(org-babel-trim v
)) results
))
1263 (org-babel-join-splits-near-ch
1264 61 (org-babel-balanced-split (cdr pair
) 32)))
1265 (push pair results
)))
1267 (nreverse results
)))
1269 (defun org-babel-process-params (params)
1270 "Expand variables in PARAMS and add summary parameters."
1271 (let* ((processed-vars (mapcar (lambda (el)
1272 (if (consp (cdr el
))
1274 (org-babel-ref-parse (cdr el
))))
1275 (org-babel-get-header params
:var
)))
1276 (vars-and-names (if (and (assoc :colname-names params
)
1277 (assoc :rowname-names params
))
1278 (list processed-vars
)
1279 (org-babel-disassemble-tables
1281 (cdr (assoc :hlines params
))
1282 (cdr (assoc :colnames params
))
1283 (cdr (assoc :rownames params
)))))
1284 (raw-result (or (cdr (assoc :results params
)) ""))
1285 (result-params (append
1286 (split-string (if (stringp raw-result
)
1289 (cdr (assoc :result-params params
)))))
1291 (mapcar (lambda (var) (cons :var var
)) (car vars-and-names
))
1293 (cons :colname-names
(or (cdr (assoc :colname-names params
))
1294 (cadr vars-and-names
)))
1295 (cons :rowname-names
(or (cdr (assoc :rowname-names params
))
1296 (caddr vars-and-names
)))
1297 (cons :result-params result-params
)
1298 (cons :result-type
(cond ((member "output" result-params
) 'output
)
1299 ((member "value" result-params
) 'value
)
1301 (org-babel-get-header params
:var
'other
))))
1303 ;; row and column names
1304 (defun org-babel-del-hlines (table)
1305 "Remove all 'hlines from TABLE."
1306 (remove 'hline table
))
1308 (defun org-babel-get-colnames (table)
1309 "Return the column names of TABLE.
1310 Return a cons cell, the `car' of which contains the TABLE less
1311 colnames, and the `cdr' of which contains a list of the column
1313 (if (equal 'hline
(nth 1 table
))
1314 (cons (cddr table
) (car table
))
1315 (cons (cdr table
) (car table
))))
1317 (defun org-babel-get-rownames (table)
1318 "Return the row names of TABLE.
1319 Return a cons cell, the `car' of which contains the TABLE less
1320 colnames, and the `cdr' of which contains a list of the column
1321 names. Note: this function removes any hlines in TABLE."
1322 (flet ((trans (table) (apply #'mapcar
* #'list table
)))
1323 (let* ((width (apply 'max
1324 (mapcar (lambda (el) (if (listp el
) (length el
) 0)) table
)))
1325 (table (trans (mapcar (lambda (row)
1326 (if (not (equal row
'hline
))
1330 (setq row
(cons 'hline row
)))
1333 (cons (mapcar (lambda (row) (if (equal (car row
) 'hline
) 'hline row
))
1334 (trans (cdr table
)))
1335 (remove 'hline
(car table
))))))
1337 (defun org-babel-put-colnames (table colnames
)
1338 "Add COLNAMES to TABLE if they exist."
1339 (if colnames
(apply 'list colnames
'hline table
) table
))
1341 (defun org-babel-put-rownames (table rownames
)
1342 "Add ROWNAMES to TABLE if they exist."
1344 (mapcar (lambda (row)
1346 (cons (or (pop rownames
) "") row
)
1350 (defun org-babel-pick-name (names selector
)
1351 "Select one out of an alist of row or column names.
1352 SELECTOR can be either a list of names in which case those names
1353 will be returned directly, or an index into the list NAMES in
1354 which case the indexed names will be return."
1355 (if (listp selector
)
1358 (if (and selector
(symbolp selector
) (not (equal t selector
)))
1359 (cdr (assoc selector names
))
1360 (if (integerp selector
)
1361 (nth (- selector
1) names
)
1362 (cdr (car (last names
))))))))
1364 (defun org-babel-disassemble-tables (vars hlines colnames rownames
)
1365 "Parse tables for further processing.
1366 Process the variables in VARS according to the HLINES,
1367 ROWNAMES and COLNAMES header arguments. Return a list consisting
1368 of the vars, cnames and rnames."
1369 (let (cnames rnames
)
1373 (when (listp (cdr var
))
1374 (when (and (not (equal colnames
"no"))
1375 (or colnames
(and (equal (nth 1 (cdr var
)) 'hline
)
1376 (not (member 'hline
(cddr (cdr var
)))))))
1377 (let ((both (org-babel-get-colnames (cdr var
))))
1378 (setq cnames
(cons (cons (car var
) (cdr both
))
1380 (setq var
(cons (car var
) (car both
)))))
1381 (when (and rownames
(not (equal rownames
"no")))
1382 (let ((both (org-babel-get-rownames (cdr var
))))
1383 (setq rnames
(cons (cons (car var
) (cdr both
))
1385 (setq var
(cons (car var
) (car both
)))))
1386 (when (and hlines
(not (equal hlines
"yes")))
1387 (setq var
(cons (car var
) (org-babel-del-hlines (cdr var
))))))
1390 (reverse cnames
) (reverse rnames
))))
1392 (defun org-babel-reassemble-table (table colnames rownames
)
1393 "Add column and row names to a table.
1394 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1395 to the table for reinsertion to org-mode."
1398 (if (and colnames
(listp (car table
)) (= (length (car table
))
1400 (org-babel-put-colnames table colnames
) table
))
1401 (if (and rownames
(= (length table
) (length rownames
)))
1402 (org-babel-put-rownames table rownames
) table
))
1405 (defun org-babel-where-is-src-block-head ()
1406 "Find where the current source block begins.
1407 Return the point at the beginning of the current source
1408 block. Specifically at the beginning of the #+BEGIN_SRC line.
1409 If the point is not on a source block then return nil."
1410 (let ((initial (point)) top bottom
)
1412 (save-excursion ;; on a source name line or a #+header line
1413 (beginning-of-line 1)
1414 (and (or (looking-at org-babel-src-name-regexp
)
1415 (looking-at org-babel-multi-line-header-regexp
))
1417 (while (and (forward-line 1)
1418 (looking-at org-babel-multi-line-header-regexp
)))
1419 (looking-at org-babel-src-block-regexp
))
1421 (save-excursion ;; on a #+begin_src line
1422 (beginning-of-line 1)
1423 (and (looking-at org-babel-src-block-regexp
)
1425 (save-excursion ;; inside a src block
1427 (re-search-backward "^[ \t]*#\\+begin_src" nil t
) (setq top
(point))
1428 (re-search-forward "^[ \t]*#\\+end_src" nil t
) (setq bottom
(point))
1429 (< top initial
) (< initial bottom
)
1430 (progn (goto-char top
) (beginning-of-line 1)
1431 (looking-at org-babel-src-block-regexp
))
1435 (defun org-babel-goto-src-block-head ()
1436 "Go to the beginning of the current code block."
1439 (if head
(goto-char head
) (error "not currently in a code block")))
1440 (org-babel-where-is-src-block-head)))
1443 (defun org-babel-goto-named-src-block (name)
1444 "Go to a named source-code block."
1446 (let ((completion-ignore-case t
))
1447 (list (org-icompleting-read "source-block name: "
1448 (org-babel-src-block-names) nil t
))))
1449 (let ((point (org-babel-find-named-block name
)))
1451 ;; taken from `org-open-at-point'
1452 (progn (goto-char point
) (org-show-context))
1453 (message "source-code block '%s' not found in this buffer" name
))))
1455 (defun org-babel-find-named-block (name)
1456 "Find a named source-code block.
1457 Return the location of the source block identified by source
1458 NAME, or nil if no such block exists. Set match data according to
1459 org-babel-named-src-block-regexp."
1461 (let ((case-fold-search t
)
1462 (regexp (org-babel-named-src-block-regexp-for-name name
)) msg
)
1463 (goto-char (point-min))
1464 (when (or (re-search-forward regexp nil t
)
1465 (re-search-backward regexp nil t
))
1466 (match-beginning 0)))))
1468 (defun org-babel-src-block-names (&optional file
)
1469 "Returns the names of source blocks in FILE or the current buffer."
1471 (when file
(find-file file
)) (goto-char (point-min))
1473 (while (re-search-forward org-babel-src-name-w-name-regexp nil t
)
1474 (setq names
(cons (match-string 3) names
)))
1478 (defun org-babel-goto-named-result (name)
1479 "Go to a named result."
1481 (let ((completion-ignore-case t
))
1482 (list (org-icompleting-read "source-block name: "
1483 (org-babel-result-names) nil t
))))
1484 (let ((point (org-babel-find-named-result name
)))
1486 ;; taken from `org-open-at-point'
1487 (progn (goto-char point
) (org-show-context))
1488 (message "result '%s' not found in this buffer" name
))))
1490 (defun org-babel-find-named-result (name &optional point
)
1491 "Find a named result.
1492 Return the location of the result named NAME in the current
1493 buffer or nil if no such result exists."
1495 (goto-char (or point
(point-min)))
1496 (catch 'is-a-code-block
1497 (when (re-search-forward
1498 (concat org-babel-result-regexp
1499 "[ \t]" (regexp-quote name
) "[ \t\n\f\v\r]+") nil t
)
1500 (when (and (string= "name" (downcase (match-string 1)))
1501 (or (beginning-of-line 1)
1502 (looking-at org-babel-src-block-regexp
)
1503 (looking-at org-babel-multi-line-header-regexp
)))
1504 (throw 'is-a-code-block
(org-babel-find-named-result name
(point))))
1505 (beginning-of-line 0) (point)))))
1507 (defun org-babel-result-names (&optional file
)
1508 "Returns the names of results in FILE or the current buffer."
1510 (when file
(find-file file
)) (goto-char (point-min))
1512 (while (re-search-forward org-babel-result-w-name-regexp nil t
)
1513 (setq names
(cons (match-string 4) names
)))
1517 (defun org-babel-next-src-block (&optional arg
)
1518 "Jump to the next source block.
1519 With optional prefix argument ARG, jump forward ARG many source blocks."
1521 (when (looking-at org-babel-src-block-regexp
) (forward-char 1))
1523 (re-search-forward org-babel-src-block-regexp nil nil
(or arg
1))
1524 (error (error "No further code blocks")))
1525 (goto-char (match-beginning 0)) (org-show-context))
1528 (defun org-babel-previous-src-block (&optional arg
)
1529 "Jump to the previous source block.
1530 With optional prefix argument ARG, jump backward ARG many source blocks."
1533 (re-search-backward org-babel-src-block-regexp nil nil
(or arg
1))
1534 (error (error "No previous code blocks")))
1535 (goto-char (match-beginning 0)) (org-show-context))
1537 (defvar org-babel-load-languages
)
1540 (defun org-babel-mark-block ()
1541 "Mark current src block"
1547 (looking-at org-babel-src-block-regexp
))
1548 (push-mark (match-end 5) nil t
)
1549 (goto-char (match-beginning 5))))
1550 (org-babel-where-is-src-block-head)))
1552 (defun org-babel-demarcate-block (&optional arg
)
1553 "Wrap or split the code in the region or on the point.
1554 When called from inside of a code block the current block is
1555 split. When called from outside of a code block a new code block
1556 is created. In both cases if the region is demarcated and if the
1557 region is not active then the point is demarcated."
1559 (let ((info (org-babel-get-src-block-info 'light
))
1560 (headers (progn (org-babel-where-is-src-block-head)
1562 (stars (concat (make-string (or (org-current-level) 1) ?
*) " ")))
1568 (let ((lang (nth 0 info
))
1569 (indent (make-string (nth 5 info
) ?
)))
1570 (when (string-match "^[[:space:]]*$"
1571 (buffer-substring (point-at-bol)
1573 (delete-region (point-at-bol) (point-at-eol)))
1575 (if (looking-at "^") "" "\n")
1576 indent
"#+end_src\n"
1577 (if arg stars indent
) "\n"
1578 indent
"#+begin_src " lang
1579 (if (> (length headers
) 1)
1580 (concat " " headers
) headers
)
1581 (if (looking-at "[\n\r]")
1583 (concat "\n" (make-string (current-column) ?
)))))))
1584 (move-end-of-line 2))
1585 (sort (if (region-active-p) (list (mark) (point)) (list (point))) #'>))
1586 (let ((start (point))
1587 (lang (org-icompleting-read "Lang: "
1588 (mapcar (lambda (el) (symbol-name (car el
)))
1589 org-babel-load-languages
)))
1590 (body (delete-and-extract-region
1591 (if (region-active-p) (mark) (point)) (point))))
1592 (insert (concat (if (looking-at "^") "" "\n")
1593 (if arg
(concat stars
"\n") "")
1594 "#+begin_src " lang
"\n"
1596 (if (or (= (length body
) 0)
1597 (string-match "[\r\n]$" body
)) "" "\n")
1599 (goto-char start
) (move-end-of-line 1)))))
1601 (defvar org-babel-lob-one-liner-regexp
)
1602 (defun org-babel-where-is-src-block-result (&optional insert info hash indent
)
1603 "Find where the current source block results begin.
1604 Return the point at the beginning of the result of the current
1605 source block. Specifically at the beginning of the results line.
1606 If no result exists for this block then create a results line
1607 following the source block."
1609 (let* ((on-lob-line (save-excursion
1610 (beginning-of-line 1)
1611 (looking-at org-babel-lob-one-liner-regexp
)))
1612 (inlinep (when (org-babel-get-inline-src-block-matches)
1614 (name (if on-lob-line
1615 (mapconcat #'identity
(butlast (org-babel-lob-get-info)) "")
1616 (nth 4 (or info
(org-babel-get-src-block-info 'light
)))))
1617 (head (unless on-lob-line
(org-babel-where-is-src-block-head)))
1619 (when head
(goto-char head
))
1621 found
;; was there a result (before we potentially insert one)
1626 ;; - return t if it is found, else return nil
1627 ;; - if it does not need to be rebuilt, then don't set end
1628 ;; - if it does need to be rebuilt then do set end
1629 name
(setq beg
(org-babel-find-named-result name
))
1631 (when (and hash
(not (string= hash
(match-string 3))))
1632 (goto-char beg
) (setq end beg
) ;; beginning of result
1634 (delete-region end
(org-babel-result-end)) nil
)))
1637 ;; - return t if it is found, else return nil
1638 ;; - if it is found, and the hash doesn't match, delete and set end
1639 (or on-lob-line
(re-search-forward "^[ \t]*#\\+end_src" nil t
))
1640 (progn (end-of-line 1)
1641 (if (eobp) (insert "\n") (forward-char 1))
1644 (progn ;; unnamed results line already exists
1645 (re-search-forward "[^ \f\t\n\r\v]" nil t
)
1646 (beginning-of-line 1)
1648 (concat org-babel-result-regexp
"\n")))
1650 ;; must remove and rebuild if hash!=old-hash
1651 (if (and hash
(not (string= hash
(match-string 3))))
1655 end
(org-babel-result-end)))
1656 (setq end nil
)))))))))
1657 (if (and insert end
)
1661 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1666 (org-number-sequence 1 indent
) "")
1668 "#+" org-babel-results-keyword
1669 (when hash
(concat "["hash
"]"))
1671 (when name
(concat " " name
)) "\n"))
1672 (unless beg
(insert "\n") (backward-char))
1673 (beginning-of-line 0)
1674 (if hash
(org-babel-hide-hash))
1678 (defvar org-block-regexp
)
1679 (defun org-babel-read-result ()
1680 "Read the result at `point' into emacs-lisp."
1681 (let ((case-fold-search t
) result-string
)
1683 ((org-at-table-p) (org-babel-read-table))
1684 ((org-at-item-p) (org-babel-read-list))
1685 ((looking-at org-bracket-link-regexp
) (org-babel-read-link))
1686 ((looking-at org-block-regexp
) (org-babel-trim (match-string 4)))
1687 ((looking-at "^[ \t]*: ")
1690 (mapconcat (lambda (line)
1691 (if (and (> (length line
) 1)
1692 (string-match "^[ \t]*: \\(.+\\)" line
))
1693 (match-string 1 line
)
1697 (point) (org-babel-result-end)) "[\r\n]+")
1699 (or (org-babel-number-p result-string
) result-string
))
1700 ((looking-at org-babel-result-regexp
)
1701 (save-excursion (forward-line 1) (org-babel-read-result))))))
1703 (defun org-babel-read-table ()
1704 "Read the table at `point' into emacs-lisp."
1705 (mapcar (lambda (row)
1706 (if (and (symbolp row
) (equal row
'hline
)) row
1707 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
)) row
)))
1708 (org-table-to-lisp)))
1710 (defun org-babel-read-list ()
1711 "Read the list at `point' into emacs-lisp."
1712 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
))
1713 (mapcar #'cadr
(cdr (org-list-parse-list)))))
1715 (defvar org-link-types-re
)
1716 (defun org-babel-read-link ()
1717 "Read the link at `point' into emacs-lisp.
1718 If the path of the link is a file path it is expanded using
1719 `expand-file-name'."
1720 (let* ((case-fold-search t
)
1721 (raw (and (looking-at org-bracket-link-regexp
)
1722 (org-babel-clean-text-properties (match-string 1))))
1723 (type (and (string-match org-link-types-re raw
)
1724 (match-string 1 raw
))))
1726 ((not type
) (expand-file-name raw
))
1727 ((string= type
"file")
1728 (and (string-match "file\\(.*\\):\\(.+\\)" raw
)
1729 (expand-file-name (match-string 2 raw
))))
1732 (defun org-babel-format-result (result &optional sep
)
1733 "Format RESULT for writing to file."
1734 (flet ((echo-res (result)
1735 (if (stringp result
) result
(format "%S" result
))))
1744 (echo-res result
))))
1746 (defun org-babel-insert-result
1747 (result &optional result-params info hash indent lang
)
1748 "Insert RESULT into the current buffer.
1749 By default RESULT is inserted after the end of the
1750 current source block. With optional argument RESULT-PARAMS
1751 controls insertion of results in the org-mode file.
1752 RESULT-PARAMS can take the following values...
1754 replace - (default option) insert results after the source block
1755 replacing any previously inserted results
1757 silent -- no results are inserted
1759 file ---- the results are interpreted as a file path, and are
1760 inserted into the buffer using the Org-mode file syntax
1762 list ---- the results are interpreted as an Org-mode list.
1764 raw ----- results are added directly to the Org-mode file. This
1765 is a good option if you code block will output org-mode
1768 wrap ---- results are added directly to the Org-mode file as with
1769 \"raw\", but are wrapped in a RESULTS drawer, allowing
1770 them to later be replaced or removed automatically.
1772 org ----- similar in effect to raw, only the results are wrapped
1773 in an org code block. Similar to the raw option, on
1774 export the results will be interpreted as org-formatted
1775 text, however by wrapping the results in an org code
1776 block they can be replaced upon re-execution of the
1779 html ---- results are added inside of a #+BEGIN_HTML block. This
1780 is a good option if you code block will output html
1783 latex --- results are added inside of a #+BEGIN_LATEX block.
1784 This is a good option if you code block will output
1785 latex formatted text.
1787 code ---- the results are extracted in the syntax of the source
1788 code of the language being evaluated and are added
1789 inside of a #+BEGIN_SRC block with the source-code
1790 language set appropriately. Note this relies on the
1791 optional LANG argument."
1792 (if (stringp result
)
1794 (setq result
(org-babel-clean-text-properties result
))
1795 (when (member "file" result-params
)
1796 (setq result
(org-babel-result-to-file result
))))
1797 (unless (listp result
) (setq result
(format "%S" result
))))
1798 (if (and result-params
(member "silent" result-params
))
1800 (message (replace-regexp-in-string "%" "%%" (format "%S" result
)))
1805 (when (or (org-babel-get-inline-src-block-matches)
1806 (org-babel-get-lob-one-liner-matches))
1807 (goto-char (match-end 0))
1808 (insert (if (listp result
) "\n" " "))
1810 (existing-result (unless inlinep
1811 (org-babel-where-is-src-block-result
1812 t info hash indent
)))
1814 (cdr (assoc :results_switches
(nth 2 info
))))
1816 (when (and (stringp result
) ; ensure results end in a newline
1818 (> (length result
) 0)
1819 (not (or (string-equal (substring result -
1) "\n")
1820 (string-equal (substring result -
1) "\r"))))
1821 (setq result
(concat result
"\n")))
1822 (if (not existing-result
)
1823 (setq beg
(or inlinep
(point)))
1824 (goto-char existing-result
)
1826 (re-search-forward "#" nil t
)
1827 (setq indent
(- (current-column) 1)))
1831 ((member "replace" result-params
)
1832 (delete-region (point) (org-babel-result-end)))
1833 ((member "append" result-params
)
1834 (goto-char (org-babel-result-end)) (setq beg
(point-marker)))
1835 ((member "prepend" result-params
)))) ; already there
1836 (setq results-switches
1837 (if results-switches
(concat " " results-switches
) ""))
1838 (flet ((wrap (start finish
)
1839 (goto-char end
) (insert (concat finish
"\n"))
1840 (goto-char beg
) (insert (concat start
"\n"))
1841 (goto-char end
) (goto-char (point-at-eol))
1842 (setq end
(point-marker)))
1843 (proper-list-p (it) (and (listp it
) (null (cdr (last it
))))))
1844 ;; insert results based on type
1846 ;; do nothing for an empty result
1848 ;; insert a list if preferred
1849 ((member "list" result-params
)
1852 (org-list-to-generic
1855 (lambda (el) (list nil
(if (stringp el
) el
(format "%S" el
))))
1856 (if (listp result
) result
(list result
))))
1857 '(:splicep nil
:istart
"- " :iend
"\n")))
1859 ;; assume the result is a table if it's not a string
1860 ((proper-list-p result
)
1862 (insert (concat (orgtbl-to-orgtbl
1863 (if (or (eq 'hline
(car result
))
1864 (and (listp (car result
))
1865 (listp (cdr (car result
)))))
1866 result
(list result
))
1867 '(:fmt
(lambda (cell) (format "%s" cell
)))) "\n"))
1868 (goto-char beg
) (when (org-at-table-p) (org-table-align)))
1869 ((and (listp result
) (not (proper-list-p result
)))
1870 (insert (format "%s\n" result
)))
1871 ((member "file" result-params
)
1872 (when inlinep
(goto-char inlinep
))
1874 (t (goto-char beg
) (insert result
)))
1875 (when (proper-list-p result
) (goto-char (org-table-end)))
1876 (setq end
(point-marker))
1877 ;; possibly wrap result
1879 ((member "html" result-params
)
1880 (wrap "#+BEGIN_HTML" "#+END_HTML"))
1881 ((member "latex" result-params
)
1882 (wrap "#+BEGIN_LaTeX" "#+END_LaTeX"))
1883 ((member "code" result-params
)
1884 (wrap (format "#+BEGIN_SRC %s%s" (or lang
"none") results-switches
)
1886 ((member "org" result-params
)
1887 (wrap "#+BEGIN_ORG" "#+END_ORG"))
1888 ((member "raw" result-params
)
1889 (goto-char beg
) (if (org-at-table-p) (org-cycle)))
1890 ((member "wrap" result-params
)
1891 (wrap ":RESULTS:" ":END:"))
1892 ((and (not (proper-list-p result
))
1893 (not (member "file" result-params
)))
1894 (org-babel-examplize-region beg end results-switches
)
1895 (setq end
(point)))))
1896 ;; possibly indent the results to match the #+results line
1897 (when (and (not inlinep
) (numberp indent
) indent
(> indent
0)
1898 ;; in this case `table-align' does the work for us
1899 (not (and (listp result
)
1900 (member "append" result-params
))))
1901 (indent-rigidly beg end indent
))))
1903 (if (member "value" result-params
)
1904 (message "Code block returned no value.")
1905 (message "Code block produced no output."))
1906 (message "Code block evaluation complete."))))
1908 (defun org-babel-remove-result (&optional info
)
1909 "Remove the result of the current source block."
1911 (let ((location (org-babel-where-is-src-block-result nil info
)) start
)
1913 (setq start
(- location
1))
1915 (goto-char location
) (forward-line 1)
1916 (delete-region start
(org-babel-result-end))))))
1918 (defun org-babel-result-end ()
1919 "Return the point at the end of the current set of results"
1922 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
1923 ((org-at-item-p) (let* ((struct (org-list-struct))
1924 (prvs (org-list-prevs-alist struct
)))
1925 (org-list-get-list-end (point-at-bol) struct prvs
)))
1926 ((looking-at "^\\([ \t]*\\):RESULTS:")
1927 (progn (re-search-forward (concat "^" (match-string 1) ":END:"))
1928 (forward-char 1) (point)))
1930 (let ((case-fold-search t
)
1931 (blocks-re (regexp-opt
1932 (list "latex" "html" "example" "src" "result" "org"))))
1933 (if (looking-at (concat "[ \t]*#\\+begin_" blocks-re
))
1934 (progn (re-search-forward (concat "[ \t]*#\\+end_" blocks-re
) nil t
)
1936 (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
1940 (defun org-babel-result-to-file (result)
1941 "Convert RESULT into an `org-mode' link.
1942 If the `default-directory' is different from the containing
1943 file's directory then expand relative links."
1944 (flet ((cond-exp (file)
1945 (if (and default-directory
1947 (not (string= (expand-file-name default-directory
)
1949 (file-name-directory buffer-file-name
)))))
1950 (expand-file-name file default-directory
)
1952 (if (stringp result
)
1953 (format "[[file:%s]]" (cond-exp result
))
1954 (when (and (listp result
) (= 2 (length result
))
1955 (stringp (car result
)) (stringp (cadr result
)))
1956 (format "[[file:%s][%s]]" (car result
) (cadr result
))))))
1958 (defun org-babel-examplize-region (beg end
&optional results-switches
)
1959 "Comment out region using the inline '==' or ': ' org example quote."
1961 (flet ((chars-between (b e
)
1962 (not (string-match "^[\\s]*$" (buffer-substring b e
)))))
1963 (if (or (chars-between (save-excursion (goto-char beg
) (point-at-bol)) beg
)
1964 (chars-between end
(save-excursion (goto-char end
) (point-at-eol))))
1967 (insert (format "=%s=" (prog1 (buffer-substring beg end
)
1968 (delete-region beg end
)))))
1969 (let ((size (count-lines beg end
)))
1971 (cond ((= size
0)) ; do nothing for an empty result
1972 ((< size org-babel-min-lines-for-block-output
)
1975 (beginning-of-line 1) (insert ": ") (forward-line 1)))
1978 (insert (if results-switches
1979 (format "#+begin_example%s\n" results-switches
)
1980 "#+begin_example\n"))
1981 (if (markerp end
) (goto-char end
) (forward-char (- end beg
)))
1982 (insert "#+end_example\n"))))))))
1984 (defun org-babel-update-block-body (new-body)
1985 "Update the body of the current code block to NEW-BODY."
1986 (if (not (org-babel-where-is-src-block-head))
1987 (error "not in source block")
1989 (replace-match (concat (org-babel-trim new-body
) "\n") nil t nil
5))
1990 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
1992 (defun org-babel-merge-params (&rest plists
)
1993 "Combine all parameter association lists in PLISTS.
1994 Later elements of PLISTS override the values of previous elements.
1995 This takes into account some special considerations for certain
1996 parameters when merging lists."
1997 (let ((results-exclusive-groups
1998 (mapcar (lambda (group) (mapcar #'symbol-name group
))
1999 (cdr (assoc 'results org-babel-common-header-args-w-values
))))
2000 (exports-exclusive-groups
2001 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2002 (cdr (assoc 'exports org-babel-common-header-args-w-values
))))
2004 params results exports tangle noweb cache vars shebang comments padline
)
2005 (flet ((e-merge (exclusive-groups &rest result-params
)
2006 ;; maintain exclusivity of mutually exclusive parameters
2008 (mapc (lambda (new-params)
2009 (mapc (lambda (new-param)
2010 (mapc (lambda (exclusive-group)
2011 (when (member new-param exclusive-group
)
2012 (mapcar (lambda (excluded-param)
2019 (setq output
(org-uniquify
2020 (cons new-param output
))))
2030 (let ((name (if (listp (cdr pair
))
2032 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
2034 (intern (match-string 1 (cdr pair
)))))))
2038 (if (member name
(mapcar #'car vars
))
2042 (unless (equal (car p
) name
) p
))
2045 (list (cons name pair
))))
2046 ;; if no name is given and we already have named variables
2047 ;; then assign to named variables in order
2048 (if (and vars
(nth variable-index vars
))
2049 (prog1 (setf (cddr (nth variable-index vars
))
2050 (concat (symbol-name
2051 (car (nth variable-index vars
)))
2053 (incf variable-index
))
2054 (error "variable \"%s\" must be assigned a default value"
2057 (setq results
(e-merge results-exclusive-groups
2060 (let ((r (cdr pair
)))
2061 (if (stringp r
) r
(eval r
)))))))
2064 (setq results
(e-merge results-exclusive-groups
2066 (unless (or (member "both" exports
)
2067 (member "none" exports
)
2068 (member "code" exports
))
2069 (setq exports
(e-merge exports-exclusive-groups
2070 exports
'("results"))))
2071 (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))
2073 (setq exports
(e-merge exports-exclusive-groups
2074 exports
(split-string (cdr pair
)))))
2075 (:tangle
;; take the latest -- always overwrite
2076 (setq tangle
(or (list (cdr pair
)) tangle
)))
2078 (setq noweb
(e-merge '(("yes" "no" "tangle")) noweb
2079 (split-string (or (cdr pair
) "")))))
2081 (setq cache
(e-merge '(("yes" "no")) cache
2082 (split-string (or (cdr pair
) "")))))
2084 (setq padline
(e-merge '(("yes" "no")) padline
2085 (split-string (or (cdr pair
) "")))))
2086 (:shebang
;; take the latest -- always overwrite
2087 (setq shebang
(or (list (cdr pair
)) shebang
)))
2089 (setq comments
(e-merge '(("yes" "no")) comments
2090 (split-string (or (cdr pair
) "")))))
2091 (t ;; replace: this covers e.g. :session
2092 (setq params
(cons pair
(assq-delete-all (car pair
) params
))))))
2095 (setq vars
(reverse vars
))
2096 (while vars
(setq params
(cons (cons :var
(cddr (pop vars
))) params
)))
2099 (let ((key (intern (concat ":" (symbol-name hd
))))
2101 (setf params
(cons (cons key
(mapconcat 'identity val
" ")) params
))))
2102 '(results exports tangle noweb padline cache shebang comments
))
2105 (defvar *org-babel-use-quick-and-dirty-noweb-expansion
* nil
2106 "Set to true to use regular expressions to expand noweb references.
2107 This results in much faster noweb reference expansion but does
2108 not properly allow code blocks to inherit the \":noweb-ref\"
2109 header argument from buffer or subtree wide properties.")
2111 (defun org-babel-expand-noweb-references (&optional info parent-buffer
)
2112 "Expand Noweb references in the body of the current source code block.
2114 For example the following reference would be replaced with the
2115 body of the source-code block named 'example-block'.
2119 Note that any text preceding the <<foo>> construct on a line will
2120 be interposed between the lines of the replacement text. So for
2121 example if <<foo>> is placed behind a comment, then the entire
2122 replacement text will also be commented.
2124 This function must be called from inside of the buffer containing
2125 the source-code block which holds BODY.
2127 In addition the following syntax can be used to insert the
2128 results of evaluating the source-code block named 'example-block'.
2132 Any optional arguments can be passed to example-block by placing
2133 the arguments inside the parenthesis following the convention
2134 defined by `org-babel-lob'. For example
2136 <<example-block(a=9)>>
2138 would set the value of argument \"a\" equal to \"9\". Note that
2139 these arguments are not evaluated in the current source-code
2140 block but are passed literally to the \"example-block\"."
2141 (let* ((parent-buffer (or parent-buffer
(current-buffer)))
2142 (info (or info
(org-babel-get-src-block-info)))
2145 (comment (string= "noweb" (cdr (assoc :comments
(nth 2 info
)))))
2146 (rx-prefix (concat "\\(" org-babel-src-name-regexp
"\\|"
2147 ":noweb-ref[ \t]+" "\\)"))
2148 (new-body "") index source-name evaluate prefix blocks-in-buffer
)
2149 (flet ((nb-add (text) (setq new-body
(concat new-body text
)))
2152 (funcall (intern (concat lang
"-mode")))
2153 (comment-region (point) (progn (insert text
) (point)))
2154 (org-babel-trim (buffer-string)))))
2156 (insert body
) (goto-char (point-min))
2157 (setq index
(point))
2158 (while (and (re-search-forward "<<\\([^ \t\n].+?[^ \t\n]\\|[^ \t\n]\\)>>"
2160 (save-match-data (setf source-name
(match-string 1)))
2161 (save-match-data (setq evaluate
(string-match "\(.*\)" source-name
)))
2164 (buffer-substring (match-beginning 0)
2166 (beginning-of-line 1) (point)))))
2167 ;; add interval to new-body (removing noweb reference)
2168 (goto-char (match-beginning 0))
2169 (nb-add (buffer-substring index
(point)))
2170 (goto-char (match-end 0))
2171 (setq index
(point))
2173 (with-current-buffer parent-buffer
2176 (mapconcat ;; interpose PREFIX between every line
2180 (let ((raw (org-babel-ref-resolve source-name
)))
2181 (if (stringp raw
) raw
(format "%S" raw
)))
2183 ;; retrieve from the library of babel
2184 (nth 2 (assoc (intern source-name
)
2185 org-babel-library-of-babel
))
2186 ;; return the contents of headlines literally
2188 (when (org-babel-ref-goto-headline-id source-name
)
2189 (org-babel-ref-headline-body)))
2190 ;; find the expansion of reference in this buffer
2191 (let ((rx (concat rx-prefix source-name
"[ \t\n]"))
2194 (goto-char (point-min))
2195 (if *org-babel-use-quick-and-dirty-noweb-expansion
*
2196 (while (re-search-forward rx nil t
)
2197 (let* ((i (org-babel-get-src-block-info 'light
))
2198 (body (org-babel-expand-noweb-references i
))
2199 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2203 (concat (c-wrap (car cs
)) "\n"
2205 (c-wrap (cadr cs
))))
2206 (org-babel-tangle-comment-links i
))
2208 (setq expansion
(cons sep
(cons full expansion
)))))
2209 (org-babel-map-src-blocks nil
2210 (let ((i (org-babel-get-src-block-info 'light
)))
2211 (when (equal (or (cdr (assoc :noweb-ref
(nth 2 i
)))
2214 (let* ((body (org-babel-expand-noweb-references i
))
2215 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2219 (concat (c-wrap (car cs
)) "\n"
2221 (c-wrap (cadr cs
))))
2222 (org-babel-tangle-comment-links i
))
2225 (cons sep
(cons full expansion
)))))))))
2227 (mapconcat #'identity
(nreverse (cdr expansion
)) "")))
2228 ;; possibly raise an error if named block doesn't exist
2229 (if (member lang org-babel-noweb-error-langs
)
2231 "<<" source-name
">> "
2232 "could not be resolved (see "
2233 "`org-babel-noweb-error-langs')"))
2235 "[\n\r]") (concat "\n" prefix
))))))
2236 (nb-add (buffer-substring index
(point-max)))))
2239 (defun org-babel-clean-text-properties (text)
2240 "Strip all properties from text return."
2242 (set-text-properties 0 (length text
) nil text
) text
))
2244 (defun org-babel-strip-protective-commas (body &optional lang
)
2245 "Strip protective commas from bodies of source blocks."
2248 (if (and lang
(string= lang
"org"))
2249 (progn (goto-char (point-min))
2250 (while (re-search-forward "^[ \t]*\\(,\\)" nil t
)
2251 (replace-match "" nil nil nil
1)))
2252 (org-strip-protective-commas (point-min) (point-max)))
2255 (defun org-babel-script-escape (str &optional force
)
2256 "Safely convert tables into elisp lists."
2257 (let (in-single in-double out
)
2258 ((lambda (escaped) (condition-case nil
(org-babel-read escaped
) (error escaped
)))
2262 (or (and (string-equal "[" (substring str
0 1))
2263 (string-equal "]" (substring str -
1)))
2264 (and (string-equal "{" (substring str
0 1))
2265 (string-equal "}" (substring str -
1)))
2266 (and (string-equal "(" (substring str
0 1))
2267 (string-equal ")" (substring str -
1))))))
2277 (91 (if (or in-double in-single
) ; [
2280 (93 (if (or in-double in-single
) ; ]
2283 (123 (if (or in-double in-single
) ; {
2286 (125 (if (or in-double in-single
) ; }
2289 (44 (if (or in-double in-single
) ; ,
2290 (cons 44 out
) (cons 32 out
)))
2291 (39 (if in-double
; '
2293 (setq in-single
(not in-single
)) (cons 34 out
)))
2294 (34 (if in-single
; "
2295 (append (list 34 32) out
)
2296 (setq in-double
(not in-double
)) (cons 34 out
)))
2297 (t (cons ch out
)))))
2298 (string-to-list str
))
2299 (apply #'string
(reverse out
)))))
2302 (defun org-babel-read (cell &optional inhibit-lisp-eval
)
2303 "Convert the string value of CELL to a number if appropriate.
2304 Otherwise if cell looks like lisp (meaning it starts with a
2305 \"(\", \"'\", \"`\" or a \"[\") then read it as lisp, otherwise
2306 return it unmodified as a string. Optional argument NO-LISP-EVAL
2307 inhibits lisp evaluation for situations in which is it not
2309 (if (and (stringp cell
) (not (equal cell
"")))
2310 (or (org-babel-number-p cell
)
2311 (if (and (not inhibit-lisp-eval
)
2312 (member (substring cell
0 1) '("(" "'" "`" "[")))
2314 (if (string= (substring cell
0 1) "\"")
2316 (progn (set-text-properties 0 (length cell
) nil cell
) cell
))))
2319 (defun org-babel-number-p (string)
2320 "If STRING represents a number return its value."
2321 (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string
)
2322 (= (length (substring string
(match-beginning 0)
2325 (string-to-number string
)))
2327 (defun org-babel-import-elisp-from-file (file-name &optional separator
)
2328 "Read the results located at FILE-NAME into an elisp table.
2329 If the table is trivial, then return it as a scalar."
2331 (save-window-excursion
2335 (org-table-import file-name separator
)
2336 (delete-file file-name
)
2337 (setq result
(mapcar (lambda (row)
2338 (mapcar #'org-babel-string-read row
))
2339 (org-table-to-lisp))))
2341 (if (null (cdr result
)) ;; if result is trivial vector, then scalarize it
2342 (if (consp (car result
))
2343 (if (null (cdr (car result
)))
2349 (defun org-babel-string-read (cell)
2350 "Strip nested \"s from around strings."
2351 (org-babel-read (or (and (stringp cell
)
2352 (string-match "\\\"\\(.+\\)\\\"" cell
)
2353 (match-string 1 cell
))
2356 (defun org-babel-reverse-string (string)
2357 "Return the reverse of STRING."
2358 (apply 'string
(reverse (string-to-list string
))))
2360 (defun org-babel-chomp (string &optional regexp
)
2361 "Strip trailing spaces and carriage returns from STRING.
2362 Default regexp used is \"[ \f\t\n\r\v]\" but can be
2363 overwritten by specifying a regexp as a second argument."
2364 (let ((regexp (or regexp
"[ \f\t\n\r\v]")))
2365 (while (and (> (length string
) 0)
2366 (string-match regexp
(substring string -
1)))
2367 (setq string
(substring string
0 -
1)))
2370 (defun org-babel-trim (string &optional regexp
)
2371 "Strip leading and trailing spaces and carriage returns from STRING.
2372 Like `org-babel-chomp' only it runs on both the front and back
2374 (org-babel-chomp (org-babel-reverse-string
2375 (org-babel-chomp (org-babel-reverse-string string
) regexp
))
2378 (defvar org-babel-org-babel-call-process-region-original nil
)
2379 (defun org-babel-tramp-handle-call-process-region
2380 (start end program
&optional delete buffer display
&rest args
)
2381 "Use tramp to handle call-process-region.
2382 Fixes a bug in `tramp-handle-call-process-region'."
2383 (if (and (featurep 'tramp
) (file-remote-p default-directory
))
2384 (let ((tmpfile (tramp-compat-make-temp-file "")))
2385 (write-region start end tmpfile
)
2386 (when delete
(delete-region start end
))
2388 ;; (apply 'call-process program tmpfile buffer display args)
2390 (apply 'process-file program tmpfile buffer display args
)
2391 (delete-file tmpfile
)))
2392 ;; org-babel-call-process-region-original is the original emacs
2393 ;; definition. It is in scope from the let binding in
2394 ;; org-babel-execute-src-block
2395 (apply org-babel-call-process-region-original
2396 start end program delete buffer display args
)))
2398 (defun org-babel-local-file-name (file)
2399 "Return the local name component of FILE."
2400 (if (file-remote-p file
)
2402 (with-parsed-tramp-file-name file nil
2406 (defun org-babel-process-file-name (name &optional no-quote-p
)
2407 "Prepare NAME to be used in an external process.
2408 If NAME specifies a remote location, the remote portion of the
2409 name is removed, since in that case the process will be executing
2410 remotely. The file name is then processed by
2411 `expand-file-name'. Unless second argument NO-QUOTE-P is non-nil,
2412 the file name is additionally processed by
2413 `shell-quote-argument'"
2414 ((lambda (f) (if no-quote-p f
(shell-quote-argument f
)))
2415 (expand-file-name (org-babel-local-file-name name
))))
2417 (defvar org-babel-temporary-directory
)
2418 (unless (or noninteractive
(boundp 'org-babel-temporary-directory
))
2419 (defvar org-babel-temporary-directory
2420 (or (and (boundp 'org-babel-temporary-directory
)
2421 (file-exists-p org-babel-temporary-directory
)
2422 org-babel-temporary-directory
)
2423 (make-temp-file "babel-" t
))
2424 "Directory to hold temporary files created to execute code blocks.
2425 Used by `org-babel-temp-file'. This directory will be removed on
2428 (defun org-babel-temp-file (prefix &optional suffix
)
2429 "Create a temporary file in the `org-babel-temporary-directory'.
2430 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2431 value of `temporary-file-directory' temporarily set to the value
2432 of `org-babel-temporary-directory'."
2433 (if (file-remote-p default-directory
)
2435 (concat (file-remote-p default-directory
)
2437 prefix temporary-file-directory
)
2439 (let ((temporary-file-directory
2440 (or (and (boundp 'org-babel-temporary-directory
)
2441 (file-exists-p org-babel-temporary-directory
)
2442 org-babel-temporary-directory
)
2443 temporary-file-directory
)))
2444 (make-temp-file prefix nil suffix
))))
2446 (defun org-babel-remove-temporary-directory ()
2447 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2448 (when (and (boundp 'org-babel-temporary-directory
)
2449 (file-exists-p org-babel-temporary-directory
))
2450 ;; taken from `delete-directory' in files.el
2453 (mapc (lambda (file)
2454 ;; This test is equivalent to
2455 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2456 ;; but more efficient
2457 (if (eq t
(car (file-attributes file
)))
2458 (delete-directory file
)
2459 (delete-file file
)))
2460 ;; We do not want to delete "." and "..".
2461 (directory-files org-babel-temporary-directory
'full
2462 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2463 (delete-directory org-babel-temporary-directory
))
2465 (message "Failed to remove temporary Org-babel directory %s"
2466 (if (boundp 'org-babel-temporary-directory
)
2467 org-babel-temporary-directory
2468 "[directory not defined]"))))))
2470 (add-hook 'kill-emacs-hook
'org-babel-remove-temporary-directory
)