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 org-mark-ring-push
"org" (&optional pos buffer
))
37 (declare-function org-strip-protective-commas
"org" (beg end
))
38 (declare-function tramp-compat-make-temp-file
"tramp-compat"
39 (filename &optional dir-flag
))
40 (declare-function tramp-dissect-file-name
"tramp" (name &optional nodefault
))
41 (declare-function tramp-file-name-user
"tramp" (vec))
42 (declare-function tramp-file-name-host
"tramp" (vec))
43 (declare-function with-parsed-tramp-file-name
"tramp" (filename var
&rest body
))
44 (declare-function org-icompleting-read
"org" (&rest args
))
45 (declare-function org-edit-src-code
"org-src"
46 (&optional context code edit-buffer-name quietp
))
47 (declare-function org-edit-src-exit
"org-src" (&optional context
))
48 (declare-function org-open-at-point
"org" (&optional in-emacs reference-buffer
))
49 (declare-function org-save-outline-visibility
"org" (use-markers &rest body
))
50 (declare-function org-outline-overlay-data
"org" (&optional use-markers
))
51 (declare-function org-set-outline-overlay-data
"org" (data))
52 (declare-function org-narrow-to-subtree
"org" ())
53 (declare-function org-entry-get
"org"
54 (pom property
&optional inherit literal-nil
))
55 (declare-function org-make-options-regexp
"org" (kwds &optional extra
))
56 (declare-function org-do-remove-indentation
"org" (&optional n
))
57 (declare-function org-show-context
"org" (&optional key
))
58 (declare-function org-at-table-p
"org" (&optional table-type
))
59 (declare-function org-cycle
"org" (&optional arg
))
60 (declare-function org-uniquify
"org" (list))
61 (declare-function org-current-level
"org" ())
62 (declare-function org-table-import
"org-table" (file arg
))
63 (declare-function org-add-hook
"org-compat"
64 (hook function
&optional append local
))
65 (declare-function org-table-align
"org-table" ())
66 (declare-function org-table-end
"org-table" (&optional table-type
))
67 (declare-function orgtbl-to-generic
"org-table" (table params
))
68 (declare-function orgtbl-to-orgtbl
"org-table" (table params
))
69 (declare-function org-babel-tangle-comment-links
"ob-tangle" (&optional info
))
70 (declare-function org-babel-lob-get-info
"ob-lob" nil
)
71 (declare-function org-babel-ref-split-args
"ob-ref" (arg-string))
72 (declare-function org-babel-ref-parse
"ob-ref" (assignment))
73 (declare-function org-babel-ref-resolve
"ob-ref" (ref))
74 (declare-function org-babel-ref-goto-headline-id
"ob-ref" (id))
75 (declare-function org-babel-ref-headline-body
"ob-ref" ())
76 (declare-function org-babel-lob-execute-maybe
"ob-lob" ())
77 (declare-function org-number-sequence
"org-compat" (from &optional to inc
))
78 (declare-function org-at-item-p
"org-list" ())
79 (declare-function org-list-parse-list
"org-list" (&optional delete
))
80 (declare-function org-list-to-generic
"org-list" (LIST PARAMS
))
81 (declare-function org-list-struct
"org-list" ())
82 (declare-function org-list-prevs-alist
"org-list" (struct))
83 (declare-function org-list-get-list-end
"org-list" (item struct prevs
))
85 (defgroup org-babel nil
86 "Code block evaluation and management in `org-mode' documents."
90 (defcustom org-confirm-babel-evaluate t
91 "Confirm before evaluation.
92 Require confirmation before interactively evaluating code
93 blocks in Org-mode buffers. The default value of this variable
94 is t, meaning confirmation is required for any code block
95 evaluation. This variable can be set to nil to inhibit any
96 future confirmation requests. This variable can also be set to a
97 function which takes two arguments the language of the code block
98 and the body of the code block. Such a function should then
99 return a non-nil value if the user should be prompted for
100 execution or nil if no prompt is required.
102 Warning: Disabling confirmation may result in accidental
103 evaluation of potentially harmful code. It may be advisable
104 remove code block execution from C-c C-c as further protection
105 against accidental code block evaluation. The
106 `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
107 remove code block execution from the C-c C-c keybinding."
110 :type
'(choice boolean function
))
111 ;; don't allow this variable to be changed through file settings
112 (put 'org-confirm-babel-evaluate
'safe-local-variable
(lambda (x) (eq x t
)))
114 (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
115 "Remove code block evaluation from the C-c C-c key binding."
120 (defcustom org-babel-results-keyword
"RESULTS"
121 "Keyword used to name results generated by code blocks.
122 Should be either RESULTS or NAME however any capitalization may
127 (defcustom org-babel-noweb-wrap-start
"<<"
128 "String used to begin a noweb reference in a code block.
129 See also `org-babel-noweb-wrap-end'."
133 (defcustom org-babel-noweb-wrap-end
">>"
134 "String used to end a noweb reference in a code block.
135 See also `org-babel-noweb-wrap-start'."
139 (defun org-babel-noweb-wrap (&optional regexp
)
140 (concat org-babel-noweb-wrap-start
141 (or regexp
"\\([^ \t\n].+?[^ \t]\\|[^ \t\n]\\)")
142 org-babel-noweb-wrap-end
))
144 (defvar org-babel-src-name-regexp
145 "^[ \t]*#\\+name:[ \t]*"
146 "Regular expression used to match a source name line.")
148 (defvar org-babel-multi-line-header-regexp
149 "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
150 "Regular expression used to match multi-line header arguments.")
152 (defvar org-babel-src-name-w-name-regexp
153 (concat org-babel-src-name-regexp
155 org-babel-multi-line-header-regexp
157 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)")
158 "Regular expression matching source name lines with a name.")
160 (defvar org-babel-src-block-regexp
162 ;; (1) indentation (2) lang
163 "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
165 "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
166 ;; (4) header arguments
169 "\\([^\000]*?\n\\)?[ \t]*#\\+end_src")
170 "Regexp used to identify code blocks.")
172 (defvar org-babel-inline-src-block-regexp
174 ;; (1) replacement target (2) lang
175 "\\(?:^\\|[^-[:alnum:]]\\)\\(src_\\([^ \f\t\n\r\v]+\\)"
176 ;; (3,4) (unused, headers)
177 "\\(\\|\\[\\(.*?\\)\\]\\)"
179 "{\\([^\f\n\r\v]+?\\)}\\)")
180 "Regexp used to identify inline src-blocks.")
182 (defun org-babel-get-header (params key
&optional others
)
183 "Select only header argument of type KEY from a list.
184 Optional argument OTHERS indicates that only the header that do
185 not match KEY should be returned."
188 (lambda (p) (when (funcall (if others
#'not
#'identity
) (eq (car p
) key
)) p
))
191 (defun org-babel-get-inline-src-block-matches()
192 "Set match data if within body of an inline source block.
193 Returns non-nil if match-data set"
194 (let ((src-at-0-p (save-excursion
195 (beginning-of-line 1)
196 (string= "src" (thing-at-point 'word
))))
197 (first-line-p (= 1 (line-number-at-pos)))
199 (let ((search-for (cond ((and src-at-0-p first-line-p
"src_"))
200 (first-line-p "[[:punct:] \t]src_")
201 (t "[[:punct:] \f\t\n\r\v]src_")))
202 (lower-limit (if first-line-p
204 (- (point-at-bol) 1))))
206 (when (or (and src-at-0-p
(bobp))
207 (and (re-search-forward "}" (point-at-eol) t
)
208 (re-search-backward search-for lower-limit t
)
210 (when (looking-at org-babel-inline-src-block-regexp
)
213 (defvar org-babel-inline-lob-one-liner-regexp
)
214 (defun org-babel-get-lob-one-liner-matches()
215 "Set match data if on line of an lob one liner.
216 Returns non-nil if match-data set"
218 (unless (= (point) (point-at-bol)) ;; move before inline block
219 (re-search-backward "[ \f\t\n\r\v]" nil t
))
220 (if (looking-at org-babel-inline-lob-one-liner-regexp
)
224 (defun org-babel-get-src-block-info (&optional light
)
225 "Get information on the current source block.
227 Optional argument LIGHT does not resolve remote variable
228 references; a process which could likely result in the execution
229 of other code blocks.
232 (language body header-arguments-alist switches name indent)."
233 (let ((case-fold-search t
) head info name indent
)
235 (if (setq head
(org-babel-where-is-src-block-head))
238 (setq info
(org-babel-parse-src-block-match))
239 (setq indent
(car (last info
)))
240 (setq info
(butlast info
))
241 (while (and (forward-line -
1)
242 (looking-at org-babel-multi-line-header-regexp
))
244 (org-babel-merge-params
246 (org-babel-parse-header-arguments (match-string 1)))))
247 (when (looking-at org-babel-src-name-w-name-regexp
)
248 (setq name
(org-babel-clean-text-properties (match-string 3)))
249 (when (and (match-string 5) (> (length (match-string 5)) 0))
250 (setf (nth 2 info
) ;; merge functional-syntax vars and header-args
251 (org-babel-merge-params
253 (lambda (ref) (cons :var ref
))
255 (lambda (var) ;; check that each variable is initialized
256 (if (string-match ".+=.+" var
)
259 "variable \"%s\"%s must be assigned a default value"
260 var
(if name
(format " in block \"%s\"" name
) ""))))
261 (org-babel-ref-split-args (match-string 5))))
263 ;; inline source block
264 (when (org-babel-get-inline-src-block-matches)
265 (setq info
(org-babel-parse-inline-src-block-match))))
266 ;; resolve variable references and add summary parameters
267 (when (and info
(not light
))
268 (setf (nth 2 info
) (org-babel-process-params (nth 2 info
))))
269 (when info
(append info
(list name indent
)))))
271 (defvar org-current-export-file
) ; dynamically bound
272 (defun org-babel-confirm-evaluate (info)
273 "Confirm evaluation of the code block INFO.
274 This behavior can be suppressed by setting the value of
275 `org-confirm-babel-evaluate' to nil, in which case all future
276 interactive code block evaluations will proceed without any
277 confirmation from the user.
279 Note disabling confirmation may result in accidental evaluation
280 of potentially harmful code."
281 (let* ((eval (or (cdr (assoc :eval
(nth 2 info
)))
282 (when (assoc :noeval
(nth 2 info
)) "no")))
283 (query (cond ((equal eval
"query") t
)
284 ((and org-current-export-file
285 (equal eval
"query-export")) t
)
286 ((functionp org-confirm-babel-evaluate
)
287 (funcall org-confirm-babel-evaluate
288 (nth 0 info
) (nth 1 info
)))
289 (t org-confirm-babel-evaluate
))))
290 (if (or (equal eval
"never") (equal eval
"no")
291 (and org-current-export-file
(or (equal eval
"no-export")
292 (equal eval
"never-export")))
295 (format "Evaluate this%scode block%son your system? "
296 (if info
(format " %s " (nth 0 info
)) " ")
298 (format " (%s) " (nth 4 info
)) " "))))))
299 (prog1 nil
(message "Evaluation %s"
300 (if (or (equal eval
"never") (equal eval
"no")
301 (equal eval
"no-export")
302 (equal eval
"never-export"))
303 "Disabled" "Aborted")))
307 (defun org-babel-execute-safely-maybe ()
308 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
309 (org-babel-execute-maybe)))
311 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-execute-safely-maybe
)
314 (defun org-babel-execute-maybe ()
316 (or (org-babel-execute-src-block-maybe)
317 (org-babel-lob-execute-maybe)))
319 (defun org-babel-execute-src-block-maybe ()
320 "Conditionally execute a source block.
321 Detect if this is context for a Babel src-block and if so
322 then run `org-babel-execute-src-block'."
324 (let ((info (org-babel-get-src-block-info)))
326 (progn (org-babel-eval-wipe-error-buffer)
327 (org-babel-execute-src-block current-prefix-arg info
) t
) nil
)))
330 (defun org-babel-view-src-block-info ()
331 "Display information on the current source block.
332 This includes header arguments, language and name, and is largely
333 a window into the `org-babel-get-src-block-info' function."
335 (let ((info (org-babel-get-src-block-info 'light
)))
336 (flet ((full (it) (> (length it
) 0))
337 (printf (fmt &rest args
) (princ (apply #'format fmt args
))))
339 (with-help-window (help-buffer)
340 (let ((name (nth 4 info
))
342 (switches (nth 3 info
))
343 (header-args (nth 2 info
)))
344 (when name
(printf "Name: %s\n" name
))
345 (when lang
(printf "Lang: %s\n" lang
))
346 (when (full switches
) (printf "Switches: %s\n" switches
))
347 (printf "Header Arguments:\n")
348 (dolist (pair (sort header-args
349 (lambda (a b
) (string< (symbol-name (car a
))
350 (symbol-name (car b
))))))
351 (when (full (cdr pair
))
352 (printf "\t%S%s\t%s\n"
354 (if (> (length (format "%S" (car pair
))) 7) "" "\t")
358 (defun org-babel-expand-src-block-maybe ()
359 "Conditionally expand a source block.
360 Detect if this is context for a org-babel src-block and if so
361 then run `org-babel-expand-src-block'."
363 (let ((info (org-babel-get-src-block-info)))
365 (progn (org-babel-expand-src-block current-prefix-arg info
) t
)
369 (defun org-babel-load-in-session-maybe ()
370 "Conditionally load a source block in a session.
371 Detect if this is context for a org-babel src-block and if so
372 then run `org-babel-load-in-session'."
374 (let ((info (org-babel-get-src-block-info)))
376 (progn (org-babel-load-in-session current-prefix-arg info
) t
)
379 (add-hook 'org-metaup-hook
'org-babel-load-in-session-maybe
)
382 (defun org-babel-pop-to-session-maybe ()
383 "Conditionally pop to a session.
384 Detect if this is context for a org-babel src-block and if so
385 then run `org-babel-pop-to-session'."
387 (let ((info (org-babel-get-src-block-info)))
388 (if info
(progn (org-babel-pop-to-session current-prefix-arg info
) t
) nil
)))
390 (add-hook 'org-metadown-hook
'org-babel-pop-to-session-maybe
)
392 (defconst org-babel-common-header-args-w-values
393 '((cache .
((no yes
)))
395 (colnames .
((nil no yes
)))
396 (comments .
((no link yes org both noweb
)))
398 (eval .
((never query
)))
399 (exports .
((code results both none
)))
401 (hlines .
((no yes
)))
402 (mkdirp .
((yes no
)))
405 (noweb .
((yes no tangle no-export strip-export
)))
408 (padline .
((yes no
)))
409 (results .
((file list vector table scalar verbatim
)
410 (raw org html latex code pp wrap
)
411 (replace silent append prepend
)
413 (rownames .
((no yes
)))
417 (tangle .
((tangle yes no
:any
)))
421 (defconst org-babel-header-arg-names
422 (mapcar #'car org-babel-common-header-args-w-values
)
423 "Common header arguments used by org-babel.
424 Note that individual languages may define their own language
425 specific header arguments as well.")
427 (defvar org-babel-default-header-args
428 '((:session .
"none") (:results .
"replace") (:exports .
"code")
429 (:cache .
"no") (:noweb .
"no") (:hlines .
"no") (:tangle .
"no")
430 (:padnewline .
"yes"))
431 "Default arguments to use when evaluating a source block.")
433 (defvar org-babel-default-inline-header-args
434 '((:session .
"none") (:results .
"replace") (:exports .
"results"))
435 "Default arguments to use when evaluating an inline source block.")
437 (defvar org-babel-data-names
'("TBLNAME" "RESULTS" "NAME"))
439 (defvar org-babel-result-regexp
440 (concat "^[ \t]*#\\+"
441 (regexp-opt org-babel-data-names t
)
442 "\\(\\[\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*")
443 "Regular expression used to match result lines.
444 If the results are associated with a hash key then the hash will
445 be saved in the second match data.")
447 (defvar org-babel-result-w-name-regexp
448 (concat org-babel-result-regexp
449 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
451 (defvar org-babel-min-lines-for-block-output
10
452 "The minimum number of lines for block output.
453 If number of lines of output is equal to or exceeds this
454 value, the output is placed in a #+begin_example...#+end_example
455 block. Otherwise the output is marked as literal by inserting
456 colons at the starts of the lines. This variable only takes
457 effect if the :results output option is in effect.")
459 (defvar org-babel-noweb-error-langs nil
460 "Languages for which Babel will raise literate programming errors.
461 List of languages for which errors should be raised when the
462 source code block satisfying a noweb reference in this language
463 can not be resolved.")
465 (defvar org-babel-hash-show
4
466 "Number of initial characters to show of a hidden results hash.")
468 (defvar org-babel-after-execute-hook nil
469 "Hook for functions to be called after `org-babel-execute-src-block'")
471 (defun org-babel-named-src-block-regexp-for-name (name)
472 "This generates a regexp used to match a src block named NAME."
473 (concat org-babel-src-name-regexp
(regexp-quote name
)
474 "\\([ \t]\\|$\\|(\\)" ".*[\r\n]"
475 (substring org-babel-src-block-regexp
1)))
477 (defun org-babel-named-data-regexp-for-name (name)
478 "This generates a regexp used to match data named NAME."
479 (concat org-babel-result-regexp
(regexp-quote name
) "\\([ \t]\\|$\\)"))
482 (defvar call-process-region
)
485 (defun org-babel-execute-src-block (&optional arg info params
)
486 "Execute the current source code block.
487 Insert the results of execution into the buffer. Source code
488 execution and the collection and formatting of results can be
489 controlled through a variety of header arguments.
491 With prefix argument ARG, force re-execution even if an existing
492 result cached in the buffer would otherwise have been returned.
494 Optionally supply a value for INFO in the form returned by
495 `org-babel-get-src-block-info'.
497 Optionally supply a value for PARAMS which will be merged with
498 the header arguments specified at the front of the source code
501 (let ((info (or info
(org-babel-get-src-block-info))))
502 (when (org-babel-confirm-evaluate
504 (setf (nth 2 i
) (org-babel-merge-params (nth 2 info
) params
))
506 (let* ((lang (nth 0 info
))
508 (org-babel-process-params
509 (org-babel-merge-params (nth 2 info
) params
))
511 (cache?
(and (not arg
) (cdr (assoc :cache params
))
512 (string= "yes" (cdr (assoc :cache params
)))))
513 (result-params (cdr (assoc :result-params params
)))
514 (new-hash (when cache?
(org-babel-sha1-hash info
)))
515 (old-hash (when cache?
(org-babel-current-result-hash)))
516 (body (setf (nth 1 info
)
517 (if (org-babel-noweb-p params
:eval
)
518 (org-babel-expand-noweb-references info
)
520 (dir (cdr (assoc :dir params
)))
522 (or (and dir
(file-name-as-directory dir
)) default-directory
))
523 (org-babel-call-process-region-original
524 (if (boundp 'org-babel-call-process-region-original
)
525 org-babel-call-process-region-original
526 (symbol-function 'call-process-region
)))
527 (indent (car (last info
)))
530 (flet ((call-process-region (&rest args
)
531 (apply 'org-babel-tramp-handle-call-process-region args
)))
532 (flet ((lang-check (f)
533 (let ((f (intern (concat "org-babel-execute:" f
))))
534 (when (fboundp f
) f
))))
536 (or (lang-check lang
)
537 (lang-check (symbol-name
538 (cdr (assoc lang org-src-lang-modes
))))
539 (error "No org-babel-execute function for %s!" lang
))))
540 (if (and (not arg
) new-hash
(equal new-hash old-hash
))
541 (save-excursion ;; return cached result
542 (goto-char (org-babel-where-is-src-block-result nil info
))
543 (end-of-line 1) (forward-char 1)
544 (setq result
(org-babel-read-result))
545 (message (replace-regexp-in-string
546 "%" "%%" (format "%S" result
))) result
)
547 (message "executing %s code block%s..."
549 (if (nth 4 info
) (format " (%s)" (nth 4 info
)) ""))
552 (if (and (eq (cdr (assoc :result-type params
)) 'value
)
553 (or (member "vector" result-params
)
554 (member "table" result-params
))
555 (not (listp result
)))
556 (list (list result
)) result
))
557 (funcall cmd body params
)))
558 ;; if non-empty result and :file then write to :file
559 (when (cdr (assoc :file params
))
561 (with-temp-file (cdr (assoc :file params
))
563 (org-babel-format-result
564 result
(cdr (assoc :sep
(nth 2 info
)))))))
565 (setq result
(cdr (assoc :file params
))))
566 (org-babel-insert-result
567 result result-params info new-hash indent lang
)
568 (run-hooks 'org-babel-after-execute-hook
)
570 (setq call-process-region
'org-babel-call-process-region-original
))))))
572 (defun org-babel-expand-body:generic
(body params
&optional var-lines
)
573 "Expand BODY with PARAMS.
574 Expand a block of code with org-babel according to its header
575 arguments. This generic implementation of body expansion is
576 called for languages which have not defined their own specific
577 org-babel-expand-body:lang function."
578 (mapconcat #'identity
(append var-lines
(list body
)) "\n"))
581 (defun org-babel-expand-src-block (&optional arg info params
)
582 "Expand the current source code block.
583 Expand according to the source code block's header
584 arguments and pop open the results in a preview buffer."
586 (let* ((info (or info
(org-babel-get-src-block-info)))
588 (params (setf (nth 2 info
)
589 (sort (org-babel-merge-params (nth 2 info
) params
)
590 (lambda (el1 el2
) (string< (symbol-name (car el1
))
591 (symbol-name (car el2
)))))))
592 (body (setf (nth 1 info
)
593 (if (org-babel-noweb-p params
:eval
)
594 (org-babel-expand-noweb-references info
) (nth 1 info
))))
595 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
596 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
599 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
600 (org-babel-expand-body:generic
601 body params
(and (fboundp assignments-cmd
)
602 (funcall assignments-cmd params
))))))
604 nil expanded
(concat "*Org-Babel Preview " (buffer-name) "[ " lang
" ]*"))))
606 (defun org-babel-edit-distance (s1 s2
)
607 "Return the edit (levenshtein) distance between strings S1 S2."
608 (let* ((l1 (length s1
))
610 (dist (map 'vector
(lambda (_) (make-vector (1+ l2
) nil
))
611 (number-sequence 1 (1+ l1
)))))
612 (flet ((in (i j
) (aref (aref dist i
) j
))
613 (mmin (&rest lst
) (apply #'min
(remove nil lst
))))
614 (setf (aref (aref dist
0) 0) 0)
615 (dolist (i (number-sequence 1 l1
))
616 (dolist (j (number-sequence 1 l2
))
617 (setf (aref (aref dist i
) j
)
618 (+ (if (equal (aref s1
(1- i
)) (aref s2
(1- j
))) 0 1)
619 (mmin (in (1- i
) j
) (in i
(1- j
)) (in (1- i
) (1- j
)))))))
623 (defun org-babel-check-src-block ()
624 "Check for misspelled header arguments in the current code block."
626 ;; TODO: report malformed code block
627 ;; TODO: report incompatible combinations of header arguments
628 ;; TODO: report uninitialized variables
629 (let ((too-close 2) ;; <- control closeness to report potential match
630 (names (mapcar #'symbol-name org-babel-header-arg-names
)))
631 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg
)) 1))
632 (and (org-babel-where-is-src-block-head)
633 (org-babel-parse-header-arguments
634 (org-babel-clean-text-properties
635 (match-string 4))))))
637 (when (and (not (string= header name
))
638 (<= (org-babel-edit-distance header name
) too-close
)
639 (not (member header names
)))
640 (error "supplied header \"%S\" is suspiciously close to \"%S\""
642 (message "No suspicious header arguments found.")))
645 (defun org-babel-insert-header-arg ()
646 "Insert a header argument selecting from lists of common args and values."
648 (let* ((lang (car (org-babel-get-src-block-info 'light
)))
649 (lang-headers (intern (concat "org-babel-header-arg-names:" lang
)))
650 (headers (append (if (boundp lang-headers
)
651 (mapcar (lambda (h) (cons h
:any
))
654 org-babel-common-header-args-w-values
))
655 (arg (org-icompleting-read
658 (lambda (header-spec) (symbol-name (car header-spec
)))
661 (let ((vals (cdr (assoc (intern arg
) headers
))))
667 (read-from-minibuffer "value: "))
671 (let ((arg (org-icompleting-read
673 (cons "default" (mapcar #'symbol-name group
)))))
674 (if (and arg
(not (string= "default" arg
)))
680 (defun org-babel-load-in-session (&optional arg info
)
681 "Load the body of the current source-code block.
682 Evaluate the header arguments for the source block before
683 entering the session. After loading the body this pops open the
686 (let* ((info (or info
(org-babel-get-src-block-info)))
688 (params (nth 2 info
))
689 (body (setf (nth 1 info
)
690 (if (org-babel-noweb-p params
:eval
)
691 (org-babel-expand-noweb-references 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 (cmd (intern (concat "org-babel-load-session:" lang
))))
698 (unless (fboundp cmd
)
699 (error "No org-babel-load-session function for %s!" lang
))
700 (pop-to-buffer (funcall cmd session body params
))
704 (defun org-babel-initiate-session (&optional arg info
)
705 "Initiate session for current code block.
706 If called with a prefix argument then resolve any variable
707 references in the header arguments and assign these variables in
708 the session. Copy the body of the code block to the kill ring."
710 (let* ((info (or info
(org-babel-get-src-block-info (not arg
))))
713 (params (nth 2 info
))
714 (session (cdr (assoc :session params
)))
715 (dir (cdr (assoc :dir params
)))
717 (or (and dir
(file-name-as-directory dir
)) default-directory
))
718 (init-cmd (intern (format "org-babel-%s-initiate-session" lang
)))
719 (prep-cmd (intern (concat "org-babel-prep-session:" lang
))))
720 (if (and (stringp session
) (string= session
"none"))
721 (error "This block is not using a session!"))
722 (unless (fboundp init-cmd
)
723 (error "No org-babel-initiate-session function for %s!" lang
))
724 (with-temp-buffer (insert (org-babel-trim body
))
725 (copy-region-as-kill (point-min) (point-max)))
727 (unless (fboundp prep-cmd
)
728 (error "No org-babel-prep-session function for %s!" lang
))
729 (funcall prep-cmd session params
))
730 (funcall init-cmd session params
)))
733 (defun org-babel-switch-to-session (&optional arg info
)
734 "Switch to the session of the current code block.
735 Uses `org-babel-initiate-session' to start the session. If called
736 with a prefix argument then this is passed on to
737 `org-babel-initiate-session'."
739 (pop-to-buffer (org-babel-initiate-session arg info
))
742 (defalias 'org-babel-pop-to-session
'org-babel-switch-to-session
)
745 (defun org-babel-switch-to-session-with-code (&optional arg info
)
746 "Switch to code buffer and display session."
750 (let ((other-window-buffer (window-buffer (next-window))))
751 (set-window-buffer (next-window) (current-buffer))
752 (set-window-buffer (selected-window) other-window-buffer
))
754 (let ((info (org-babel-get-src-block-info))
755 (org-src-window-setup 'reorganize-frame
))
757 (org-babel-switch-to-session arg info
))
761 (defmacro org-babel-do-in-edit-buffer
(&rest body
)
762 "Evaluate BODY in edit buffer if there is a code block at point.
763 Return t if a code block was found at point, nil otherwise."
764 `(let ((org-src-window-setup 'switch-invisibly
))
765 (when (and (org-babel-where-is-src-block-head)
766 (org-edit-src-code nil nil nil
))
767 (unwind-protect (progn ,@body
)
768 (if (org-bound-and-true-p org-edit-src-from-org-mode
)
769 (org-edit-src-exit)))
771 (def-edebug-spec org-babel-do-in-edit-buffer
(body))
773 (defun org-babel-do-key-sequence-in-edit-buffer (key)
774 "Read key sequence and execute the command in edit buffer.
775 Enter a key sequence to be executed in the language major-mode
776 edit buffer. For example, TAB will alter the contents of the
777 Org-mode code block according to the effect of TAB in the
778 language major-mode buffer. For languages that support
779 interactive sessions, this can be used to send code from the Org
780 buffer to the session for evaluation using the native major-mode
781 evaluation mechanisms."
782 (interactive "kEnter key-sequence to execute in edit buffer: ")
783 (org-babel-do-in-edit-buffer
785 (key-binding (or key
(read-key-sequence nil
))))))
787 (defvar org-bracket-link-regexp
)
789 (defun org-babel-open-src-block-result (&optional re-run
)
790 "If `point' is on a src block then open the results of the
791 source code block, otherwise return nil. With optional prefix
792 argument RE-RUN the source-code block is evaluated even if
793 results already exist."
795 (let ((info (org-babel-get-src-block-info)))
798 ;; go to the results, if there aren't any then run the block
799 (goto-char (or (and (not re-run
) (org-babel-where-is-src-block-result))
800 (progn (org-babel-execute-src-block)
801 (org-babel-where-is-src-block-result))))
803 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
805 (if (looking-at org-bracket-link-regexp
)
808 (let ((r (org-babel-format-result
809 (org-babel-read-result) (cdr (assoc :sep
(nth 2 info
))))))
810 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
811 (delete-region (point-min) (point-max))
816 (defmacro org-babel-map-src-blocks
(file &rest body
)
817 "Evaluate BODY forms on each source-block in FILE.
818 If FILE is nil evaluate BODY forms on source blocks in current
819 buffer. During evaluation of BODY the following local variables
820 are set relative to the currently matched code block.
822 full-block ------- string holding the entirety of the code block
823 beg-block -------- point at the beginning of the code block
824 end-block -------- point at the end of the matched code block
825 lang ------------- string holding the language of the code block
826 beg-lang --------- point at the beginning of the lang
827 end-lang --------- point at the end of the lang
828 switches --------- string holding the switches
829 beg-switches ----- point at the beginning of the switches
830 end-switches ----- point at the end of the switches
831 header-args ------ string holding the header-args
832 beg-header-args -- point at the beginning of the header-args
833 end-header-args -- point at the end of the header-args
834 body ------------- string holding the body of the code block
835 beg-body --------- point at the beginning of the body
836 end-body --------- point at the end of the body"
838 (let ((tempvar (make-symbol "file")))
839 `(let* ((,tempvar
,file
)
840 (visited-p (or (null ,tempvar
)
841 (get-file-buffer (expand-file-name ,tempvar
))))
842 (point (point)) to-be-removed
)
843 (save-window-excursion
844 (when ,tempvar
(find-file ,tempvar
))
845 (setq to-be-removed
(current-buffer))
846 (goto-char (point-min))
847 (while (re-search-forward org-babel-src-block-regexp nil t
)
848 (goto-char (match-beginning 0))
849 (let ((full-block (match-string 0))
850 (beg-block (match-beginning 0))
851 (end-block (match-end 0))
852 (lang (match-string 2))
853 (beg-lang (match-beginning 2))
854 (end-lang (match-end 2))
855 (switches (match-string 3))
856 (beg-switches (match-beginning 3))
857 (end-switches (match-end 3))
858 (header-args (match-string 4))
859 (beg-header-args (match-beginning 4))
860 (end-header-args (match-end 4))
861 (body (match-string 5))
862 (beg-body (match-beginning 5))
863 (end-body (match-end 5)))
865 (goto-char end-block
))))
866 (unless visited-p
(kill-buffer to-be-removed
))
868 (def-edebug-spec org-babel-map-src-blocks
(form body
))
871 (defmacro org-babel-map-inline-src-blocks
(file &rest body
)
872 "Evaluate BODY forms on each inline source-block in FILE.
873 If FILE is nil evaluate BODY forms on source blocks in current
876 (let ((tempvar (make-symbol "file")))
877 `(let* ((,tempvar
,file
)
878 (visited-p (or (null ,tempvar
)
879 (get-file-buffer (expand-file-name ,tempvar
))))
880 (point (point)) to-be-removed
)
881 (save-window-excursion
882 (when ,tempvar
(find-file ,tempvar
))
883 (setq to-be-removed
(current-buffer))
884 (goto-char (point-min))
885 (while (re-search-forward org-babel-inline-src-block-regexp nil t
)
886 (goto-char (match-beginning 1))
887 (save-match-data ,@body
)
888 (goto-char (match-end 0))))
889 (unless visited-p
(kill-buffer to-be-removed
))
891 (def-edebug-spec org-babel-map-inline-src-blocks
(form body
))
893 (defvar org-babel-lob-one-liner-regexp
)
895 (defmacro org-babel-map-call-lines
(file &rest body
)
896 "Evaluate BODY forms on each call line in FILE.
897 If FILE is nil evaluate BODY forms on source blocks in current
900 (let ((tempvar (make-symbol "file")))
901 `(let* ((,tempvar
,file
)
902 (visited-p (or (null ,tempvar
)
903 (get-file-buffer (expand-file-name ,tempvar
))))
904 (point (point)) to-be-removed
)
905 (save-window-excursion
906 (when ,tempvar
(find-file ,tempvar
))
907 (setq to-be-removed
(current-buffer))
908 (goto-char (point-min))
909 (while (re-search-forward org-babel-lob-one-liner-regexp nil t
)
910 (goto-char (match-beginning 1))
911 (save-match-data ,@body
)
912 (goto-char (match-end 0))))
913 (unless visited-p
(kill-buffer to-be-removed
))
915 (def-edebug-spec org-babel-map-call-lines
(form body
))
918 (defmacro org-babel-map-executables
(file &rest body
)
920 (let ((tempvar (make-symbol "file"))
921 (rx (make-symbol "rx")))
922 `(let* ((,tempvar
,file
)
923 (,rx
(concat "\\(" org-babel-src-block-regexp
924 "\\|" org-babel-inline-src-block-regexp
925 "\\|" org-babel-lob-one-liner-regexp
"\\)"))
926 (visited-p (or (null ,tempvar
)
927 (get-file-buffer (expand-file-name ,tempvar
))))
928 (point (point)) to-be-removed
)
929 (save-window-excursion
930 (when ,tempvar
(find-file ,tempvar
))
931 (setq to-be-removed
(current-buffer))
932 (goto-char (point-min))
933 (while (re-search-forward ,rx nil t
)
934 (goto-char (match-beginning 1))
935 (when (looking-at org-babel-inline-src-block-regexp
)(forward-char 1))
936 (save-match-data ,@body
)
937 (goto-char (match-end 0))))
938 (unless visited-p
(kill-buffer to-be-removed
))
940 (def-edebug-spec org-babel-map-executables
(form body
))
943 (defun org-babel-execute-buffer (&optional arg
)
944 "Execute source code blocks in a buffer.
945 Call `org-babel-execute-src-block' on every source block in
948 (org-babel-eval-wipe-error-buffer)
949 (org-save-outline-visibility t
950 (org-babel-map-executables nil
951 (if (looking-at org-babel-lob-one-liner-regexp
)
952 (org-babel-lob-execute-maybe)
953 (org-babel-execute-src-block arg
)))))
956 (defun org-babel-execute-subtree (&optional arg
)
957 "Execute source code blocks in a subtree.
958 Call `org-babel-execute-src-block' on every source block in
959 the current subtree."
963 (org-narrow-to-subtree)
964 (org-babel-execute-buffer arg
)
968 (defun org-babel-sha1-hash (&optional info
)
969 "Generate an sha1 hash based on the value of info."
971 (let ((print-level nil
)
972 (info (or info
(org-babel-get-src-block-info))))
974 (sort (copy-sequence (nth 2 info
))
975 (lambda (a b
) (string< (car a
) (car b
)))))
977 (dolist (p '("replace" "silent" "append" "prepend"))
978 (setq lst
(remove p lst
)))
981 (let ((v (if (and (listp (cdr arg
)) (null (cddr arg
)))
982 (copy-sequence (cdr arg
))
984 (when (and v
(not (and (sequencep v
)
988 ((and (listp v
) ; lists are sorted
989 (member (car arg
) '(:result-params
)))
990 (sort (rm v
) #'string
<))
991 ((and (stringp v
) ; strings are sorted
992 (member (car arg
) '(:results
:exports
)))
993 (mapconcat #'identity
(sort (rm (split-string v
))
997 (when (org-called-interactively-p 'interactive
) (message hash
)) hash
)
998 (let ((it (format "%s-%s"
1001 (delq nil
(mapcar (lambda (arg)
1002 (let ((normalized (norm arg
)))
1004 (format "%S" normalized
))))
1009 (defun org-babel-current-result-hash ()
1010 "Return the in-buffer hash associated with INFO."
1011 (org-babel-where-is-src-block-result)
1012 (org-babel-clean-text-properties (match-string 3)))
1014 (defun org-babel-hide-hash ()
1015 "Hide the hash in the current results line.
1016 Only the initial `org-babel-hash-show' characters of the hash
1017 will remain visible."
1018 (add-to-invisibility-spec '(org-babel-hide-hash . t
))
1020 (when (and (re-search-forward org-babel-result-regexp nil t
)
1022 (let* ((start (match-beginning 3))
1023 (hide-start (+ org-babel-hash-show start
))
1025 (hash (match-string 3))
1027 (setq ov1
(make-overlay start hide-start
))
1028 (setq ov2
(make-overlay hide-start end
))
1029 (overlay-put ov2
'invisible
'org-babel-hide-hash
)
1030 (overlay-put ov1
'babel-hash hash
)))))
1032 (defun org-babel-hide-all-hashes ()
1033 "Hide the hash in the current buffer.
1034 Only the initial `org-babel-hash-show' characters of each hash
1035 will remain visible. This function should be called as part of
1036 the `org-mode-hook'."
1038 (while (re-search-forward org-babel-result-regexp nil t
)
1039 (goto-char (match-beginning 0))
1040 (org-babel-hide-hash)
1041 (goto-char (match-end 0)))))
1042 (add-hook 'org-mode-hook
'org-babel-hide-all-hashes
)
1044 (defun org-babel-hash-at-point (&optional point
)
1045 "Return the value of the hash at POINT.
1046 The hash is also added as the last element of the kill ring.
1047 This can be called with C-c C-c."
1049 (let ((hash (car (delq nil
(mapcar
1050 (lambda (ol) (overlay-get ol
'babel-hash
))
1051 (overlays-at (or point
(point))))))))
1052 (when hash
(kill-new hash
) (message hash
))))
1053 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-hash-at-point
)
1055 (defun org-babel-result-hide-spec ()
1056 "Hide portions of results lines.
1057 Add `org-babel-hide-result' as an invisibility spec for hiding
1058 portions of results lines."
1059 (add-to-invisibility-spec '(org-babel-hide-result . t
)))
1060 (add-hook 'org-mode-hook
'org-babel-result-hide-spec
)
1062 (defvar org-babel-hide-result-overlays nil
1063 "Overlays hiding results.")
1065 (defun org-babel-result-hide-all ()
1066 "Fold all results in the current buffer."
1068 (org-babel-show-result-all)
1070 (while (re-search-forward org-babel-result-regexp nil t
)
1071 (save-excursion (goto-char (match-beginning 0))
1072 (org-babel-hide-result-toggle-maybe)))))
1074 (defun org-babel-show-result-all ()
1075 "Unfold all results in the current buffer."
1076 (mapc 'delete-overlay org-babel-hide-result-overlays
)
1077 (setq org-babel-hide-result-overlays nil
))
1080 (defun org-babel-hide-result-toggle-maybe ()
1081 "Toggle visibility of result at point."
1083 (let ((case-fold-search t
))
1085 (beginning-of-line 1)
1086 (looking-at org-babel-result-regexp
))
1087 (progn (org-babel-hide-result-toggle)
1088 t
) ;; to signal that we took action
1089 nil
))) ;; to signal that we did not
1091 (defun org-babel-hide-result-toggle (&optional force
)
1092 "Toggle the visibility of the current result."
1096 (if (re-search-forward org-babel-result-regexp nil t
)
1097 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
1099 (while (looking-at org-babel-multi-line-header-regexp
)
1101 (goto-char (- (org-babel-result-end) 1)) (point)))
1103 (if (memq t
(mapcar (lambda (overlay)
1104 (eq (overlay-get overlay
'invisible
)
1105 'org-babel-hide-result
))
1106 (overlays-at start
)))
1107 (if (or (not force
) (eq force
'off
))
1109 (when (member ov org-babel-hide-result-overlays
)
1110 (setq org-babel-hide-result-overlays
1111 (delq ov org-babel-hide-result-overlays
)))
1112 (when (eq (overlay-get ov
'invisible
)
1113 'org-babel-hide-result
)
1114 (delete-overlay ov
)))
1115 (overlays-at start
)))
1116 (setq ov
(make-overlay start end
))
1117 (overlay-put ov
'invisible
'org-babel-hide-result
)
1118 ;; make the block accessible to isearch
1120 ov
'isearch-open-invisible
1122 (when (member ov org-babel-hide-result-overlays
)
1123 (setq org-babel-hide-result-overlays
1124 (delq ov org-babel-hide-result-overlays
)))
1125 (when (eq (overlay-get ov
'invisible
)
1126 'org-babel-hide-result
)
1127 (delete-overlay ov
))))
1128 (push ov org-babel-hide-result-overlays
)))
1129 (error "Not looking at a result line"))))
1131 ;; org-tab-after-check-for-cycling-hook
1132 (add-hook 'org-tab-first-hook
'org-babel-hide-result-toggle-maybe
)
1133 ;; Remove overlays when changing major mode
1134 (add-hook 'org-mode-hook
1135 (lambda () (org-add-hook 'change-major-mode-hook
1136 'org-babel-show-result-all
'append
'local
)))
1138 (defvar org-file-properties
)
1139 (defun org-babel-params-from-properties (&optional lang
)
1140 "Retrieve parameters specified as properties.
1141 Return an association list of any source block params which
1142 may be specified in the properties of the current outline entry."
1145 (org-babel-parse-multiple-vars
1148 (lambda (header-arg)
1149 (and (setq val
(org-entry-get (point) header-arg t
))
1150 (cons (intern (concat ":" header-arg
))
1151 (org-babel-read val
))))
1155 org-babel-header-arg-names
1157 (setq sym
(intern (concat "org-babel-header-arg-names:"
1159 (and (boundp sym
) (eval sym
)))))))))))
1161 (defvar org-src-preserve-indentation
)
1162 (defun org-babel-parse-src-block-match ()
1163 "Parse the results from a match of the `org-babel-src-block-regexp'."
1164 (let* ((block-indentation (length (match-string 1)))
1165 (lang (org-babel-clean-text-properties (match-string 2)))
1166 (lang-headers (intern (concat "org-babel-default-header-args:" lang
)))
1167 (switches (match-string 3))
1168 (body (org-babel-clean-text-properties
1169 (let* ((body (match-string 5))
1170 (sub-length (- (length body
) 1)))
1171 (if (and (> sub-length
0)
1172 (string= "\n" (substring body sub-length
)))
1173 (substring body
0 sub-length
)
1175 (preserve-indentation (or org-src-preserve-indentation
1176 (string-match "-i\\>" switches
))))
1178 ;; get block body less properties, protective commas, and indentation
1181 (insert (org-babel-strip-protective-commas body
))
1182 (unless preserve-indentation
(org-do-remove-indentation))
1184 (org-babel-merge-params
1185 org-babel-default-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 block-indentation
)))
1193 (defun org-babel-parse-inline-src-block-match ()
1194 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
1195 (let* ((lang (org-babel-clean-text-properties (match-string 2)))
1196 (lang-headers (intern (concat "org-babel-default-header-args:" lang
))))
1198 (org-babel-strip-protective-commas
1199 (org-babel-clean-text-properties (match-string 5)))
1200 (org-babel-merge-params
1201 org-babel-default-inline-header-args
1202 (org-babel-params-from-properties lang
)
1203 (if (boundp lang-headers
) (eval lang-headers
) nil
)
1204 (org-babel-parse-header-arguments
1205 (org-babel-clean-text-properties (or (match-string 4) "")))))))
1207 (defun org-babel-balanced-split (string alts
)
1208 "Split STRING on instances of ALTS.
1209 ALTS is a cons of two character options where each option may be
1210 either the numeric code of a single character or a list of
1211 character alternatives. For example to split on balanced
1212 instances of \"[ \t]:\" set ALTS to '((32 9) . 58)."
1213 (flet ((matches (ch spec
) (if (listp spec
) (member ch spec
) (equal spec ch
)))
1216 (and (matches ch
(cdr alts
))
1217 (matches last
(car alts
)))
1218 (matches ch alts
))))
1219 (let ((balance 0) (quote nil
) (partial nil
) (lst nil
) (last 0))
1220 (mapc (lambda (ch) ; split on [], (), "" balanced instances of [ \t]:
1221 (setq balance
(+ balance
1222 (cond ((or (equal 91 ch
) (equal 40 ch
)) 1)
1223 ((or (equal 93 ch
) (equal 41 ch
)) -
1)
1225 (when (and (equal 34 ch
) (not (equal 92 last
)))
1226 (setq quote
(not quote
)))
1227 (setq partial
(cons ch partial
))
1228 (when (and (= balance
0) (not quote
) (matched ch last
))
1229 (setq lst
(cons (apply #'string
(nreverse
1236 (string-to-list string
))
1237 (nreverse (cons (apply #'string
(nreverse partial
)) lst
)))))
1239 (defun org-babel-join-splits-near-ch (ch list
)
1240 "Join splits where \"=\" is on either end of the split."
1241 (flet ((last= (str) (= ch
(aref str
(1- (length str
)))))
1242 (first= (str) (= ch
(aref str
0))))
1244 (org-reduce (lambda (acc el
)
1245 (let ((head (car acc
)))
1246 (if (and head
(or (last= head
) (first= el
)))
1247 (cons (concat head el
) (cdr acc
))
1249 list
:initial-value nil
))))
1251 (defun org-babel-parse-header-arguments (arg-string)
1252 "Parse a string of header arguments returning an alist."
1253 (when (> (length arg-string
) 0)
1254 (org-babel-parse-multiple-vars
1259 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1261 (cons (intern (match-string 1 arg
))
1262 (org-babel-read (org-babel-chomp (match-string 2 arg
))))
1263 (cons (intern (org-babel-chomp arg
)) nil
)))
1265 (cons (car raw
) (mapcar (lambda (r) (concat ":" r
)) (cdr raw
))))
1266 (org-babel-balanced-split arg-string
'((32 9) .
58))))))))
1268 (defun org-babel-parse-multiple-vars (header-arguments)
1269 "Expand multiple variable assignments behind a single :var keyword.
1271 This allows expression of multiple variables with one :var as
1274 #+PROPERTY: var foo=1, bar=2"
1276 (mapc (lambda (pair)
1277 (if (eq (car pair
) :var
)
1278 (mapcar (lambda (v) (push (cons :var
(org-babel-trim v
)) results
))
1279 (org-babel-join-splits-near-ch
1280 61 (org-babel-balanced-split (cdr pair
) 32)))
1281 (push pair results
)))
1283 (nreverse results
)))
1285 (defun org-babel-process-params (params)
1286 "Expand variables in PARAMS and add summary parameters."
1287 (let* ((processed-vars (mapcar (lambda (el)
1288 (if (consp (cdr el
))
1290 (org-babel-ref-parse (cdr el
))))
1291 (org-babel-get-header params
:var
)))
1292 (vars-and-names (if (and (assoc :colname-names params
)
1293 (assoc :rowname-names params
))
1294 (list processed-vars
)
1295 (org-babel-disassemble-tables
1297 (cdr (assoc :hlines params
))
1298 (cdr (assoc :colnames params
))
1299 (cdr (assoc :rownames params
)))))
1300 (raw-result (or (cdr (assoc :results params
)) ""))
1301 (result-params (append
1302 (split-string (if (stringp raw-result
)
1305 (cdr (assoc :result-params params
)))))
1307 (mapcar (lambda (var) (cons :var var
)) (car vars-and-names
))
1309 (cons :colname-names
(or (cdr (assoc :colname-names params
))
1310 (cadr vars-and-names
)))
1311 (cons :rowname-names
(or (cdr (assoc :rowname-names params
))
1312 (caddr vars-and-names
)))
1313 (cons :result-params result-params
)
1314 (cons :result-type
(cond ((member "output" result-params
) 'output
)
1315 ((member "value" result-params
) 'value
)
1317 (org-babel-get-header params
:var
'other
))))
1319 ;; row and column names
1320 (defun org-babel-del-hlines (table)
1321 "Remove all 'hlines from TABLE."
1322 (remove 'hline table
))
1324 (defun org-babel-get-colnames (table)
1325 "Return the column names of TABLE.
1326 Return a cons cell, the `car' of which contains the TABLE less
1327 colnames, and the `cdr' of which contains a list of the column
1329 (if (equal 'hline
(nth 1 table
))
1330 (cons (cddr table
) (car table
))
1331 (cons (cdr table
) (car table
))))
1333 (defun org-babel-get-rownames (table)
1334 "Return the row names of TABLE.
1335 Return a cons cell, the `car' of which contains the TABLE less
1336 colnames, and the `cdr' of which contains a list of the column
1337 names. Note: this function removes any hlines in TABLE."
1338 (flet ((trans (table) (apply #'mapcar
* #'list table
)))
1339 (let* ((width (apply 'max
1340 (mapcar (lambda (el) (if (listp el
) (length el
) 0)) table
)))
1341 (table (trans (mapcar (lambda (row)
1342 (if (not (equal row
'hline
))
1346 (setq row
(cons 'hline row
)))
1349 (cons (mapcar (lambda (row) (if (equal (car row
) 'hline
) 'hline row
))
1350 (trans (cdr table
)))
1351 (remove 'hline
(car table
))))))
1353 (defun org-babel-put-colnames (table colnames
)
1354 "Add COLNAMES to TABLE if they exist."
1355 (if colnames
(apply 'list colnames
'hline table
) table
))
1357 (defun org-babel-put-rownames (table rownames
)
1358 "Add ROWNAMES to TABLE if they exist."
1360 (mapcar (lambda (row)
1362 (cons (or (pop rownames
) "") row
)
1366 (defun org-babel-pick-name (names selector
)
1367 "Select one out of an alist of row or column names.
1368 SELECTOR can be either a list of names in which case those names
1369 will be returned directly, or an index into the list NAMES in
1370 which case the indexed names will be return."
1371 (if (listp selector
)
1374 (if (and selector
(symbolp selector
) (not (equal t selector
)))
1375 (cdr (assoc selector names
))
1376 (if (integerp selector
)
1377 (nth (- selector
1) names
)
1378 (cdr (car (last names
))))))))
1380 (defun org-babel-disassemble-tables (vars hlines colnames rownames
)
1381 "Parse tables for further processing.
1382 Process the variables in VARS according to the HLINES,
1383 ROWNAMES and COLNAMES header arguments. Return a list consisting
1384 of the vars, cnames and rnames."
1385 (let (cnames rnames
)
1389 (when (listp (cdr var
))
1390 (when (and (not (equal colnames
"no"))
1391 (or colnames
(and (equal (nth 1 (cdr var
)) 'hline
)
1392 (not (member 'hline
(cddr (cdr var
)))))))
1393 (let ((both (org-babel-get-colnames (cdr var
))))
1394 (setq cnames
(cons (cons (car var
) (cdr both
))
1396 (setq var
(cons (car var
) (car both
)))))
1397 (when (and rownames
(not (equal rownames
"no")))
1398 (let ((both (org-babel-get-rownames (cdr var
))))
1399 (setq rnames
(cons (cons (car var
) (cdr both
))
1401 (setq var
(cons (car var
) (car both
)))))
1402 (when (and hlines
(not (equal hlines
"yes")))
1403 (setq var
(cons (car var
) (org-babel-del-hlines (cdr var
))))))
1406 (reverse cnames
) (reverse rnames
))))
1408 (defun org-babel-reassemble-table (table colnames rownames
)
1409 "Add column and row names to a table.
1410 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1411 to the table for reinsertion to org-mode."
1414 (if (and colnames
(listp (car table
)) (= (length (car table
))
1416 (org-babel-put-colnames table colnames
) table
))
1417 (if (and rownames
(= (length table
) (length rownames
)))
1418 (org-babel-put-rownames table rownames
) table
))
1421 (defun org-babel-where-is-src-block-head ()
1422 "Find where the current source block begins.
1423 Return the point at the beginning of the current source
1424 block. Specifically at the beginning of the #+BEGIN_SRC line.
1425 If the point is not on a source block then return nil."
1426 (let ((initial (point)) top bottom
)
1428 (save-excursion ;; on a source name line or a #+header line
1429 (beginning-of-line 1)
1430 (and (or (looking-at org-babel-src-name-regexp
)
1431 (looking-at org-babel-multi-line-header-regexp
))
1433 (while (and (forward-line 1)
1434 (looking-at org-babel-multi-line-header-regexp
)))
1435 (looking-at org-babel-src-block-regexp
))
1437 (save-excursion ;; on a #+begin_src line
1438 (beginning-of-line 1)
1439 (and (looking-at org-babel-src-block-regexp
)
1441 (save-excursion ;; inside a src block
1443 (re-search-backward "^[ \t]*#\\+begin_src" nil t
) (setq top
(point))
1444 (re-search-forward "^[ \t]*#\\+end_src" nil t
) (setq bottom
(point))
1445 (< top initial
) (< initial bottom
)
1446 (progn (goto-char top
) (beginning-of-line 1)
1447 (looking-at org-babel-src-block-regexp
))
1451 (defun org-babel-goto-src-block-head ()
1452 "Go to the beginning of the current code block."
1455 (if head
(goto-char head
) (error "not currently in a code block")))
1456 (org-babel-where-is-src-block-head)))
1459 (defun org-babel-goto-named-src-block (name)
1460 "Go to a named source-code block."
1462 (let ((completion-ignore-case t
)
1463 (under-point (thing-at-point 'line
)))
1464 (list (org-icompleting-read
1465 "source-block name: " (org-babel-src-block-names) nil t
1468 ((string-match (org-babel-noweb-wrap) under-point
)
1469 (let ((block-name (match-string 1 under-point
)))
1470 (string-match "[^(]*" block-name
)
1471 (match-string 0 block-name
)))
1473 ((string-match org-babel-lob-one-liner-regexp under-point
)
1474 (let ((source-info (car (org-babel-lob-get-info))))
1475 (if (string-match "^\\([^\\[]+?\\)\\(\\[.*\\]\\)?(" source-info
)
1476 (let ((source-name (match-string 1 source-info
)))
1479 ((string-match (concat "#\\+" org-babel-results-keyword
1480 "\\:\s+\\([^\\(]*\\)") under-point
)
1481 (match-string 1 under-point
))
1483 ((and (thing-at-point 'symbol
))
1484 (org-babel-find-named-block (thing-at-point 'symbol
))
1485 (thing-at-point 'symbol
))
1487 (let ((point (org-babel-find-named-block name
)))
1489 ;; taken from `org-open-at-point'
1490 (progn (org-mark-ring-push) (goto-char point
) (org-show-context))
1491 (message "source-code block '%s' not found in this buffer" name
))))
1493 (defun org-babel-find-named-block (name)
1494 "Find a named source-code block.
1495 Return the location of the source block identified by source
1496 NAME, or nil if no such block exists. Set match data according to
1497 org-babel-named-src-block-regexp."
1499 (let ((case-fold-search t
)
1500 (regexp (org-babel-named-src-block-regexp-for-name name
)) msg
)
1501 (goto-char (point-min))
1502 (when (or (re-search-forward regexp nil t
)
1503 (re-search-backward regexp nil t
))
1504 (match-beginning 0)))))
1506 (defun org-babel-src-block-names (&optional file
)
1507 "Returns the names of source blocks in FILE or the current buffer."
1509 (when file
(find-file file
)) (goto-char (point-min))
1511 (while (re-search-forward org-babel-src-name-w-name-regexp nil t
)
1512 (setq names
(cons (match-string 3) names
)))
1516 (defun org-babel-goto-named-result (name)
1517 "Go to a named result."
1519 (let ((completion-ignore-case t
))
1520 (list (org-icompleting-read "source-block name: "
1521 (org-babel-result-names) nil t
))))
1522 (let ((point (org-babel-find-named-result name
)))
1524 ;; taken from `org-open-at-point'
1525 (progn (goto-char point
) (org-show-context))
1526 (message "result '%s' not found in this buffer" name
))))
1528 (defun org-babel-find-named-result (name &optional point
)
1529 "Find a named result.
1530 Return the location of the result named NAME in the current
1531 buffer or nil if no such result exists."
1533 (goto-char (or point
(point-min)))
1534 (catch 'is-a-code-block
1535 (when (re-search-forward
1536 (concat org-babel-result-regexp
1537 "[ \t]" (regexp-quote name
) "[ \t\n\f\v\r]+") nil t
)
1538 (when (and (string= "name" (downcase (match-string 1)))
1539 (or (looking-at org-babel-src-block-regexp
)
1540 (looking-at org-babel-multi-line-header-regexp
)))
1541 (throw 'is-a-code-block
(org-babel-find-named-result name
(point))))
1542 (beginning-of-line 0) (point)))))
1544 (defun org-babel-result-names (&optional file
)
1545 "Returns the names of results in FILE or the current buffer."
1547 (when file
(find-file file
)) (goto-char (point-min))
1549 (while (re-search-forward org-babel-result-w-name-regexp nil t
)
1550 (setq names
(cons (match-string 4) names
)))
1554 (defun org-babel-next-src-block (&optional arg
)
1555 "Jump to the next source block.
1556 With optional prefix argument ARG, jump forward ARG many source blocks."
1558 (when (looking-at org-babel-src-block-regexp
) (forward-char 1))
1560 (re-search-forward org-babel-src-block-regexp nil nil
(or arg
1))
1561 (error (error "No further code blocks")))
1562 (goto-char (match-beginning 0)) (org-show-context))
1565 (defun org-babel-previous-src-block (&optional arg
)
1566 "Jump to the previous source block.
1567 With optional prefix argument ARG, jump backward ARG many source blocks."
1570 (re-search-backward org-babel-src-block-regexp nil nil
(or arg
1))
1571 (error (error "No previous code blocks")))
1572 (goto-char (match-beginning 0)) (org-show-context))
1574 (defvar org-babel-load-languages
)
1577 (defun org-babel-mark-block ()
1578 "Mark current src block"
1584 (looking-at org-babel-src-block-regexp
))
1585 (push-mark (match-end 5) nil t
)
1586 (goto-char (match-beginning 5))))
1587 (org-babel-where-is-src-block-head)))
1589 (defun org-babel-demarcate-block (&optional arg
)
1590 "Wrap or split the code in the region or on the point.
1591 When called from inside of a code block the current block is
1592 split. When called from outside of a code block a new code block
1593 is created. In both cases if the region is demarcated and if the
1594 region is not active then the point is demarcated."
1596 (let ((info (org-babel-get-src-block-info 'light
))
1597 (headers (progn (org-babel-where-is-src-block-head)
1599 (stars (concat (make-string (or (org-current-level) 1) ?
*) " ")))
1605 (let ((lang (nth 0 info
))
1606 (indent (make-string (nth 5 info
) ?
)))
1607 (when (string-match "^[[:space:]]*$"
1608 (buffer-substring (point-at-bol)
1610 (delete-region (point-at-bol) (point-at-eol)))
1612 (if (looking-at "^") "" "\n")
1613 indent
"#+end_src\n"
1614 (if arg stars indent
) "\n"
1615 indent
"#+begin_src " lang
1616 (if (> (length headers
) 1)
1617 (concat " " headers
) headers
)
1618 (if (looking-at "[\n\r]")
1620 (concat "\n" (make-string (current-column) ?
)))))))
1621 (move-end-of-line 2))
1622 (sort (if (region-active-p) (list (mark) (point)) (list (point))) #'>))
1623 (let ((start (point))
1624 (lang (org-icompleting-read "Lang: "
1625 (mapcar (lambda (el) (symbol-name (car el
)))
1626 org-babel-load-languages
)))
1627 (body (delete-and-extract-region
1628 (if (region-active-p) (mark) (point)) (point))))
1629 (insert (concat (if (looking-at "^") "" "\n")
1630 (if arg
(concat stars
"\n") "")
1631 "#+begin_src " lang
"\n"
1633 (if (or (= (length body
) 0)
1634 (string-match "[\r\n]$" body
)) "" "\n")
1636 (goto-char start
) (move-end-of-line 1)))))
1638 (defvar org-babel-lob-one-liner-regexp
)
1639 (defun org-babel-where-is-src-block-result (&optional insert info hash indent
)
1640 "Find where the current source block results begin.
1641 Return the point at the beginning of the result of the current
1642 source block. Specifically at the beginning of the results line.
1643 If no result exists for this block then create a results line
1644 following the source block."
1646 (let* ((on-lob-line (save-excursion
1647 (beginning-of-line 1)
1648 (looking-at org-babel-lob-one-liner-regexp
)))
1649 (inlinep (when (org-babel-get-inline-src-block-matches)
1651 (name (if on-lob-line
1652 (nth 0 (org-babel-lob-get-info))
1653 (nth 4 (or info
(org-babel-get-src-block-info 'light
)))))
1654 (head (unless on-lob-line
(org-babel-where-is-src-block-head)))
1656 (when head
(goto-char head
))
1658 found
;; was there a result (before we potentially insert one)
1663 ;; - return t if it is found, else return nil
1664 ;; - if it does not need to be rebuilt, then don't set end
1665 ;; - if it does need to be rebuilt then do set end
1666 name
(setq beg
(org-babel-find-named-result name
))
1668 (when (and hash
(not (string= hash
(match-string 3))))
1669 (goto-char beg
) (setq end beg
) ;; beginning of result
1671 (delete-region end
(org-babel-result-end)) nil
)))
1674 ;; - return t if it is found, else return nil
1675 ;; - if it is found, and the hash doesn't match, delete and set end
1676 (or on-lob-line
(re-search-forward "^[ \t]*#\\+end_src" nil t
))
1677 (progn (end-of-line 1)
1678 (if (eobp) (insert "\n") (forward-char 1))
1681 (progn ;; unnamed results line already exists
1682 (re-search-forward "[^ \f\t\n\r\v]" nil t
)
1683 (beginning-of-line 1)
1685 (concat org-babel-result-regexp
"\n")))
1687 ;; must remove and rebuild if hash!=old-hash
1688 (if (and hash
(not (string= hash
(match-string 3))))
1692 end
(org-babel-result-end)))
1693 (setq end nil
)))))))))
1694 (if (and insert end
)
1698 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1703 (org-number-sequence 1 indent
) "")
1705 "#+" org-babel-results-keyword
1706 (when hash
(concat "["hash
"]"))
1708 (when name
(concat " " name
)) "\n"))
1709 (unless beg
(insert "\n") (backward-char))
1710 (beginning-of-line 0)
1711 (if hash
(org-babel-hide-hash))
1715 (defvar org-block-regexp
)
1716 (defun org-babel-read-result ()
1717 "Read the result at `point' into emacs-lisp."
1718 (let ((case-fold-search t
) result-string
)
1720 ((org-at-table-p) (org-babel-read-table))
1721 ((org-at-item-p) (org-babel-read-list))
1722 ((looking-at org-bracket-link-regexp
) (org-babel-read-link))
1723 ((looking-at org-block-regexp
) (org-babel-trim (match-string 4)))
1724 ((looking-at "^[ \t]*: ")
1727 (mapconcat (lambda (line)
1728 (if (and (> (length line
) 1)
1729 (string-match "^[ \t]*: \\(.+\\)" line
))
1730 (match-string 1 line
)
1734 (point) (org-babel-result-end)) "[\r\n]+")
1736 (or (org-babel-number-p result-string
) result-string
))
1737 ((looking-at org-babel-result-regexp
)
1738 (save-excursion (forward-line 1) (org-babel-read-result))))))
1740 (defun org-babel-read-table ()
1741 "Read the table at `point' into emacs-lisp."
1742 (mapcar (lambda (row)
1743 (if (and (symbolp row
) (equal row
'hline
)) row
1744 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
)) row
)))
1745 (org-table-to-lisp)))
1747 (defun org-babel-read-list ()
1748 "Read the list at `point' into emacs-lisp."
1749 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
))
1750 (mapcar #'cadr
(cdr (org-list-parse-list)))))
1752 (defvar org-link-types-re
)
1753 (defun org-babel-read-link ()
1754 "Read the link at `point' into emacs-lisp.
1755 If the path of the link is a file path it is expanded using
1756 `expand-file-name'."
1757 (let* ((case-fold-search t
)
1758 (raw (and (looking-at org-bracket-link-regexp
)
1759 (org-babel-clean-text-properties (match-string 1))))
1760 (type (and (string-match org-link-types-re raw
)
1761 (match-string 1 raw
))))
1763 ((not type
) (expand-file-name raw
))
1764 ((string= type
"file")
1765 (and (string-match "file\\(.*\\):\\(.+\\)" raw
)
1766 (expand-file-name (match-string 2 raw
))))
1769 (defun org-babel-format-result (result &optional sep
)
1770 "Format RESULT for writing to file."
1771 (flet ((echo-res (result)
1772 (if (stringp result
) result
(format "%S" result
))))
1781 (echo-res result
))))
1783 (defun org-babel-insert-result
1784 (result &optional result-params info hash indent lang
)
1785 "Insert RESULT into the current buffer.
1786 By default RESULT is inserted after the end of the
1787 current source block. With optional argument RESULT-PARAMS
1788 controls insertion of results in the org-mode file.
1789 RESULT-PARAMS can take the following values...
1791 replace - (default option) insert results after the source block
1792 replacing any previously inserted results
1794 silent -- no results are inserted
1796 file ---- the results are interpreted as a file path, and are
1797 inserted into the buffer using the Org-mode file syntax
1799 list ---- the results are interpreted as an Org-mode list.
1801 raw ----- results are added directly to the Org-mode file. This
1802 is a good option if you code block will output org-mode
1805 wrap ---- results are added directly to the Org-mode file as with
1806 \"raw\", but are wrapped in a RESULTS drawer, allowing
1807 them to later be replaced or removed automatically.
1809 org ----- similar in effect to raw, only the results are wrapped
1810 in an org code block. Similar to the raw option, on
1811 export the results will be interpreted as org-formatted
1812 text, however by wrapping the results in an org code
1813 block they can be replaced upon re-execution of the
1816 html ---- results are added inside of a #+BEGIN_HTML block. This
1817 is a good option if you code block will output html
1820 latex --- results are added inside of a #+BEGIN_LATEX block.
1821 This is a good option if you code block will output
1822 latex formatted text.
1824 code ---- the results are extracted in the syntax of the source
1825 code of the language being evaluated and are added
1826 inside of a #+BEGIN_SRC block with the source-code
1827 language set appropriately. Note this relies on the
1828 optional LANG argument."
1829 (if (stringp result
)
1831 (setq result
(org-babel-clean-text-properties result
))
1832 (when (member "file" result-params
)
1833 (setq result
(org-babel-result-to-file result
))))
1834 (unless (listp result
) (setq result
(format "%S" result
))))
1835 (if (and result-params
(member "silent" result-params
))
1837 (message (replace-regexp-in-string "%" "%%" (format "%S" result
)))
1842 (when (or (org-babel-get-inline-src-block-matches)
1843 (org-babel-get-lob-one-liner-matches))
1844 (goto-char (match-end 0))
1845 (insert (if (listp result
) "\n" " "))
1847 (existing-result (unless inlinep
1848 (org-babel-where-is-src-block-result
1849 t info hash indent
)))
1851 (cdr (assoc :results_switches
(nth 2 info
))))
1853 (when (and (stringp result
) ; ensure results end in a newline
1855 (> (length result
) 0)
1856 (not (or (string-equal (substring result -
1) "\n")
1857 (string-equal (substring result -
1) "\r"))))
1858 (setq result
(concat result
"\n")))
1859 (if (not existing-result
)
1860 (setq beg
(or inlinep
(point)))
1861 (goto-char existing-result
)
1863 (re-search-forward "#" nil t
)
1864 (setq indent
(- (current-column) 1)))
1868 ((member "replace" result-params
)
1869 (delete-region (point) (org-babel-result-end)))
1870 ((member "append" result-params
)
1871 (goto-char (org-babel-result-end)) (setq beg
(point-marker)))
1872 ((member "prepend" result-params
)))) ; already there
1873 (setq results-switches
1874 (if results-switches
(concat " " results-switches
) ""))
1875 (flet ((wrap (start finish
)
1876 (goto-char beg
) (insert (concat start
"\n"))
1877 (goto-char end
) (insert (concat finish
"\n"))
1878 (setq end
(point-marker)))
1879 (proper-list-p (it) (and (listp it
) (null (cdr (last it
))))))
1880 ;; insert results based on type
1882 ;; do nothing for an empty result
1884 ;; insert a list if preferred
1885 ((member "list" result-params
)
1888 (org-list-to-generic
1891 (lambda (el) (list nil
(if (stringp el
) el
(format "%S" el
))))
1892 (if (listp result
) result
(list result
))))
1893 '(:splicep nil
:istart
"- " :iend
"\n")))
1895 ;; assume the result is a table if it's not a string
1896 ((proper-list-p result
)
1898 (insert (concat (orgtbl-to-orgtbl
1899 (if (or (eq 'hline
(car result
))
1900 (and (listp (car result
))
1901 (listp (cdr (car result
)))))
1902 result
(list result
))
1903 '(:fmt
(lambda (cell) (format "%s" cell
)))) "\n"))
1904 (goto-char beg
) (when (org-at-table-p) (org-table-align)))
1905 ((and (listp result
) (not (proper-list-p result
)))
1906 (insert (format "%s\n" result
)))
1907 ((member "file" result-params
)
1908 (when inlinep
(goto-char inlinep
))
1910 (t (goto-char beg
) (insert result
)))
1911 (when (proper-list-p result
) (goto-char (org-table-end)))
1912 (setq end
(point-marker))
1913 ;; possibly wrap result
1915 ((assoc :wrap
(nth 2 info
))
1916 (let ((name (or (cdr (assoc :wrap
(nth 2 info
))) "RESULTS")))
1917 (wrap (concat "#+BEGIN_" name
) (concat "#+END_" name
))))
1918 ((member "html" result-params
)
1919 (wrap "#+BEGIN_HTML" "#+END_HTML"))
1920 ((member "latex" result-params
)
1921 (wrap "#+BEGIN_LaTeX" "#+END_LaTeX"))
1922 ((member "code" result-params
)
1923 (wrap (format "#+BEGIN_SRC %s%s" (or lang
"none") results-switches
)
1925 ((member "org" result-params
)
1926 (wrap "#+BEGIN_ORG" "#+END_ORG"))
1927 ((member "raw" result-params
)
1928 (goto-char beg
) (if (org-at-table-p) (org-cycle)))
1929 ((member "wrap" result-params
)
1930 (wrap ":RESULTS:" ":END:"))
1931 ((and (not (proper-list-p result
))
1932 (not (member "file" result-params
)))
1933 (org-babel-examplize-region beg end results-switches
)
1934 (setq end
(point)))))
1935 ;; possibly indent the results to match the #+results line
1936 (when (and (not inlinep
) (numberp indent
) indent
(> indent
0)
1937 ;; in this case `table-align' does the work for us
1938 (not (and (listp result
)
1939 (member "append" result-params
))))
1940 (indent-rigidly beg end indent
))))
1942 (if (member "value" result-params
)
1943 (message "Code block returned no value.")
1944 (message "Code block produced no output."))
1945 (message "Code block evaluation complete."))))
1947 (defun org-babel-remove-result (&optional info
)
1948 "Remove the result of the current source block."
1950 (let ((location (org-babel-where-is-src-block-result nil info
)) start
)
1952 (setq start
(- location
1))
1954 (goto-char location
) (forward-line 1)
1955 (delete-region start
(org-babel-result-end))))))
1957 (defun org-babel-result-end ()
1958 "Return the point at the end of the current set of results"
1961 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
1962 ((org-at-item-p) (let* ((struct (org-list-struct))
1963 (prvs (org-list-prevs-alist struct
)))
1964 (org-list-get-list-end (point-at-bol) struct prvs
)))
1965 ((looking-at "^\\([ \t]*\\):RESULTS:")
1966 (progn (re-search-forward (concat "^" (match-string 1) ":END:"))
1967 (forward-char 1) (point)))
1969 (let ((case-fold-search t
))
1970 (if (looking-at (concat "[ \t]*#\\+begin_\\([^ \t\n\r]+\\)"))
1971 (progn (re-search-forward (concat "[ \t]*#\\+end_" (match-string 1))
1974 (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
1978 (defun org-babel-result-to-file (result)
1979 "Convert RESULT into an `org-mode' link.
1980 If the `default-directory' is different from the containing
1981 file's directory then expand relative links."
1982 (flet ((cond-exp (file)
1983 (if (and default-directory
1985 (not (string= (expand-file-name default-directory
)
1987 (file-name-directory buffer-file-name
)))))
1988 (expand-file-name file default-directory
)
1990 (if (stringp result
)
1991 (format "[[file:%s]]" (cond-exp result
))
1992 (when (and (listp result
) (= 2 (length result
))
1993 (stringp (car result
)) (stringp (cadr result
)))
1994 (format "[[file:%s][%s]]" (car result
) (cadr result
))))))
1996 (defun org-babel-examplize-region (beg end
&optional results-switches
)
1997 "Comment out region using the inline '==' or ': ' org example quote."
1999 (flet ((chars-between (b e
)
2000 (not (string-match "^[\\s]*$" (buffer-substring b e
)))))
2001 (if (or (chars-between (save-excursion (goto-char beg
) (point-at-bol)) beg
)
2002 (chars-between end
(save-excursion (goto-char end
) (point-at-eol))))
2005 (insert (format "=%s=" (prog1 (buffer-substring beg end
)
2006 (delete-region beg end
)))))
2007 (let ((size (count-lines beg end
)))
2009 (cond ((= size
0)) ; do nothing for an empty result
2010 ((< size org-babel-min-lines-for-block-output
)
2013 (beginning-of-line 1) (insert ": ") (forward-line 1)))
2016 (insert (if results-switches
2017 (format "#+begin_example%s\n" results-switches
)
2018 "#+begin_example\n"))
2019 (if (markerp end
) (goto-char end
) (forward-char (- end beg
)))
2020 (insert "#+end_example\n"))))))))
2022 (defun org-babel-update-block-body (new-body)
2023 "Update the body of the current code block to NEW-BODY."
2024 (if (not (org-babel-where-is-src-block-head))
2025 (error "not in source block")
2027 (replace-match (concat (org-babel-trim new-body
) "\n") nil t nil
5))
2028 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
2030 (defun org-babel-merge-params (&rest plists
)
2031 "Combine all parameter association lists in PLISTS.
2032 Later elements of PLISTS override the values of previous elements.
2033 This takes into account some special considerations for certain
2034 parameters when merging lists."
2035 (let ((results-exclusive-groups
2036 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2037 (cdr (assoc 'results org-babel-common-header-args-w-values
))))
2038 (exports-exclusive-groups
2039 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2040 (cdr (assoc 'exports org-babel-common-header-args-w-values
))))
2042 params results exports tangle noweb cache vars shebang comments padline
)
2043 (flet ((e-merge (exclusive-groups &rest result-params
)
2044 ;; maintain exclusivity of mutually exclusive parameters
2046 (mapc (lambda (new-params)
2047 (mapc (lambda (new-param)
2048 (mapc (lambda (exclusive-group)
2049 (when (member new-param exclusive-group
)
2050 (mapcar (lambda (excluded-param)
2057 (setq output
(org-uniquify
2058 (cons new-param output
))))
2068 (let ((name (if (listp (cdr pair
))
2070 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
2072 (intern (match-string 1 (cdr pair
)))))))
2076 (if (member name
(mapcar #'car vars
))
2080 (unless (equal (car p
) name
) p
))
2083 (list (cons name pair
))))
2084 ;; if no name is given and we already have named variables
2085 ;; then assign to named variables in order
2086 (if (and vars
(nth variable-index vars
))
2087 (prog1 (setf (cddr (nth variable-index vars
))
2088 (concat (symbol-name
2089 (car (nth variable-index vars
)))
2091 (incf variable-index
))
2092 (error "variable \"%s\" must be assigned a default value"
2095 (setq results
(e-merge results-exclusive-groups
2098 (let ((r (cdr pair
)))
2099 (if (stringp r
) r
(eval r
)))))))
2102 (setq results
(e-merge results-exclusive-groups
2104 (unless (or (member "both" exports
)
2105 (member "none" exports
)
2106 (member "code" exports
))
2107 (setq exports
(e-merge exports-exclusive-groups
2108 exports
'("results"))))
2109 (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))
2111 (setq exports
(e-merge exports-exclusive-groups
2112 exports
(split-string (cdr pair
)))))
2113 (:tangle
;; take the latest -- always overwrite
2114 (setq tangle
(or (list (cdr pair
)) tangle
)))
2116 (setq noweb
(e-merge
2117 '(("yes" "no" "tangle" "no-export" "strip-export"))
2119 (split-string (or (cdr pair
) "")))))
2121 (setq cache
(e-merge '(("yes" "no")) cache
2122 (split-string (or (cdr pair
) "")))))
2124 (setq padline
(e-merge '(("yes" "no")) padline
2125 (split-string (or (cdr pair
) "")))))
2126 (:shebang
;; take the latest -- always overwrite
2127 (setq shebang
(or (list (cdr pair
)) shebang
)))
2129 (setq comments
(e-merge '(("yes" "no")) comments
2130 (split-string (or (cdr pair
) "")))))
2131 (t ;; replace: this covers e.g. :session
2132 (setq params
(cons pair
(assq-delete-all (car pair
) params
))))))
2135 (setq vars
(reverse vars
))
2136 (while vars
(setq params
(cons (cons :var
(cddr (pop vars
))) params
)))
2139 (let ((key (intern (concat ":" (symbol-name hd
))))
2141 (setf params
(cons (cons key
(mapconcat 'identity val
" ")) params
))))
2142 '(results exports tangle noweb padline cache shebang comments
))
2145 (defvar *org-babel-use-quick-and-dirty-noweb-expansion
* nil
2146 "Set to true to use regular expressions to expand noweb references.
2147 This results in much faster noweb reference expansion but does
2148 not properly allow code blocks to inherit the \":noweb-ref\"
2149 header argument from buffer or subtree wide properties.")
2151 (defun org-babel-noweb-p (params context
)
2152 "Check if PARAMS require expansion in CONTEXT.
2153 CONTEXT may be one of :tangle, :export or :eval."
2154 (flet ((intersect (as bs
)
2156 (if (member (car as
) bs
)
2158 (intersect (cdr as
) bs
)))))
2159 (intersect (case context
2160 (:tangle
'("yes" "tangle" "no-export" "strip-export"))
2161 (:eval
'("yes" "no-export" "strip-export"))
2163 (split-string (or (cdr (assoc :noweb params
)) "")))))
2165 (defun org-babel-expand-noweb-references (&optional info parent-buffer
)
2166 "Expand Noweb references in the body of the current source code block.
2168 For example the following reference would be replaced with the
2169 body of the source-code block named 'example-block'.
2173 Note that any text preceding the <<foo>> construct on a line will
2174 be interposed between the lines of the replacement text. So for
2175 example if <<foo>> is placed behind a comment, then the entire
2176 replacement text will also be commented.
2178 This function must be called from inside of the buffer containing
2179 the source-code block which holds BODY.
2181 In addition the following syntax can be used to insert the
2182 results of evaluating the source-code block named 'example-block'.
2186 Any optional arguments can be passed to example-block by placing
2187 the arguments inside the parenthesis following the convention
2188 defined by `org-babel-lob'. For example
2190 <<example-block(a=9)>>
2192 would set the value of argument \"a\" equal to \"9\". Note that
2193 these arguments are not evaluated in the current source-code
2194 block but are passed literally to the \"example-block\"."
2195 (let* ((parent-buffer (or parent-buffer
(current-buffer)))
2196 (info (or info
(org-babel-get-src-block-info)))
2199 (comment (string= "noweb" (cdr (assoc :comments
(nth 2 info
)))))
2200 (rx-prefix (concat "\\(" org-babel-src-name-regexp
"\\|"
2201 ":noweb-ref[ \t]+" "\\)"))
2202 (new-body "") index source-name evaluate prefix blocks-in-buffer
)
2203 (flet ((nb-add (text) (setq new-body
(concat new-body text
)))
2206 (funcall (intern (concat lang
"-mode")))
2207 (comment-region (point) (progn (insert text
) (point)))
2208 (org-babel-trim (buffer-string)))))
2210 (insert body
) (goto-char (point-min))
2211 (setq index
(point))
2212 (while (and (re-search-forward (org-babel-noweb-wrap) nil t
))
2213 (save-match-data (setf source-name
(match-string 1)))
2214 (save-match-data (setq evaluate
(string-match "\(.*\)" source-name
)))
2217 (buffer-substring (match-beginning 0)
2219 (beginning-of-line 1) (point)))))
2220 ;; add interval to new-body (removing noweb reference)
2221 (goto-char (match-beginning 0))
2222 (nb-add (buffer-substring index
(point)))
2223 (goto-char (match-end 0))
2224 (setq index
(point))
2226 (with-current-buffer parent-buffer
2227 (mapconcat ;; interpose PREFIX between every line
2231 (let ((raw (org-babel-ref-resolve source-name
)))
2232 (if (stringp raw
) raw
(format "%S" raw
)))
2234 ;; retrieve from the library of babel
2235 (nth 2 (assoc (intern source-name
)
2236 org-babel-library-of-babel
))
2237 ;; return the contents of headlines literally
2239 (when (org-babel-ref-goto-headline-id source-name
)
2240 (org-babel-ref-headline-body)))
2241 ;; find the expansion of reference in this buffer
2242 (let ((rx (concat rx-prefix source-name
))
2245 (goto-char (point-min))
2246 (if *org-babel-use-quick-and-dirty-noweb-expansion
*
2247 (while (re-search-forward rx nil t
)
2248 (let* ((i (org-babel-get-src-block-info 'light
))
2249 (body (org-babel-expand-noweb-references i
))
2250 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2254 (concat (c-wrap (car cs
)) "\n"
2256 (c-wrap (cadr cs
))))
2257 (org-babel-tangle-comment-links i
))
2259 (setq expansion
(cons sep
(cons full expansion
)))))
2260 (org-babel-map-src-blocks nil
2261 (let ((i (org-babel-get-src-block-info 'light
)))
2262 (when (equal (or (cdr (assoc :noweb-ref
(nth 2 i
)))
2265 (let* ((body (org-babel-expand-noweb-references i
))
2266 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2270 (concat (c-wrap (car cs
)) "\n"
2272 (c-wrap (cadr cs
))))
2273 (org-babel-tangle-comment-links i
))
2276 (cons sep
(cons full expansion
)))))))))
2278 (mapconcat #'identity
(nreverse (cdr expansion
)) "")))
2279 ;; possibly raise an error if named block doesn't exist
2280 (if (member lang org-babel-noweb-error-langs
)
2282 (org-babel-noweb-wrap source-name
)
2283 "could not be resolved (see "
2284 "`org-babel-noweb-error-langs')"))
2286 "[\n\r]") (concat "\n" prefix
)))))
2287 (nb-add (buffer-substring index
(point-max)))))
2290 (defun org-babel-clean-text-properties (text)
2291 "Strip all properties from text return."
2293 (set-text-properties 0 (length text
) nil text
) text
))
2295 (defun org-babel-strip-protective-commas (body)
2296 "Strip protective commas from bodies of source blocks."
2299 (org-strip-protective-commas (point-min) (point-max))
2302 (defun org-babel-script-escape (str &optional force
)
2303 "Safely convert tables into elisp lists."
2304 (let (in-single in-double out
)
2305 ((lambda (escaped) (condition-case nil
(org-babel-read escaped
) (error escaped
)))
2309 (or (and (string-equal "[" (substring str
0 1))
2310 (string-equal "]" (substring str -
1)))
2311 (and (string-equal "{" (substring str
0 1))
2312 (string-equal "}" (substring str -
1)))
2313 (and (string-equal "(" (substring str
0 1))
2314 (string-equal ")" (substring str -
1))))))
2324 (91 (if (or in-double in-single
) ; [
2327 (93 (if (or in-double in-single
) ; ]
2330 (123 (if (or in-double in-single
) ; {
2333 (125 (if (or in-double in-single
) ; }
2336 (44 (if (or in-double in-single
) ; ,
2337 (cons 44 out
) (cons 32 out
)))
2338 (39 (if in-double
; '
2340 (setq in-single
(not in-single
)) (cons 34 out
)))
2341 (34 (if in-single
; "
2342 (append (list 34 32) out
)
2343 (setq in-double
(not in-double
)) (cons 34 out
)))
2344 (t (cons ch out
)))))
2345 (string-to-list str
))
2346 (apply #'string
(reverse out
)))))
2349 (defun org-babel-read (cell &optional inhibit-lisp-eval
)
2350 "Convert the string value of CELL to a number if appropriate.
2351 Otherwise if cell looks like lisp (meaning it starts with a
2352 \"(\", \"'\", \"`\" or a \"[\") then read it as lisp, otherwise
2353 return it unmodified as a string. Optional argument NO-LISP-EVAL
2354 inhibits lisp evaluation for situations in which is it not
2356 (if (and (stringp cell
) (not (equal cell
"")))
2357 (or (org-babel-number-p cell
)
2358 (if (and (not inhibit-lisp-eval
)
2359 (member (substring cell
0 1) '("(" "'" "`" "[")))
2361 (if (string= (substring cell
0 1) "\"")
2363 (progn (set-text-properties 0 (length cell
) nil cell
) cell
))))
2366 (defun org-babel-number-p (string)
2367 "If STRING represents a number return its value."
2368 (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string
)
2369 (= (length (substring string
(match-beginning 0)
2372 (string-to-number string
)))
2374 (defun org-babel-import-elisp-from-file (file-name &optional separator
)
2375 "Read the results located at FILE-NAME into an elisp table.
2376 If the table is trivial, then return it as a scalar."
2378 (save-window-excursion
2382 (org-table-import file-name separator
)
2383 (delete-file file-name
)
2384 (setq result
(mapcar (lambda (row)
2385 (mapcar #'org-babel-string-read row
))
2386 (org-table-to-lisp))))
2388 (if (null (cdr result
)) ;; if result is trivial vector, then scalarize it
2389 (if (consp (car result
))
2390 (if (null (cdr (car result
)))
2396 (defun org-babel-string-read (cell)
2397 "Strip nested \"s from around strings."
2398 (org-babel-read (or (and (stringp cell
)
2399 (string-match "\\\"\\(.+\\)\\\"" cell
)
2400 (match-string 1 cell
))
2403 (defun org-babel-reverse-string (string)
2404 "Return the reverse of STRING."
2405 (apply 'string
(reverse (string-to-list string
))))
2407 (defun org-babel-chomp (string &optional regexp
)
2408 "Strip trailing spaces and carriage returns from STRING.
2409 Default regexp used is \"[ \f\t\n\r\v]\" but can be
2410 overwritten by specifying a regexp as a second argument."
2411 (let ((regexp (or regexp
"[ \f\t\n\r\v]")))
2412 (while (and (> (length string
) 0)
2413 (string-match regexp
(substring string -
1)))
2414 (setq string
(substring string
0 -
1)))
2417 (defun org-babel-trim (string &optional regexp
)
2418 "Strip leading and trailing spaces and carriage returns from STRING.
2419 Like `org-babel-chomp' only it runs on both the front and back
2421 (org-babel-chomp (org-babel-reverse-string
2422 (org-babel-chomp (org-babel-reverse-string string
) regexp
))
2425 (defvar org-babel-org-babel-call-process-region-original nil
)
2426 (defun org-babel-tramp-handle-call-process-region
2427 (start end program
&optional delete buffer display
&rest args
)
2428 "Use tramp to handle call-process-region.
2429 Fixes a bug in `tramp-handle-call-process-region'."
2430 (if (and (featurep 'tramp
) (file-remote-p default-directory
))
2431 (let ((tmpfile (tramp-compat-make-temp-file "")))
2432 (write-region start end tmpfile
)
2433 (when delete
(delete-region start end
))
2435 ;; (apply 'call-process program tmpfile buffer display args)
2437 (apply 'process-file program tmpfile buffer display args
)
2438 (delete-file tmpfile
)))
2439 ;; org-babel-call-process-region-original is the original emacs
2440 ;; definition. It is in scope from the let binding in
2441 ;; org-babel-execute-src-block
2442 (apply org-babel-call-process-region-original
2443 start end program delete buffer display args
)))
2445 (defun org-babel-local-file-name (file)
2446 "Return the local name component of FILE."
2447 (if (file-remote-p file
)
2449 (with-parsed-tramp-file-name file nil
2453 (defun org-babel-process-file-name (name &optional no-quote-p
)
2454 "Prepare NAME to be used in an external process.
2455 If NAME specifies a remote location, the remote portion of the
2456 name is removed, since in that case the process will be executing
2457 remotely. The file name is then processed by
2458 `expand-file-name'. Unless second argument NO-QUOTE-P is non-nil,
2459 the file name is additionally processed by
2460 `shell-quote-argument'"
2461 ((lambda (f) (if no-quote-p f
(shell-quote-argument f
)))
2462 (expand-file-name (org-babel-local-file-name name
))))
2464 (defvar org-babel-temporary-directory
)
2465 (unless (or noninteractive
(boundp 'org-babel-temporary-directory
))
2466 (defvar org-babel-temporary-directory
2467 (or (and (boundp 'org-babel-temporary-directory
)
2468 (file-exists-p org-babel-temporary-directory
)
2469 org-babel-temporary-directory
)
2470 (make-temp-file "babel-" t
))
2471 "Directory to hold temporary files created to execute code blocks.
2472 Used by `org-babel-temp-file'. This directory will be removed on
2475 (defun org-babel-temp-file (prefix &optional suffix
)
2476 "Create a temporary file in the `org-babel-temporary-directory'.
2477 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2478 value of `temporary-file-directory' temporarily set to the value
2479 of `org-babel-temporary-directory'."
2480 (if (file-remote-p default-directory
)
2482 (concat (file-remote-p default-directory
)
2484 prefix temporary-file-directory
)
2486 (let ((temporary-file-directory
2487 (or (and (boundp 'org-babel-temporary-directory
)
2488 (file-exists-p org-babel-temporary-directory
)
2489 org-babel-temporary-directory
)
2490 temporary-file-directory
)))
2491 (make-temp-file prefix nil suffix
))))
2493 (defun org-babel-remove-temporary-directory ()
2494 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2495 (when (and (boundp 'org-babel-temporary-directory
)
2496 (file-exists-p org-babel-temporary-directory
))
2497 ;; taken from `delete-directory' in files.el
2500 (mapc (lambda (file)
2501 ;; This test is equivalent to
2502 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2503 ;; but more efficient
2504 (if (eq t
(car (file-attributes file
)))
2505 (delete-directory file
)
2506 (delete-file file
)))
2507 ;; We do not want to delete "." and "..".
2508 (directory-files org-babel-temporary-directory
'full
2509 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2510 (delete-directory org-babel-temporary-directory
))
2512 (message "Failed to remove temporary Org-babel directory %s"
2513 (if (boundp 'org-babel-temporary-directory
)
2514 org-babel-temporary-directory
2515 "[directory not defined]"))))))
2517 (add-hook 'kill-emacs-hook
'org-babel-remove-temporary-directory
)