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 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-strip-protective-commas
"org" (beg end
))
63 (declare-function org-table-import
"org-table" (file arg
))
64 (declare-function org-add-hook
"org-compat"
65 (hook function
&optional append local
))
66 (declare-function org-table-align
"org-table" ())
67 (declare-function org-table-end
"org-table" (&optional table-type
))
68 (declare-function orgtbl-to-generic
"org-table" (table params
))
69 (declare-function orgtbl-to-orgtbl
"org-table" (table params
))
70 (declare-function org-babel-tangle-comment-links
"ob-tangle" (&optional info
))
71 (declare-function org-babel-lob-get-info
"ob-lob" nil
)
72 (declare-function org-babel-ref-split-args
"ob-ref" (arg-string))
73 (declare-function org-babel-ref-parse
"ob-ref" (assignment))
74 (declare-function org-babel-ref-resolve
"ob-ref" (ref))
75 (declare-function org-babel-ref-goto-headline-id
"ob-ref" (id))
76 (declare-function org-babel-ref-headline-body
"ob-ref" ())
77 (declare-function org-babel-lob-execute-maybe
"ob-lob" ())
78 (declare-function org-number-sequence
"org-compat" (from &optional to inc
))
79 (declare-function org-at-item-p
"org-list" ())
80 (declare-function org-list-parse-list
"org-list" (&optional delete
))
81 (declare-function org-list-to-generic
"org-list" (LIST PARAMS
))
82 (declare-function org-list-struct
"org-list" ())
83 (declare-function org-list-prevs-alist
"org-list" (struct))
84 (declare-function org-list-get-list-end
"org-list" (item struct prevs
))
85 (declare-function org-strip-protective-commas
"org" (beg end
))
87 (defgroup org-babel nil
88 "Code block evaluation and management in `org-mode' documents."
92 (defcustom org-confirm-babel-evaluate t
93 "Confirm before evaluation.
94 Require confirmation before interactively evaluating code
95 blocks in Org-mode buffers. The default value of this variable
96 is t, meaning confirmation is required for any code block
97 evaluation. This variable can be set to nil to inhibit any
98 future confirmation requests. This variable can also be set to a
99 function which takes two arguments the language of the code block
100 and the body of the code block. Such a function should then
101 return a non-nil value if the user should be prompted for
102 execution or nil if no prompt is required.
104 Warning: Disabling confirmation may result in accidental
105 evaluation of potentially harmful code. It may be advisable
106 remove code block execution from C-c C-c as further protection
107 against accidental code block evaluation. The
108 `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
109 remove code block execution from the C-c C-c keybinding."
112 :type
'(choice boolean function
))
113 ;; don't allow this variable to be changed through file settings
114 (put 'org-confirm-babel-evaluate
'safe-local-variable
(lambda (x) (eq x t
)))
116 (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
117 "Remove code block evaluation from the C-c C-c key binding."
122 (defcustom org-babel-results-keyword
"RESULTS"
123 "Keyword used to name results generated by code blocks.
124 Should be either RESULTS or NAME however any capitalization may
129 (defcustom org-babel-noweb-wrap-start
"<<"
130 "String used to begin a noweb reference in a code block.
131 See also `org-babel-noweb-wrap-end'."
135 (defcustom org-babel-noweb-wrap-end
">>"
136 "String used to end a noweb reference in a code block.
137 See also `org-babel-noweb-wrap-start'."
141 (defun org-babel-noweb-wrap (&optional regexp
)
142 (concat org-babel-noweb-wrap-start
143 (or regexp
"\\([^ \t\n].+?[^ \t]\\|[^ \t\n]\\)")
144 org-babel-noweb-wrap-end
))
146 (defvar org-babel-src-name-regexp
147 "^[ \t]*#\\+name:[ \t]*"
148 "Regular expression used to match a source name line.")
150 (defvar org-babel-multi-line-header-regexp
151 "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
152 "Regular expression used to match multi-line header arguments.")
154 (defvar org-babel-src-name-w-name-regexp
155 (concat org-babel-src-name-regexp
157 org-babel-multi-line-header-regexp
159 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)")
160 "Regular expression matching source name lines with a name.")
162 (defvar org-babel-src-block-regexp
164 ;; (1) indentation (2) lang
165 "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
167 "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
168 ;; (4) header arguments
171 "\\([^\000]*?\n\\)?[ \t]*#\\+end_src")
172 "Regexp used to identify code blocks.")
174 (defvar org-babel-inline-src-block-regexp
176 ;; (1) replacement target (2) lang
177 "\\(?:^\\|[^-[:alnum:]]\\)\\(src_\\([^ \f\t\n\r\v]+\\)"
178 ;; (3,4) (unused, headers)
179 "\\(\\|\\[\\(.*?\\)\\]\\)"
181 "{\\([^\f\n\r\v]+?\\)}\\)")
182 "Regexp used to identify inline src-blocks.")
184 (defun org-babel-get-header (params key
&optional others
)
185 "Select only header argument of type KEY from a list.
186 Optional argument OTHERS indicates that only the header that do
187 not match KEY should be returned."
190 (lambda (p) (when (funcall (if others
#'not
#'identity
) (eq (car p
) key
)) p
))
193 (defun org-babel-get-inline-src-block-matches()
194 "Set match data if within body of an inline source block.
195 Returns non-nil if match-data set"
196 (let ((src-at-0-p (save-excursion
197 (beginning-of-line 1)
198 (string= "src" (thing-at-point 'word
))))
199 (first-line-p (= 1 (line-number-at-pos)))
201 (let ((search-for (cond ((and src-at-0-p first-line-p
"src_"))
202 (first-line-p "[[:punct:] \t]src_")
203 (t "[[:punct:] \f\t\n\r\v]src_")))
204 (lower-limit (if first-line-p
206 (- (point-at-bol) 1))))
208 (when (or (and src-at-0-p
(bobp))
209 (and (re-search-forward "}" (point-at-eol) t
)
210 (re-search-backward search-for lower-limit t
)
212 (when (looking-at org-babel-inline-src-block-regexp
)
215 (defvar org-babel-inline-lob-one-liner-regexp
)
216 (defun org-babel-get-lob-one-liner-matches()
217 "Set match data if on line of an lob one liner.
218 Returns non-nil if match-data set"
220 (unless (= (point) (point-at-bol)) ;; move before inline block
221 (re-search-backward "[ \f\t\n\r\v]" nil t
))
222 (if (looking-at org-babel-inline-lob-one-liner-regexp
)
226 (defun org-babel-get-src-block-info (&optional light
)
227 "Get information on the current source block.
229 Optional argument LIGHT does not resolve remote variable
230 references; a process which could likely result in the execution
231 of other code blocks.
234 (language body header-arguments-alist switches name indent)."
235 (let ((case-fold-search t
) head info name indent
)
237 (if (setq head
(org-babel-where-is-src-block-head))
240 (setq info
(org-babel-parse-src-block-match))
241 (setq indent
(car (last info
)))
242 (setq info
(butlast info
))
243 (while (and (forward-line -
1)
244 (looking-at org-babel-multi-line-header-regexp
))
246 (org-babel-merge-params
248 (org-babel-parse-header-arguments (match-string 1)))))
249 (when (looking-at org-babel-src-name-w-name-regexp
)
250 (setq name
(org-babel-clean-text-properties (match-string 3)))
251 (when (and (match-string 5) (> (length (match-string 5)) 0))
252 (setf (nth 2 info
) ;; merge functional-syntax vars and header-args
253 (org-babel-merge-params
255 (lambda (ref) (cons :var ref
))
257 (lambda (var) ;; check that each variable is initialized
258 (if (string-match ".+=.+" var
)
261 "variable \"%s\"%s must be assigned a default value"
262 var
(if name
(format " in block \"%s\"" name
) ""))))
263 (org-babel-ref-split-args (match-string 5))))
265 ;; inline source block
266 (when (org-babel-get-inline-src-block-matches)
267 (setq info
(org-babel-parse-inline-src-block-match))))
268 ;; resolve variable references and add summary parameters
269 (when (and info
(not light
))
270 (setf (nth 2 info
) (org-babel-process-params (nth 2 info
))))
271 (when info
(append info
(list name indent
)))))
273 (defvar org-current-export-file
) ; dynamically bound
274 (defun org-babel-confirm-evaluate (info)
275 "Confirm evaluation of the code block INFO.
276 This behavior can be suppressed by setting the value of
277 `org-confirm-babel-evaluate' to nil, in which case all future
278 interactive code block evaluations will proceed without any
279 confirmation from the user.
281 Note disabling confirmation may result in accidental evaluation
282 of potentially harmful code."
283 (let* ((eval (or (cdr (assoc :eval
(nth 2 info
)))
284 (when (assoc :noeval
(nth 2 info
)) "no")))
285 (query (cond ((equal eval
"query") t
)
286 ((and org-current-export-file
287 (equal eval
"query-export")) t
)
288 ((functionp org-confirm-babel-evaluate
)
289 (funcall org-confirm-babel-evaluate
290 (nth 0 info
) (nth 1 info
)))
291 (t org-confirm-babel-evaluate
))))
292 (if (or (equal eval
"never") (equal eval
"no")
293 (and org-current-export-file
(or (equal eval
"no-export")
294 (equal eval
"never-export")))
297 (format "Evaluate this%scode block%son your system? "
298 (if info
(format " %s " (nth 0 info
)) " ")
300 (format " (%s) " (nth 4 info
)) " "))))))
301 (prog1 nil
(message "Evaluation %s"
302 (if (or (equal eval
"never") (equal eval
"no")
303 (equal eval
"no-export")
304 (equal eval
"never-export"))
305 "Disabled" "Aborted")))
309 (defun org-babel-execute-safely-maybe ()
310 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
311 (org-babel-execute-maybe)))
313 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-execute-safely-maybe
)
316 (defun org-babel-execute-maybe ()
318 (or (org-babel-execute-src-block-maybe)
319 (org-babel-lob-execute-maybe)))
321 (defun org-babel-execute-src-block-maybe ()
322 "Conditionally execute a source block.
323 Detect if this is context for a Babel src-block and if so
324 then run `org-babel-execute-src-block'."
326 (let ((info (org-babel-get-src-block-info)))
328 (progn (org-babel-eval-wipe-error-buffer)
329 (org-babel-execute-src-block current-prefix-arg info
) t
) nil
)))
332 (defun org-babel-view-src-block-info ()
333 "Display information on the current source block.
334 This includes header arguments, language and name, and is largely
335 a window into the `org-babel-get-src-block-info' function."
337 (let ((info (org-babel-get-src-block-info 'light
)))
338 (flet ((full (it) (> (length it
) 0))
339 (printf (fmt &rest args
) (princ (apply #'format fmt args
))))
341 (with-help-window (help-buffer)
342 (let ((name (nth 4 info
))
344 (switches (nth 3 info
))
345 (header-args (nth 2 info
)))
346 (when name
(printf "Name: %s\n" name
))
347 (when lang
(printf "Lang: %s\n" lang
))
348 (when (full switches
) (printf "Switches: %s\n" switches
))
349 (printf "Header Arguments:\n")
350 (dolist (pair (sort header-args
351 (lambda (a b
) (string< (symbol-name (car a
))
352 (symbol-name (car b
))))))
353 (when (full (cdr pair
))
354 (printf "\t%S%s\t%s\n"
356 (if (> (length (format "%S" (car pair
))) 7) "" "\t")
360 (defun org-babel-expand-src-block-maybe ()
361 "Conditionally expand a source block.
362 Detect if this is context for a org-babel src-block and if so
363 then run `org-babel-expand-src-block'."
365 (let ((info (org-babel-get-src-block-info)))
367 (progn (org-babel-expand-src-block current-prefix-arg info
) t
)
371 (defun org-babel-load-in-session-maybe ()
372 "Conditionally load a source block in a session.
373 Detect if this is context for a org-babel src-block and if so
374 then run `org-babel-load-in-session'."
376 (let ((info (org-babel-get-src-block-info)))
378 (progn (org-babel-load-in-session current-prefix-arg info
) t
)
381 (add-hook 'org-metaup-hook
'org-babel-load-in-session-maybe
)
384 (defun org-babel-pop-to-session-maybe ()
385 "Conditionally pop to a session.
386 Detect if this is context for a org-babel src-block and if so
387 then run `org-babel-pop-to-session'."
389 (let ((info (org-babel-get-src-block-info)))
390 (if info
(progn (org-babel-pop-to-session current-prefix-arg info
) t
) nil
)))
392 (add-hook 'org-metadown-hook
'org-babel-pop-to-session-maybe
)
394 (defconst org-babel-common-header-args-w-values
395 '((cache .
((no yes
)))
397 (colnames .
((nil no yes
)))
398 (comments .
((no link yes org both noweb
)))
400 (eval .
((never query
)))
401 (exports .
((code results both none
)))
404 (hlines .
((no yes
)))
405 (mkdirp .
((yes no
)))
408 (noweb .
((yes no tangle no-export strip-export
)))
411 (padline .
((yes no
)))
412 (results .
((file list vector table scalar verbatim
)
413 (raw org html latex code pp wrap
)
414 (replace silent append prepend
)
416 (rownames .
((no yes
)))
420 (tangle .
((tangle yes no
:any
)))
424 (defconst org-babel-header-arg-names
425 (mapcar #'car org-babel-common-header-args-w-values
)
426 "Common header arguments used by org-babel.
427 Note that individual languages may define their own language
428 specific header arguments as well.")
430 (defvar org-babel-default-header-args
431 '((:session .
"none") (:results .
"replace") (:exports .
"code")
432 (:cache .
"no") (:noweb .
"no") (:hlines .
"no") (:tangle .
"no")
433 (:padnewline .
"yes"))
434 "Default arguments to use when evaluating a source block.")
436 (defvar org-babel-default-inline-header-args
437 '((:session .
"none") (:results .
"replace") (:exports .
"results"))
438 "Default arguments to use when evaluating an inline source block.")
440 (defvar org-babel-data-names
'("TBLNAME" "RESULTS" "NAME"))
442 (defvar org-babel-result-regexp
443 (concat "^[ \t]*#\\+"
444 (regexp-opt org-babel-data-names t
)
445 "\\(\\[\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*")
446 "Regular expression used to match result lines.
447 If the results are associated with a hash key then the hash will
448 be saved in the second match data.")
450 (defvar org-babel-result-w-name-regexp
451 (concat org-babel-result-regexp
452 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
454 (defvar org-babel-min-lines-for-block-output
10
455 "The minimum number of lines for block output.
456 If number of lines of output is equal to or exceeds this
457 value, the output is placed in a #+begin_example...#+end_example
458 block. Otherwise the output is marked as literal by inserting
459 colons at the starts of the lines. This variable only takes
460 effect if the :results output option is in effect.")
462 (defvar org-babel-noweb-error-langs nil
463 "Languages for which Babel will raise literate programming errors.
464 List of languages for which errors should be raised when the
465 source code block satisfying a noweb reference in this language
466 can not be resolved.")
468 (defvar org-babel-hash-show
4
469 "Number of initial characters to show of a hidden results hash.")
471 (defvar org-babel-after-execute-hook nil
472 "Hook for functions to be called after `org-babel-execute-src-block'")
474 (defun org-babel-named-src-block-regexp-for-name (name)
475 "This generates a regexp used to match a src block named NAME."
476 (concat org-babel-src-name-regexp
(regexp-quote name
)
477 "\\([ \t]\\|$\\|(\\)" ".*[\r\n]"
478 (substring org-babel-src-block-regexp
1)))
480 (defun org-babel-named-data-regexp-for-name (name)
481 "This generates a regexp used to match data named NAME."
482 (concat org-babel-result-regexp
(regexp-quote name
) "\\([ \t]\\|$\\)"))
485 (defvar call-process-region
)
488 (defun org-babel-execute-src-block (&optional arg info params
)
489 "Execute the current source code block.
490 Insert the results of execution into the buffer. Source code
491 execution and the collection and formatting of results can be
492 controlled through a variety of header arguments.
494 With prefix argument ARG, force re-execution even if an existing
495 result cached in the buffer would otherwise have been returned.
497 Optionally supply a value for INFO in the form returned by
498 `org-babel-get-src-block-info'.
500 Optionally supply a value for PARAMS which will be merged with
501 the header arguments specified at the front of the source code
504 (let ((info (or info
(org-babel-get-src-block-info))))
505 (when (org-babel-confirm-evaluate
507 (setf (nth 2 i
) (org-babel-merge-params (nth 2 info
) params
))
509 (let* ((lang (nth 0 info
))
511 (org-babel-process-params
512 (org-babel-merge-params (nth 2 info
) params
))
514 (cache?
(and (not arg
) (cdr (assoc :cache params
))
515 (string= "yes" (cdr (assoc :cache params
)))))
516 (result-params (cdr (assoc :result-params params
)))
517 (new-hash (when cache?
(org-babel-sha1-hash info
)))
518 (old-hash (when cache?
(org-babel-current-result-hash)))
519 (body (setf (nth 1 info
)
520 (if (org-babel-noweb-p params
:eval
)
521 (org-babel-expand-noweb-references info
)
523 (dir (cdr (assoc :dir params
)))
525 (or (and dir
(file-name-as-directory dir
)) default-directory
))
526 (org-babel-call-process-region-original
527 (if (boundp 'org-babel-call-process-region-original
)
528 org-babel-call-process-region-original
529 (symbol-function 'call-process-region
)))
530 (indent (car (last info
)))
533 (flet ((call-process-region (&rest args
)
534 (apply 'org-babel-tramp-handle-call-process-region args
)))
535 (flet ((lang-check (f)
536 (let ((f (intern (concat "org-babel-execute:" f
))))
537 (when (fboundp f
) f
))))
539 (or (lang-check lang
)
540 (lang-check (symbol-name
541 (cdr (assoc lang org-src-lang-modes
))))
542 (error "No org-babel-execute function for %s!" lang
))))
543 (if (and (not arg
) new-hash
(equal new-hash old-hash
))
544 (save-excursion ;; return cached result
545 (goto-char (org-babel-where-is-src-block-result nil info
))
546 (end-of-line 1) (forward-char 1)
547 (setq result
(org-babel-read-result))
548 (message (replace-regexp-in-string
549 "%" "%%" (format "%S" result
))) result
)
550 (message "executing %s code block%s..."
552 (if (nth 4 info
) (format " (%s)" (nth 4 info
)) ""))
555 (if (and (eq (cdr (assoc :result-type params
)) 'value
)
556 (or (member "vector" result-params
)
557 (member "table" result-params
))
558 (not (listp result
)))
559 (list (list result
)) result
))
560 (funcall cmd body params
)))
561 ;; if non-empty result and :file then write to :file
562 (when (cdr (assoc :file params
))
564 (with-temp-file (cdr (assoc :file params
))
566 (org-babel-format-result
567 result
(cdr (assoc :sep
(nth 2 info
)))))))
568 (setq result
(cdr (assoc :file params
))))
569 (org-babel-insert-result
570 result result-params info new-hash indent lang
)
571 (run-hooks 'org-babel-after-execute-hook
)
573 (setq call-process-region
'org-babel-call-process-region-original
))))))
575 (defun org-babel-expand-body:generic
(body params
&optional var-lines
)
576 "Expand BODY with PARAMS.
577 Expand a block of code with org-babel according to its header
578 arguments. This generic implementation of body expansion is
579 called for languages which have not defined their own specific
580 org-babel-expand-body:lang function."
581 (mapconcat #'identity
(append var-lines
(list body
)) "\n"))
584 (defun org-babel-expand-src-block (&optional arg info params
)
585 "Expand the current source code block.
586 Expand according to the source code block's header
587 arguments and pop open the results in a preview buffer."
589 (let* ((info (or info
(org-babel-get-src-block-info)))
591 (params (setf (nth 2 info
)
592 (sort (org-babel-merge-params (nth 2 info
) params
)
593 (lambda (el1 el2
) (string< (symbol-name (car el1
))
594 (symbol-name (car el2
)))))))
595 (body (setf (nth 1 info
)
596 (if (org-babel-noweb-p params
:eval
)
597 (org-babel-expand-noweb-references info
) (nth 1 info
))))
598 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
599 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
602 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
603 (org-babel-expand-body:generic
604 body params
(and (fboundp assignments-cmd
)
605 (funcall assignments-cmd params
))))))
607 nil expanded
(concat "*Org-Babel Preview " (buffer-name) "[ " lang
" ]*"))))
609 (defun org-babel-edit-distance (s1 s2
)
610 "Return the edit (levenshtein) distance between strings S1 S2."
611 (let* ((l1 (length s1
))
613 (dist (map 'vector
(lambda (_) (make-vector (1+ l2
) nil
))
614 (number-sequence 1 (1+ l1
)))))
615 (flet ((in (i j
) (aref (aref dist i
) j
))
616 (mmin (&rest lst
) (apply #'min
(remove nil lst
))))
617 (setf (aref (aref dist
0) 0) 0)
618 (dolist (i (number-sequence 1 l1
))
619 (dolist (j (number-sequence 1 l2
))
620 (setf (aref (aref dist i
) j
)
621 (+ (if (equal (aref s1
(1- i
)) (aref s2
(1- j
))) 0 1)
622 (mmin (in (1- i
) j
) (in i
(1- j
)) (in (1- i
) (1- j
)))))))
626 (defun org-babel-check-src-block ()
627 "Check for misspelled header arguments in the current code block."
629 ;; TODO: report malformed code block
630 ;; TODO: report incompatible combinations of header arguments
631 ;; TODO: report uninitialized variables
632 (let ((too-close 2) ;; <- control closeness to report potential match
633 (names (mapcar #'symbol-name org-babel-header-arg-names
)))
634 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg
)) 1))
635 (and (org-babel-where-is-src-block-head)
636 (org-babel-parse-header-arguments
637 (org-babel-clean-text-properties
638 (match-string 4))))))
640 (when (and (not (string= header name
))
641 (<= (org-babel-edit-distance header name
) too-close
)
642 (not (member header names
)))
643 (error "supplied header \"%S\" is suspiciously close to \"%S\""
645 (message "No suspicious header arguments found.")))
648 (defun org-babel-insert-header-arg ()
649 "Insert a header argument selecting from lists of common args and values."
651 (let* ((lang (car (org-babel-get-src-block-info 'light
)))
652 (lang-headers (intern (concat "org-babel-header-arg-names:" lang
)))
653 (headers (append (if (boundp lang-headers
)
654 (mapcar (lambda (h) (cons h
:any
))
657 org-babel-common-header-args-w-values
))
658 (arg (org-icompleting-read
661 (lambda (header-spec) (symbol-name (car header-spec
)))
664 (let ((vals (cdr (assoc (intern arg
) headers
))))
670 (read-from-minibuffer "value: "))
674 (let ((arg (org-icompleting-read
676 (cons "default" (mapcar #'symbol-name group
)))))
677 (if (and arg
(not (string= "default" arg
)))
683 (defun org-babel-load-in-session (&optional arg info
)
684 "Load the body of the current source-code block.
685 Evaluate the header arguments for the source block before
686 entering the session. After loading the body this pops open the
689 (let* ((info (or info
(org-babel-get-src-block-info)))
691 (params (nth 2 info
))
692 (body (setf (nth 1 info
)
693 (if (org-babel-noweb-p params
:eval
)
694 (org-babel-expand-noweb-references info
)
696 (session (cdr (assoc :session params
)))
697 (dir (cdr (assoc :dir params
)))
699 (or (and dir
(file-name-as-directory dir
)) default-directory
))
700 (cmd (intern (concat "org-babel-load-session:" lang
))))
701 (unless (fboundp cmd
)
702 (error "No org-babel-load-session function for %s!" lang
))
703 (pop-to-buffer (funcall cmd session body params
))
707 (defun org-babel-initiate-session (&optional arg info
)
708 "Initiate session for current code block.
709 If called with a prefix argument then resolve any variable
710 references in the header arguments and assign these variables in
711 the session. Copy the body of the code block to the kill ring."
713 (let* ((info (or info
(org-babel-get-src-block-info (not arg
))))
716 (params (nth 2 info
))
717 (session (cdr (assoc :session params
)))
718 (dir (cdr (assoc :dir params
)))
720 (or (and dir
(file-name-as-directory dir
)) default-directory
))
721 (init-cmd (intern (format "org-babel-%s-initiate-session" lang
)))
722 (prep-cmd (intern (concat "org-babel-prep-session:" lang
))))
723 (if (and (stringp session
) (string= session
"none"))
724 (error "This block is not using a session!"))
725 (unless (fboundp init-cmd
)
726 (error "No org-babel-initiate-session function for %s!" lang
))
727 (with-temp-buffer (insert (org-babel-trim body
))
728 (copy-region-as-kill (point-min) (point-max)))
730 (unless (fboundp prep-cmd
)
731 (error "No org-babel-prep-session function for %s!" lang
))
732 (funcall prep-cmd session params
))
733 (funcall init-cmd session params
)))
736 (defun org-babel-switch-to-session (&optional arg info
)
737 "Switch to the session of the current code block.
738 Uses `org-babel-initiate-session' to start the session. If called
739 with a prefix argument then this is passed on to
740 `org-babel-initiate-session'."
742 (pop-to-buffer (org-babel-initiate-session arg info
))
745 (defalias 'org-babel-pop-to-session
'org-babel-switch-to-session
)
748 (defun org-babel-switch-to-session-with-code (&optional arg info
)
749 "Switch to code buffer and display session."
753 (let ((other-window-buffer (window-buffer (next-window))))
754 (set-window-buffer (next-window) (current-buffer))
755 (set-window-buffer (selected-window) other-window-buffer
))
757 (let ((info (org-babel-get-src-block-info))
758 (org-src-window-setup 'reorganize-frame
))
760 (org-babel-switch-to-session arg info
))
764 (defmacro org-babel-do-in-edit-buffer
(&rest body
)
765 "Evaluate BODY in edit buffer if there is a code block at point.
766 Return t if a code block was found at point, nil otherwise."
767 `(let ((org-src-window-setup 'switch-invisibly
))
768 (when (and (org-babel-where-is-src-block-head)
769 (org-edit-src-code nil nil nil
))
770 (unwind-protect (progn ,@body
)
771 (if (org-bound-and-true-p org-edit-src-from-org-mode
)
772 (org-edit-src-exit)))
774 (def-edebug-spec org-babel-do-in-edit-buffer
(body))
776 (defun org-babel-do-key-sequence-in-edit-buffer (key)
777 "Read key sequence and execute the command in edit buffer.
778 Enter a key sequence to be executed in the language major-mode
779 edit buffer. For example, TAB will alter the contents of the
780 Org-mode code block according to the effect of TAB in the
781 language major-mode buffer. For languages that support
782 interactive sessions, this can be used to send code from the Org
783 buffer to the session for evaluation using the native major-mode
784 evaluation mechanisms."
785 (interactive "kEnter key-sequence to execute in edit buffer: ")
786 (org-babel-do-in-edit-buffer
788 (key-binding (or key
(read-key-sequence nil
))))))
790 (defvar org-bracket-link-regexp
)
792 (defun org-babel-open-src-block-result (&optional re-run
)
793 "If `point' is on a src block then open the results of the
794 source code block, otherwise return nil. With optional prefix
795 argument RE-RUN the source-code block is evaluated even if
796 results already exist."
798 (let ((info (org-babel-get-src-block-info)))
801 ;; go to the results, if there aren't any then run the block
802 (goto-char (or (and (not re-run
) (org-babel-where-is-src-block-result))
803 (progn (org-babel-execute-src-block)
804 (org-babel-where-is-src-block-result))))
806 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
808 (if (looking-at org-bracket-link-regexp
)
811 (let ((r (org-babel-format-result
812 (org-babel-read-result) (cdr (assoc :sep
(nth 2 info
))))))
813 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
814 (delete-region (point-min) (point-max))
819 (defmacro org-babel-map-src-blocks
(file &rest body
)
820 "Evaluate BODY forms on each source-block in FILE.
821 If FILE is nil evaluate BODY forms on source blocks in current
822 buffer. During evaluation of BODY the following local variables
823 are set relative to the currently matched code block.
825 full-block ------- string holding the entirety of the code block
826 beg-block -------- point at the beginning of the code block
827 end-block -------- point at the end of the matched code block
828 lang ------------- string holding the language of the code block
829 beg-lang --------- point at the beginning of the lang
830 end-lang --------- point at the end of the lang
831 switches --------- string holding the switches
832 beg-switches ----- point at the beginning of the switches
833 end-switches ----- point at the end of the switches
834 header-args ------ string holding the header-args
835 beg-header-args -- point at the beginning of the header-args
836 end-header-args -- point at the end of the header-args
837 body ------------- string holding the body of the code block
838 beg-body --------- point at the beginning of the body
839 end-body --------- point at the end of the body"
841 (let ((tempvar (make-symbol "file")))
842 `(let* ((,tempvar
,file
)
843 (visited-p (or (null ,tempvar
)
844 (get-file-buffer (expand-file-name ,tempvar
))))
845 (point (point)) to-be-removed
)
846 (save-window-excursion
847 (when ,tempvar
(find-file ,tempvar
))
848 (setq to-be-removed
(current-buffer))
849 (goto-char (point-min))
850 (while (re-search-forward org-babel-src-block-regexp nil t
)
851 (goto-char (match-beginning 0))
852 (let ((full-block (match-string 0))
853 (beg-block (match-beginning 0))
854 (end-block (match-end 0))
855 (lang (match-string 2))
856 (beg-lang (match-beginning 2))
857 (end-lang (match-end 2))
858 (switches (match-string 3))
859 (beg-switches (match-beginning 3))
860 (end-switches (match-end 3))
861 (header-args (match-string 4))
862 (beg-header-args (match-beginning 4))
863 (end-header-args (match-end 4))
864 (body (match-string 5))
865 (beg-body (match-beginning 5))
866 (end-body (match-end 5)))
868 (goto-char end-block
))))
869 (unless visited-p
(kill-buffer to-be-removed
))
871 (def-edebug-spec org-babel-map-src-blocks
(form body
))
874 (defmacro org-babel-map-inline-src-blocks
(file &rest body
)
875 "Evaluate BODY forms on each inline source-block in FILE.
876 If FILE is nil evaluate BODY forms on source blocks in current
879 (let ((tempvar (make-symbol "file")))
880 `(let* ((,tempvar
,file
)
881 (visited-p (or (null ,tempvar
)
882 (get-file-buffer (expand-file-name ,tempvar
))))
883 (point (point)) to-be-removed
)
884 (save-window-excursion
885 (when ,tempvar
(find-file ,tempvar
))
886 (setq to-be-removed
(current-buffer))
887 (goto-char (point-min))
888 (while (re-search-forward org-babel-inline-src-block-regexp nil t
)
889 (goto-char (match-beginning 1))
890 (save-match-data ,@body
)
891 (goto-char (match-end 0))))
892 (unless visited-p
(kill-buffer to-be-removed
))
894 (def-edebug-spec org-babel-map-inline-src-blocks
(form body
))
896 (defvar org-babel-lob-one-liner-regexp
)
898 (defmacro org-babel-map-call-lines
(file &rest body
)
899 "Evaluate BODY forms on each call line in FILE.
900 If FILE is nil evaluate BODY forms on source blocks in current
903 (let ((tempvar (make-symbol "file")))
904 `(let* ((,tempvar
,file
)
905 (visited-p (or (null ,tempvar
)
906 (get-file-buffer (expand-file-name ,tempvar
))))
907 (point (point)) to-be-removed
)
908 (save-window-excursion
909 (when ,tempvar
(find-file ,tempvar
))
910 (setq to-be-removed
(current-buffer))
911 (goto-char (point-min))
912 (while (re-search-forward org-babel-lob-one-liner-regexp nil t
)
913 (goto-char (match-beginning 1))
914 (save-match-data ,@body
)
915 (goto-char (match-end 0))))
916 (unless visited-p
(kill-buffer to-be-removed
))
918 (def-edebug-spec org-babel-map-call-lines
(form body
))
921 (defmacro org-babel-map-executables
(file &rest body
)
923 (let ((tempvar (make-symbol "file"))
924 (rx (make-symbol "rx")))
925 `(let* ((,tempvar
,file
)
926 (,rx
(concat "\\(" org-babel-src-block-regexp
927 "\\|" org-babel-inline-src-block-regexp
928 "\\|" org-babel-lob-one-liner-regexp
"\\)"))
929 (visited-p (or (null ,tempvar
)
930 (get-file-buffer (expand-file-name ,tempvar
))))
931 (point (point)) to-be-removed
)
932 (save-window-excursion
933 (when ,tempvar
(find-file ,tempvar
))
934 (setq to-be-removed
(current-buffer))
935 (goto-char (point-min))
936 (while (re-search-forward ,rx nil t
)
937 (goto-char (match-beginning 1))
938 (when (looking-at org-babel-inline-src-block-regexp
)(forward-char 1))
939 (save-match-data ,@body
)
940 (goto-char (match-end 0))))
941 (unless visited-p
(kill-buffer to-be-removed
))
943 (def-edebug-spec org-babel-map-executables
(form body
))
946 (defun org-babel-execute-buffer (&optional arg
)
947 "Execute source code blocks in a buffer.
948 Call `org-babel-execute-src-block' on every source block in
951 (org-babel-eval-wipe-error-buffer)
952 (org-save-outline-visibility t
953 (org-babel-map-executables nil
954 (if (looking-at org-babel-lob-one-liner-regexp
)
955 (org-babel-lob-execute-maybe)
956 (org-babel-execute-src-block arg
)))))
959 (defun org-babel-execute-subtree (&optional arg
)
960 "Execute source code blocks in a subtree.
961 Call `org-babel-execute-src-block' on every source block in
962 the current subtree."
966 (org-narrow-to-subtree)
967 (org-babel-execute-buffer arg
)
971 (defun org-babel-sha1-hash (&optional info
)
972 "Generate an sha1 hash based on the value of info."
974 (let ((print-level nil
)
975 (info (or info
(org-babel-get-src-block-info))))
977 (sort (copy-sequence (nth 2 info
))
978 (lambda (a b
) (string< (car a
) (car b
)))))
980 (dolist (p '("replace" "silent" "append" "prepend"))
981 (setq lst
(remove p lst
)))
984 (let ((v (if (and (listp (cdr arg
)) (null (cddr arg
)))
985 (copy-sequence (cdr arg
))
987 (when (and v
(not (and (sequencep v
)
991 ((and (listp v
) ; lists are sorted
992 (member (car arg
) '(:result-params
)))
993 (sort (rm v
) #'string
<))
994 ((and (stringp v
) ; strings are sorted
995 (member (car arg
) '(:results
:exports
)))
996 (mapconcat #'identity
(sort (rm (split-string v
))
1000 (when (org-called-interactively-p 'interactive
) (message hash
)) hash
)
1001 (let ((it (format "%s-%s"
1004 (delq nil
(mapcar (lambda (arg)
1005 (let ((normalized (norm arg
)))
1007 (format "%S" normalized
))))
1012 (defun org-babel-current-result-hash ()
1013 "Return the in-buffer hash associated with INFO."
1014 (org-babel-where-is-src-block-result)
1015 (org-babel-clean-text-properties (match-string 3)))
1017 (defun org-babel-hide-hash ()
1018 "Hide the hash in the current results line.
1019 Only the initial `org-babel-hash-show' characters of the hash
1020 will remain visible."
1021 (add-to-invisibility-spec '(org-babel-hide-hash . t
))
1023 (when (and (re-search-forward org-babel-result-regexp nil t
)
1025 (let* ((start (match-beginning 3))
1026 (hide-start (+ org-babel-hash-show start
))
1028 (hash (match-string 3))
1030 (setq ov1
(make-overlay start hide-start
))
1031 (setq ov2
(make-overlay hide-start end
))
1032 (overlay-put ov2
'invisible
'org-babel-hide-hash
)
1033 (overlay-put ov1
'babel-hash hash
)))))
1035 (defun org-babel-hide-all-hashes ()
1036 "Hide the hash in the current buffer.
1037 Only the initial `org-babel-hash-show' characters of each hash
1038 will remain visible. This function should be called as part of
1039 the `org-mode-hook'."
1041 (while (re-search-forward org-babel-result-regexp nil t
)
1042 (goto-char (match-beginning 0))
1043 (org-babel-hide-hash)
1044 (goto-char (match-end 0)))))
1045 (add-hook 'org-mode-hook
'org-babel-hide-all-hashes
)
1047 (defun org-babel-hash-at-point (&optional point
)
1048 "Return the value of the hash at POINT.
1049 The hash is also added as the last element of the kill ring.
1050 This can be called with C-c C-c."
1052 (let ((hash (car (delq nil
(mapcar
1053 (lambda (ol) (overlay-get ol
'babel-hash
))
1054 (overlays-at (or point
(point))))))))
1055 (when hash
(kill-new hash
) (message hash
))))
1056 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-hash-at-point
)
1058 (defun org-babel-result-hide-spec ()
1059 "Hide portions of results lines.
1060 Add `org-babel-hide-result' as an invisibility spec for hiding
1061 portions of results lines."
1062 (add-to-invisibility-spec '(org-babel-hide-result . t
)))
1063 (add-hook 'org-mode-hook
'org-babel-result-hide-spec
)
1065 (defvar org-babel-hide-result-overlays nil
1066 "Overlays hiding results.")
1068 (defun org-babel-result-hide-all ()
1069 "Fold all results in the current buffer."
1071 (org-babel-show-result-all)
1073 (while (re-search-forward org-babel-result-regexp nil t
)
1074 (save-excursion (goto-char (match-beginning 0))
1075 (org-babel-hide-result-toggle-maybe)))))
1077 (defun org-babel-show-result-all ()
1078 "Unfold all results in the current buffer."
1079 (mapc 'delete-overlay org-babel-hide-result-overlays
)
1080 (setq org-babel-hide-result-overlays nil
))
1083 (defun org-babel-hide-result-toggle-maybe ()
1084 "Toggle visibility of result at point."
1086 (let ((case-fold-search t
))
1088 (beginning-of-line 1)
1089 (looking-at org-babel-result-regexp
))
1090 (progn (org-babel-hide-result-toggle)
1091 t
) ;; to signal that we took action
1092 nil
))) ;; to signal that we did not
1094 (defun org-babel-hide-result-toggle (&optional force
)
1095 "Toggle the visibility of the current result."
1099 (if (re-search-forward org-babel-result-regexp nil t
)
1100 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
1102 (while (looking-at org-babel-multi-line-header-regexp
)
1104 (goto-char (- (org-babel-result-end) 1)) (point)))
1106 (if (memq t
(mapcar (lambda (overlay)
1107 (eq (overlay-get overlay
'invisible
)
1108 'org-babel-hide-result
))
1109 (overlays-at start
)))
1110 (if (or (not force
) (eq force
'off
))
1112 (when (member ov org-babel-hide-result-overlays
)
1113 (setq org-babel-hide-result-overlays
1114 (delq ov org-babel-hide-result-overlays
)))
1115 (when (eq (overlay-get ov
'invisible
)
1116 'org-babel-hide-result
)
1117 (delete-overlay ov
)))
1118 (overlays-at start
)))
1119 (setq ov
(make-overlay start end
))
1120 (overlay-put ov
'invisible
'org-babel-hide-result
)
1121 ;; make the block accessible to isearch
1123 ov
'isearch-open-invisible
1125 (when (member ov org-babel-hide-result-overlays
)
1126 (setq org-babel-hide-result-overlays
1127 (delq ov org-babel-hide-result-overlays
)))
1128 (when (eq (overlay-get ov
'invisible
)
1129 'org-babel-hide-result
)
1130 (delete-overlay ov
))))
1131 (push ov org-babel-hide-result-overlays
)))
1132 (error "Not looking at a result line"))))
1134 ;; org-tab-after-check-for-cycling-hook
1135 (add-hook 'org-tab-first-hook
'org-babel-hide-result-toggle-maybe
)
1136 ;; Remove overlays when changing major mode
1137 (add-hook 'org-mode-hook
1138 (lambda () (org-add-hook 'change-major-mode-hook
1139 'org-babel-show-result-all
'append
'local
)))
1141 (defvar org-file-properties
)
1142 (defun org-babel-params-from-properties (&optional lang
)
1143 "Retrieve parameters specified as properties.
1144 Return an association list of any source block params which
1145 may be specified in the properties of the current outline entry."
1148 (org-babel-parse-multiple-vars
1151 (lambda (header-arg)
1152 (and (setq val
(org-entry-get (point) header-arg t
))
1153 (cons (intern (concat ":" header-arg
))
1154 (org-babel-read val
))))
1158 org-babel-header-arg-names
1160 (setq sym
(intern (concat "org-babel-header-arg-names:"
1162 (and (boundp sym
) (eval sym
)))))))))))
1164 (defvar org-src-preserve-indentation
)
1165 (defun org-babel-parse-src-block-match ()
1166 "Parse the results from a match of the `org-babel-src-block-regexp'."
1167 (let* ((block-indentation (length (match-string 1)))
1168 (lang (org-babel-clean-text-properties (match-string 2)))
1169 (lang-headers (intern (concat "org-babel-default-header-args:" lang
)))
1170 (switches (match-string 3))
1171 (body (org-babel-clean-text-properties
1172 (let* ((body (match-string 5))
1173 (sub-length (- (length body
) 1)))
1174 (if (and (> sub-length
0)
1175 (string= "\n" (substring body sub-length
)))
1176 (substring body
0 sub-length
)
1178 (preserve-indentation (or org-src-preserve-indentation
1179 (string-match "-i\\>" switches
))))
1181 ;; get block body less properties, protective commas, and indentation
1184 (insert (org-babel-strip-protective-commas body lang
))
1185 (unless preserve-indentation
(org-do-remove-indentation))
1187 (org-babel-merge-params
1188 org-babel-default-header-args
1189 (org-babel-params-from-properties lang
)
1190 (if (boundp lang-headers
) (eval lang-headers
) nil
)
1191 (org-babel-parse-header-arguments
1192 (org-babel-clean-text-properties (or (match-string 4) ""))))
1194 block-indentation
)))
1196 (defun org-babel-parse-inline-src-block-match ()
1197 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
1198 (let* ((lang (org-babel-clean-text-properties (match-string 2)))
1199 (lang-headers (intern (concat "org-babel-default-header-args:" lang
))))
1201 (org-babel-strip-protective-commas
1202 (org-babel-clean-text-properties (match-string 5)) lang
)
1203 (org-babel-merge-params
1204 org-babel-default-inline-header-args
1205 (org-babel-params-from-properties lang
)
1206 (if (boundp lang-headers
) (eval lang-headers
) nil
)
1207 (org-babel-parse-header-arguments
1208 (org-babel-clean-text-properties (or (match-string 4) "")))))))
1210 (defun org-babel-balanced-split (string alts
)
1211 "Split STRING on instances of ALTS.
1212 ALTS is a cons of two character options where each option may be
1213 either the numeric code of a single character or a list of
1214 character alternatives. For example to split on balanced
1215 instances of \"[ \t]:\" set ALTS to '((32 9) . 58)."
1216 (flet ((matches (ch spec
) (if (listp spec
) (member ch spec
) (equal spec ch
)))
1219 (and (matches ch
(cdr alts
))
1220 (matches last
(car alts
)))
1221 (matches ch alts
))))
1222 (let ((balance 0) (quote nil
) (partial nil
) (lst nil
) (last 0))
1223 (mapc (lambda (ch) ; split on [], (), "" balanced instances of [ \t]:
1224 (setq balance
(+ balance
1225 (cond ((or (equal 91 ch
) (equal 40 ch
)) 1)
1226 ((or (equal 93 ch
) (equal 41 ch
)) -
1)
1228 (when (and (equal 34 ch
) (not (equal 92 last
)))
1229 (setq quote
(not quote
)))
1230 (setq partial
(cons ch partial
))
1231 (when (and (= balance
0) (not quote
) (matched ch last
))
1232 (setq lst
(cons (apply #'string
(nreverse
1239 (string-to-list string
))
1240 (nreverse (cons (apply #'string
(nreverse partial
)) lst
)))))
1242 (defun org-babel-join-splits-near-ch (ch list
)
1243 "Join splits where \"=\" is on either end of the split."
1244 (flet ((last= (str) (= ch
(aref str
(1- (length str
)))))
1245 (first= (str) (= ch
(aref str
0))))
1247 (org-reduce (lambda (acc el
)
1248 (let ((head (car acc
)))
1249 (if (and head
(or (last= head
) (first= el
)))
1250 (cons (concat head el
) (cdr acc
))
1252 list
:initial-value nil
))))
1254 (defun org-babel-parse-header-arguments (arg-string)
1255 "Parse a string of header arguments returning an alist."
1256 (when (> (length arg-string
) 0)
1257 (org-babel-parse-multiple-vars
1262 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1264 (cons (intern (match-string 1 arg
))
1265 (org-babel-read (org-babel-chomp (match-string 2 arg
))))
1266 (cons (intern (org-babel-chomp arg
)) nil
)))
1268 (cons (car raw
) (mapcar (lambda (r) (concat ":" r
)) (cdr raw
))))
1269 (org-babel-balanced-split arg-string
'((32 9) .
58))))))))
1271 (defun org-babel-parse-multiple-vars (header-arguments)
1272 "Expand multiple variable assignments behind a single :var keyword.
1274 This allows expression of multiple variables with one :var as
1277 #+PROPERTY: var foo=1, bar=2"
1279 (mapc (lambda (pair)
1280 (if (eq (car pair
) :var
)
1281 (mapcar (lambda (v) (push (cons :var
(org-babel-trim v
)) results
))
1282 (org-babel-join-splits-near-ch
1283 61 (org-babel-balanced-split (cdr pair
) 32)))
1284 (push pair results
)))
1286 (nreverse results
)))
1288 (defun org-babel-process-params (params)
1289 "Expand variables in PARAMS and add summary parameters."
1290 (let* ((processed-vars (mapcar (lambda (el)
1291 (if (consp (cdr el
))
1293 (org-babel-ref-parse (cdr el
))))
1294 (org-babel-get-header params
:var
)))
1295 (vars-and-names (if (and (assoc :colname-names params
)
1296 (assoc :rowname-names params
))
1297 (list processed-vars
)
1298 (org-babel-disassemble-tables
1300 (cdr (assoc :hlines params
))
1301 (cdr (assoc :colnames params
))
1302 (cdr (assoc :rownames params
)))))
1303 (raw-result (or (cdr (assoc :results params
)) ""))
1304 (result-params (append
1305 (split-string (if (stringp raw-result
)
1308 (cdr (assoc :result-params params
)))))
1310 (mapcar (lambda (var) (cons :var var
)) (car vars-and-names
))
1312 (cons :colname-names
(or (cdr (assoc :colname-names params
))
1313 (cadr vars-and-names
)))
1314 (cons :rowname-names
(or (cdr (assoc :rowname-names params
))
1315 (caddr vars-and-names
)))
1316 (cons :result-params result-params
)
1317 (cons :result-type
(cond ((member "output" result-params
) 'output
)
1318 ((member "value" result-params
) 'value
)
1320 (org-babel-get-header params
:var
'other
))))
1322 ;; row and column names
1323 (defun org-babel-del-hlines (table)
1324 "Remove all 'hlines from TABLE."
1325 (remove 'hline table
))
1327 (defun org-babel-get-colnames (table)
1328 "Return the column names of TABLE.
1329 Return a cons cell, the `car' of which contains the TABLE less
1330 colnames, and the `cdr' of which contains a list of the column
1332 (if (equal 'hline
(nth 1 table
))
1333 (cons (cddr table
) (car table
))
1334 (cons (cdr table
) (car table
))))
1336 (defun org-babel-get-rownames (table)
1337 "Return the row names of TABLE.
1338 Return a cons cell, the `car' of which contains the TABLE less
1339 colnames, and the `cdr' of which contains a list of the column
1340 names. Note: this function removes any hlines in TABLE."
1341 (flet ((trans (table) (apply #'mapcar
* #'list table
)))
1342 (let* ((width (apply 'max
1343 (mapcar (lambda (el) (if (listp el
) (length el
) 0)) table
)))
1344 (table (trans (mapcar (lambda (row)
1345 (if (not (equal row
'hline
))
1349 (setq row
(cons 'hline row
)))
1352 (cons (mapcar (lambda (row) (if (equal (car row
) 'hline
) 'hline row
))
1353 (trans (cdr table
)))
1354 (remove 'hline
(car table
))))))
1356 (defun org-babel-put-colnames (table colnames
)
1357 "Add COLNAMES to TABLE if they exist."
1358 (if colnames
(apply 'list colnames
'hline table
) table
))
1360 (defun org-babel-put-rownames (table rownames
)
1361 "Add ROWNAMES to TABLE if they exist."
1363 (mapcar (lambda (row)
1365 (cons (or (pop rownames
) "") row
)
1369 (defun org-babel-pick-name (names selector
)
1370 "Select one out of an alist of row or column names.
1371 SELECTOR can be either a list of names in which case those names
1372 will be returned directly, or an index into the list NAMES in
1373 which case the indexed names will be return."
1374 (if (listp selector
)
1377 (if (and selector
(symbolp selector
) (not (equal t selector
)))
1378 (cdr (assoc selector names
))
1379 (if (integerp selector
)
1380 (nth (- selector
1) names
)
1381 (cdr (car (last names
))))))))
1383 (defun org-babel-disassemble-tables (vars hlines colnames rownames
)
1384 "Parse tables for further processing.
1385 Process the variables in VARS according to the HLINES,
1386 ROWNAMES and COLNAMES header arguments. Return a list consisting
1387 of the vars, cnames and rnames."
1388 (let (cnames rnames
)
1392 (when (listp (cdr var
))
1393 (when (and (not (equal colnames
"no"))
1394 (or colnames
(and (equal (nth 1 (cdr var
)) 'hline
)
1395 (not (member 'hline
(cddr (cdr var
)))))))
1396 (let ((both (org-babel-get-colnames (cdr var
))))
1397 (setq cnames
(cons (cons (car var
) (cdr both
))
1399 (setq var
(cons (car var
) (car both
)))))
1400 (when (and rownames
(not (equal rownames
"no")))
1401 (let ((both (org-babel-get-rownames (cdr var
))))
1402 (setq rnames
(cons (cons (car var
) (cdr both
))
1404 (setq var
(cons (car var
) (car both
)))))
1405 (when (and hlines
(not (equal hlines
"yes")))
1406 (setq var
(cons (car var
) (org-babel-del-hlines (cdr var
))))))
1409 (reverse cnames
) (reverse rnames
))))
1411 (defun org-babel-reassemble-table (table colnames rownames
)
1412 "Add column and row names to a table.
1413 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1414 to the table for reinsertion to org-mode."
1417 (if (and colnames
(listp (car table
)) (= (length (car table
))
1419 (org-babel-put-colnames table colnames
) table
))
1420 (if (and rownames
(= (length table
) (length rownames
)))
1421 (org-babel-put-rownames table rownames
) table
))
1424 (defun org-babel-where-is-src-block-head ()
1425 "Find where the current source block begins.
1426 Return the point at the beginning of the current source
1427 block. Specifically at the beginning of the #+BEGIN_SRC line.
1428 If the point is not on a source block then return nil."
1429 (let ((initial (point)) top bottom
)
1431 (save-excursion ;; on a source name line or a #+header line
1432 (beginning-of-line 1)
1433 (and (or (looking-at org-babel-src-name-regexp
)
1434 (looking-at org-babel-multi-line-header-regexp
))
1436 (while (and (forward-line 1)
1437 (looking-at org-babel-multi-line-header-regexp
)))
1438 (looking-at org-babel-src-block-regexp
))
1440 (save-excursion ;; on a #+begin_src line
1441 (beginning-of-line 1)
1442 (and (looking-at org-babel-src-block-regexp
)
1444 (save-excursion ;; inside a src block
1446 (re-search-backward "^[ \t]*#\\+begin_src" nil t
) (setq top
(point))
1447 (re-search-forward "^[ \t]*#\\+end_src" nil t
) (setq bottom
(point))
1448 (< top initial
) (< initial bottom
)
1449 (progn (goto-char top
) (beginning-of-line 1)
1450 (looking-at org-babel-src-block-regexp
))
1454 (defun org-babel-goto-src-block-head ()
1455 "Go to the beginning of the current code block."
1458 (if head
(goto-char head
) (error "not currently in a code block")))
1459 (org-babel-where-is-src-block-head)))
1462 (defun org-babel-goto-named-src-block (name)
1463 "Go to a named source-code block."
1465 (let ((completion-ignore-case t
)
1466 (under-point (thing-at-point 'line
)))
1467 (list (org-icompleting-read
1468 "source-block name: " (org-babel-src-block-names) nil t
1471 ((string-match (org-babel-noweb-wrap) under-point
)
1472 (let ((block-name (match-string 1 under-point
)))
1473 (string-match "[^(]*" block-name
)
1474 (match-string 0 block-name
)))
1476 ((string-match org-babel-lob-one-liner-regexp under-point
)
1477 (let ((source-info (car (org-babel-lob-get-info))))
1478 (if (string-match "^\\([^\\[]+?\\)\\(\\[.*\\]\\)?(" source-info
)
1479 (let ((source-name (match-string 1 source-info
)))
1482 ((string-match (concat "#\\+" org-babel-results-keyword
1483 "\\:\s+\\([^\\(]*\\)") under-point
)
1484 (match-string 1 under-point
))
1486 ((and (thing-at-point 'symbol
))
1487 (org-babel-find-named-block (thing-at-point 'symbol
))
1488 (thing-at-point 'symbol
))
1490 (let ((point (org-babel-find-named-block name
)))
1492 ;; taken from `org-open-at-point'
1493 (progn (org-mark-ring-push) (goto-char point
) (org-show-context))
1494 (message "source-code block '%s' not found in this buffer" name
))))
1496 (defun org-babel-find-named-block (name)
1497 "Find a named source-code block.
1498 Return the location of the source block identified by source
1499 NAME, or nil if no such block exists. Set match data according to
1500 org-babel-named-src-block-regexp."
1502 (let ((case-fold-search t
)
1503 (regexp (org-babel-named-src-block-regexp-for-name name
)) msg
)
1504 (goto-char (point-min))
1505 (when (or (re-search-forward regexp nil t
)
1506 (re-search-backward regexp nil t
))
1507 (match-beginning 0)))))
1509 (defun org-babel-src-block-names (&optional file
)
1510 "Returns the names of source blocks in FILE or the current buffer."
1512 (when file
(find-file file
)) (goto-char (point-min))
1514 (while (re-search-forward org-babel-src-name-w-name-regexp nil t
)
1515 (setq names
(cons (match-string 3) names
)))
1519 (defun org-babel-goto-named-result (name)
1520 "Go to a named result."
1522 (let ((completion-ignore-case t
))
1523 (list (org-icompleting-read "source-block name: "
1524 (org-babel-result-names) nil t
))))
1525 (let ((point (org-babel-find-named-result name
)))
1527 ;; taken from `org-open-at-point'
1528 (progn (goto-char point
) (org-show-context))
1529 (message "result '%s' not found in this buffer" name
))))
1531 (defun org-babel-find-named-result (name &optional point
)
1532 "Find a named result.
1533 Return the location of the result named NAME in the current
1534 buffer or nil if no such result exists."
1536 (goto-char (or point
(point-min)))
1537 (catch 'is-a-code-block
1538 (when (re-search-forward
1539 (concat org-babel-result-regexp
1540 "[ \t]" (regexp-quote name
) "[ \t\n\f\v\r]+") nil t
)
1541 (when (and (string= "name" (downcase (match-string 1)))
1542 (or (beginning-of-line 1)
1543 (looking-at org-babel-src-block-regexp
)
1544 (looking-at org-babel-multi-line-header-regexp
)))
1545 (throw 'is-a-code-block
(org-babel-find-named-result name
(point))))
1546 (beginning-of-line 0) (point)))))
1548 (defun org-babel-result-names (&optional file
)
1549 "Returns the names of results in FILE or the current buffer."
1551 (when file
(find-file file
)) (goto-char (point-min))
1553 (while (re-search-forward org-babel-result-w-name-regexp nil t
)
1554 (setq names
(cons (match-string 4) names
)))
1558 (defun org-babel-next-src-block (&optional arg
)
1559 "Jump to the next source block.
1560 With optional prefix argument ARG, jump forward ARG many source blocks."
1562 (when (looking-at org-babel-src-block-regexp
) (forward-char 1))
1564 (re-search-forward org-babel-src-block-regexp nil nil
(or arg
1))
1565 (error (error "No further code blocks")))
1566 (goto-char (match-beginning 0)) (org-show-context))
1569 (defun org-babel-previous-src-block (&optional arg
)
1570 "Jump to the previous source block.
1571 With optional prefix argument ARG, jump backward ARG many source blocks."
1574 (re-search-backward org-babel-src-block-regexp nil nil
(or arg
1))
1575 (error (error "No previous code blocks")))
1576 (goto-char (match-beginning 0)) (org-show-context))
1578 (defvar org-babel-load-languages
)
1581 (defun org-babel-mark-block ()
1582 "Mark current src block"
1588 (looking-at org-babel-src-block-regexp
))
1589 (push-mark (match-end 5) nil t
)
1590 (goto-char (match-beginning 5))))
1591 (org-babel-where-is-src-block-head)))
1593 (defun org-babel-demarcate-block (&optional arg
)
1594 "Wrap or split the code in the region or on the point.
1595 When called from inside of a code block the current block is
1596 split. When called from outside of a code block a new code block
1597 is created. In both cases if the region is demarcated and if the
1598 region is not active then the point is demarcated."
1600 (let ((info (org-babel-get-src-block-info 'light
))
1601 (headers (progn (org-babel-where-is-src-block-head)
1603 (stars (concat (make-string (or (org-current-level) 1) ?
*) " ")))
1609 (let ((lang (nth 0 info
))
1610 (indent (make-string (nth 5 info
) ?
)))
1611 (when (string-match "^[[:space:]]*$"
1612 (buffer-substring (point-at-bol)
1614 (delete-region (point-at-bol) (point-at-eol)))
1616 (if (looking-at "^") "" "\n")
1617 indent
"#+end_src\n"
1618 (if arg stars indent
) "\n"
1619 indent
"#+begin_src " lang
1620 (if (> (length headers
) 1)
1621 (concat " " headers
) headers
)
1622 (if (looking-at "[\n\r]")
1624 (concat "\n" (make-string (current-column) ?
)))))))
1625 (move-end-of-line 2))
1626 (sort (if (region-active-p) (list (mark) (point)) (list (point))) #'>))
1627 (let ((start (point))
1628 (lang (org-icompleting-read "Lang: "
1629 (mapcar (lambda (el) (symbol-name (car el
)))
1630 org-babel-load-languages
)))
1631 (body (delete-and-extract-region
1632 (if (region-active-p) (mark) (point)) (point))))
1633 (insert (concat (if (looking-at "^") "" "\n")
1634 (if arg
(concat stars
"\n") "")
1635 "#+begin_src " lang
"\n"
1637 (if (or (= (length body
) 0)
1638 (string-match "[\r\n]$" body
)) "" "\n")
1640 (goto-char start
) (move-end-of-line 1)))))
1642 (defvar org-babel-lob-one-liner-regexp
)
1643 (defun org-babel-where-is-src-block-result (&optional insert info hash indent
)
1644 "Find where the current source block results begin.
1645 Return the point at the beginning of the result of the current
1646 source block. Specifically at the beginning of the results line.
1647 If no result exists for this block then create a results line
1648 following the source block."
1650 (let* ((on-lob-line (save-excursion
1651 (beginning-of-line 1)
1652 (looking-at org-babel-lob-one-liner-regexp
)))
1653 (inlinep (when (org-babel-get-inline-src-block-matches)
1655 (name (if on-lob-line
1656 (mapconcat #'identity
(butlast (org-babel-lob-get-info)) "")
1657 (nth 4 (or info
(org-babel-get-src-block-info 'light
)))))
1658 (head (unless on-lob-line
(org-babel-where-is-src-block-head)))
1660 (when head
(goto-char head
))
1662 found
;; was there a result (before we potentially insert one)
1667 ;; - return t if it is found, else return nil
1668 ;; - if it does not need to be rebuilt, then don't set end
1669 ;; - if it does need to be rebuilt then do set end
1670 name
(setq beg
(org-babel-find-named-result name
))
1672 (when (and hash
(not (string= hash
(match-string 3))))
1673 (goto-char beg
) (setq end beg
) ;; beginning of result
1675 (delete-region end
(org-babel-result-end)) nil
)))
1678 ;; - return t if it is found, else return nil
1679 ;; - if it is found, and the hash doesn't match, delete and set end
1680 (or on-lob-line
(re-search-forward "^[ \t]*#\\+end_src" nil t
))
1681 (progn (end-of-line 1)
1682 (if (eobp) (insert "\n") (forward-char 1))
1685 (progn ;; unnamed results line already exists
1686 (re-search-forward "[^ \f\t\n\r\v]" nil t
)
1687 (beginning-of-line 1)
1689 (concat org-babel-result-regexp
"\n")))
1691 ;; must remove and rebuild if hash!=old-hash
1692 (if (and hash
(not (string= hash
(match-string 3))))
1696 end
(org-babel-result-end)))
1697 (setq end nil
)))))))))
1698 (if (and insert end
)
1702 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1707 (org-number-sequence 1 indent
) "")
1709 "#+" org-babel-results-keyword
1710 (when hash
(concat "["hash
"]"))
1712 (when name
(concat " " name
)) "\n"))
1713 (unless beg
(insert "\n") (backward-char))
1714 (beginning-of-line 0)
1715 (if hash
(org-babel-hide-hash))
1719 (defvar org-block-regexp
)
1720 (defun org-babel-read-result ()
1721 "Read the result at `point' into emacs-lisp."
1722 (let ((case-fold-search t
) result-string
)
1724 ((org-at-table-p) (org-babel-read-table))
1725 ((org-at-item-p) (org-babel-read-list))
1726 ((looking-at org-bracket-link-regexp
) (org-babel-read-link))
1727 ((looking-at org-block-regexp
) (org-babel-trim (match-string 4)))
1728 ((looking-at "^[ \t]*: ")
1731 (mapconcat (lambda (line)
1732 (if (and (> (length line
) 1)
1733 (string-match "^[ \t]*: \\(.+\\)" line
))
1734 (match-string 1 line
)
1738 (point) (org-babel-result-end)) "[\r\n]+")
1740 (or (org-babel-number-p result-string
) result-string
))
1741 ((looking-at org-babel-result-regexp
)
1742 (save-excursion (forward-line 1) (org-babel-read-result))))))
1744 (defun org-babel-read-table ()
1745 "Read the table at `point' into emacs-lisp."
1746 (mapcar (lambda (row)
1747 (if (and (symbolp row
) (equal row
'hline
)) row
1748 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
)) row
)))
1749 (org-table-to-lisp)))
1751 (defun org-babel-read-list ()
1752 "Read the list at `point' into emacs-lisp."
1753 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
))
1754 (mapcar #'cadr
(cdr (org-list-parse-list)))))
1756 (defvar org-link-types-re
)
1757 (defun org-babel-read-link ()
1758 "Read the link at `point' into emacs-lisp.
1759 If the path of the link is a file path it is expanded using
1760 `expand-file-name'."
1761 (let* ((case-fold-search t
)
1762 (raw (and (looking-at org-bracket-link-regexp
)
1763 (org-babel-clean-text-properties (match-string 1))))
1764 (type (and (string-match org-link-types-re raw
)
1765 (match-string 1 raw
))))
1767 ((not type
) (expand-file-name raw
))
1768 ((string= type
"file")
1769 (and (string-match "file\\(.*\\):\\(.+\\)" raw
)
1770 (expand-file-name (match-string 2 raw
))))
1773 (defun org-babel-format-result (result &optional sep
)
1774 "Format RESULT for writing to file."
1775 (flet ((echo-res (result)
1776 (if (stringp result
) result
(format "%S" result
))))
1785 (echo-res result
))))
1787 (defun org-babel-insert-result
1788 (result &optional result-params info hash indent lang
)
1789 "Insert RESULT into the current buffer.
1790 By default RESULT is inserted after the end of the
1791 current source block. With optional argument RESULT-PARAMS
1792 controls insertion of results in the org-mode file.
1793 RESULT-PARAMS can take the following values...
1795 replace - (default option) insert results after the source block
1796 replacing any previously inserted results
1798 silent -- no results are inserted
1800 file ---- the results are interpreted as a file path, and are
1801 inserted into the buffer using the Org-mode file syntax
1803 list ---- the results are interpreted as an Org-mode list.
1805 raw ----- results are added directly to the Org-mode file. This
1806 is a good option if you code block will output org-mode
1809 wrap ---- results are added directly to the Org-mode file as with
1810 \"raw\", but are wrapped in a RESULTS drawer, allowing
1811 them to later be replaced or removed automatically.
1813 org ----- similar in effect to raw, only the results are wrapped
1814 in an org code block. Similar to the raw option, on
1815 export the results will be interpreted as org-formatted
1816 text, however by wrapping the results in an org code
1817 block they can be replaced upon re-execution of the
1820 html ---- results are added inside of a #+BEGIN_HTML block. This
1821 is a good option if you code block will output html
1824 latex --- results are added inside of a #+BEGIN_LATEX block.
1825 This is a good option if you code block will output
1826 latex formatted text.
1828 code ---- the results are extracted in the syntax of the source
1829 code of the language being evaluated and are added
1830 inside of a #+BEGIN_SRC block with the source-code
1831 language set appropriately. Note this relies on the
1832 optional LANG argument."
1833 (if (stringp result
)
1835 (setq result
(org-babel-clean-text-properties result
))
1836 (when (member "file" result-params
)
1837 (setq result
(org-babel-result-to-file
1838 result
(when (assoc :file-desc
(nth 2 info
))
1839 (or (cdr (assoc :file-desc
(nth 2 info
)))
1841 (unless (listp result
) (setq result
(format "%S" result
))))
1842 (if (and result-params
(member "silent" result-params
))
1844 (message (replace-regexp-in-string "%" "%%" (format "%S" result
)))
1849 (when (or (org-babel-get-inline-src-block-matches)
1850 (org-babel-get-lob-one-liner-matches))
1851 (goto-char (match-end 0))
1852 (insert (if (listp result
) "\n" " "))
1854 (existing-result (unless inlinep
1855 (org-babel-where-is-src-block-result
1856 t info hash indent
)))
1858 (cdr (assoc :results_switches
(nth 2 info
))))
1860 (when (and (stringp result
) ; ensure results end in a newline
1862 (> (length result
) 0)
1863 (not (or (string-equal (substring result -
1) "\n")
1864 (string-equal (substring result -
1) "\r"))))
1865 (setq result
(concat result
"\n")))
1866 (if (not existing-result
)
1867 (setq beg
(or inlinep
(point)))
1868 (goto-char existing-result
)
1870 (re-search-forward "#" nil t
)
1871 (setq indent
(- (current-column) 1)))
1875 ((member "replace" result-params
)
1876 (delete-region (point) (org-babel-result-end)))
1877 ((member "append" result-params
)
1878 (goto-char (org-babel-result-end)) (setq beg
(point-marker)))
1879 ((member "prepend" result-params
)))) ; already there
1880 (setq results-switches
1881 (if results-switches
(concat " " results-switches
) ""))
1882 (flet ((wrap (start finish
)
1883 (goto-char end
) (insert (concat finish
"\n"))
1884 (goto-char beg
) (insert (concat start
"\n"))
1885 (goto-char end
) (goto-char (point-at-eol))
1886 (setq end
(point-marker)))
1887 (proper-list-p (it) (and (listp it
) (null (cdr (last it
))))))
1888 ;; insert results based on type
1890 ;; do nothing for an empty result
1892 ;; insert a list if preferred
1893 ((member "list" result-params
)
1896 (org-list-to-generic
1899 (lambda (el) (list nil
(if (stringp el
) el
(format "%S" el
))))
1900 (if (listp result
) result
(list result
))))
1901 '(:splicep nil
:istart
"- " :iend
"\n")))
1903 ;; assume the result is a table if it's not a string
1904 ((proper-list-p result
)
1906 (insert (concat (orgtbl-to-orgtbl
1907 (if (or (eq 'hline
(car result
))
1908 (and (listp (car result
))
1909 (listp (cdr (car result
)))))
1910 result
(list result
))
1911 '(:fmt
(lambda (cell) (format "%s" cell
)))) "\n"))
1912 (goto-char beg
) (when (org-at-table-p) (org-table-align)))
1913 ((and (listp result
) (not (proper-list-p result
)))
1914 (insert (format "%s\n" result
)))
1915 ((member "file" result-params
)
1916 (when inlinep
(goto-char inlinep
))
1918 (t (goto-char beg
) (insert result
)))
1919 (when (proper-list-p result
) (goto-char (org-table-end)))
1920 (setq end
(point-marker))
1921 ;; possibly wrap result
1923 ((assoc :wrap
(nth 2 info
))
1924 (let ((name (or (cdr (assoc :wrap
(nth 2 info
))) "RESULTS")))
1925 (wrap (concat "#+BEGIN_" name
) (concat "#+END_" name
))))
1926 ((member "html" result-params
)
1927 (wrap "#+BEGIN_HTML" "#+END_HTML"))
1928 ((member "latex" result-params
)
1929 (wrap "#+BEGIN_LaTeX" "#+END_LaTeX"))
1930 ((member "code" result-params
)
1931 (wrap (format "#+BEGIN_SRC %s%s" (or lang
"none") results-switches
)
1933 ((member "org" result-params
)
1934 (wrap "#+BEGIN_ORG" "#+END_ORG"))
1935 ((member "raw" result-params
)
1936 (goto-char beg
) (if (org-at-table-p) (org-cycle)))
1937 ((member "wrap" result-params
)
1938 (wrap ":RESULTS:" ":END:"))
1939 ((and (not (proper-list-p result
))
1940 (not (member "file" result-params
)))
1941 (org-babel-examplize-region beg end results-switches
)
1942 (setq end
(point)))))
1943 ;; possibly indent the results to match the #+results line
1944 (when (and (not inlinep
) (numberp indent
) indent
(> indent
0)
1945 ;; in this case `table-align' does the work for us
1946 (not (and (listp result
)
1947 (member "append" result-params
))))
1948 (indent-rigidly beg end indent
))))
1950 (if (member "value" result-params
)
1951 (message "Code block returned no value.")
1952 (message "Code block produced no output."))
1953 (message "Code block evaluation complete."))))
1955 (defun org-babel-remove-result (&optional info
)
1956 "Remove the result of the current source block."
1958 (let ((location (org-babel-where-is-src-block-result nil info
)) start
)
1960 (setq start
(- location
1))
1962 (goto-char location
) (forward-line 1)
1963 (delete-region start
(org-babel-result-end))))))
1965 (defun org-babel-result-end ()
1966 "Return the point at the end of the current set of results"
1969 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
1970 ((org-at-item-p) (let* ((struct (org-list-struct))
1971 (prvs (org-list-prevs-alist struct
)))
1972 (org-list-get-list-end (point-at-bol) struct prvs
)))
1973 ((looking-at "^\\([ \t]*\\):RESULTS:")
1974 (progn (re-search-forward (concat "^" (match-string 1) ":END:"))
1975 (forward-char 1) (point)))
1977 (let ((case-fold-search t
))
1978 (if (looking-at (concat "[ \t]*#\\+begin_\\([^ \t\n\r]+\\)"))
1979 (progn (re-search-forward (concat "[ \t]*#\\+end_" (match-string 1))
1982 (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
1986 (defun org-babel-result-to-file (result &optional description
)
1987 "Convert RESULT into an `org-mode' link with optional DESCRIPTION.
1988 If the `default-directory' is different from the containing
1989 file's directory then expand relative links."
1990 (when (stringp result
)
1991 (format "[[file:%s]%s]"
1992 (if (and default-directory
1994 (not (string= (expand-file-name default-directory
)
1996 (file-name-directory buffer-file-name
)))))
1997 (expand-file-name result default-directory
)
1999 (if description
(concat "[" description
"]") ""))))
2001 (defun org-babel-examplize-region (beg end
&optional results-switches
)
2002 "Comment out region using the inline '==' or ': ' org example quote."
2004 (flet ((chars-between (b e
)
2005 (not (string-match "^[\\s]*$" (buffer-substring b e
)))))
2006 (if (or (chars-between (save-excursion (goto-char beg
) (point-at-bol)) beg
)
2007 (chars-between end
(save-excursion (goto-char end
) (point-at-eol))))
2010 (insert (format "=%s=" (prog1 (buffer-substring beg end
)
2011 (delete-region beg end
)))))
2012 (let ((size (count-lines beg end
)))
2014 (cond ((= size
0)) ; do nothing for an empty result
2015 ((< size org-babel-min-lines-for-block-output
)
2018 (beginning-of-line 1) (insert ": ") (forward-line 1)))
2021 (insert (if results-switches
2022 (format "#+begin_example%s\n" results-switches
)
2023 "#+begin_example\n"))
2024 (if (markerp end
) (goto-char end
) (forward-char (- end beg
)))
2025 (insert "#+end_example\n"))))))))
2027 (defun org-babel-update-block-body (new-body)
2028 "Update the body of the current code block to NEW-BODY."
2029 (if (not (org-babel-where-is-src-block-head))
2030 (error "not in source block")
2032 (replace-match (concat (org-babel-trim new-body
) "\n") nil t nil
5))
2033 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
2035 (defun org-babel-merge-params (&rest plists
)
2036 "Combine all parameter association lists in PLISTS.
2037 Later elements of PLISTS override the values of previous elements.
2038 This takes into account some special considerations for certain
2039 parameters when merging lists."
2040 (let ((results-exclusive-groups
2041 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2042 (cdr (assoc 'results org-babel-common-header-args-w-values
))))
2043 (exports-exclusive-groups
2044 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2045 (cdr (assoc 'exports org-babel-common-header-args-w-values
))))
2047 params results exports tangle noweb cache vars shebang comments padline
)
2048 (flet ((e-merge (exclusive-groups &rest result-params
)
2049 ;; maintain exclusivity of mutually exclusive parameters
2051 (mapc (lambda (new-params)
2052 (mapc (lambda (new-param)
2053 (mapc (lambda (exclusive-group)
2054 (when (member new-param exclusive-group
)
2055 (mapcar (lambda (excluded-param)
2062 (setq output
(org-uniquify
2063 (cons new-param output
))))
2073 (let ((name (if (listp (cdr pair
))
2075 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
2077 (intern (match-string 1 (cdr pair
)))))))
2081 (if (member name
(mapcar #'car vars
))
2085 (unless (equal (car p
) name
) p
))
2088 (list (cons name pair
))))
2089 ;; if no name is given and we already have named variables
2090 ;; then assign to named variables in order
2091 (if (and vars
(nth variable-index vars
))
2092 (prog1 (setf (cddr (nth variable-index vars
))
2093 (concat (symbol-name
2094 (car (nth variable-index vars
)))
2096 (incf variable-index
))
2097 (error "variable \"%s\" must be assigned a default value"
2100 (setq results
(e-merge results-exclusive-groups
2103 (let ((r (cdr pair
)))
2104 (if (stringp r
) r
(eval r
)))))))
2107 (setq results
(e-merge results-exclusive-groups
2109 (unless (or (member "both" exports
)
2110 (member "none" exports
)
2111 (member "code" exports
))
2112 (setq exports
(e-merge exports-exclusive-groups
2113 exports
'("results"))))
2114 (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))
2116 (setq exports
(e-merge exports-exclusive-groups
2117 exports
(split-string (cdr pair
)))))
2118 (:tangle
;; take the latest -- always overwrite
2119 (setq tangle
(or (list (cdr pair
)) tangle
)))
2121 (setq noweb
(e-merge
2122 '(("yes" "no" "tangle" "no-export"
2123 "strip-export" "eval"))
2125 (split-string (or (cdr pair
) "")))))
2127 (setq cache
(e-merge '(("yes" "no")) cache
2128 (split-string (or (cdr pair
) "")))))
2130 (setq padline
(e-merge '(("yes" "no")) padline
2131 (split-string (or (cdr pair
) "")))))
2132 (:shebang
;; take the latest -- always overwrite
2133 (setq shebang
(or (list (cdr pair
)) shebang
)))
2135 (setq comments
(e-merge '(("yes" "no")) comments
2136 (split-string (or (cdr pair
) "")))))
2137 (t ;; replace: this covers e.g. :session
2138 (setq params
(cons pair
(assq-delete-all (car pair
) params
))))))
2141 (setq vars
(reverse vars
))
2142 (while vars
(setq params
(cons (cons :var
(cddr (pop vars
))) params
)))
2145 (let ((key (intern (concat ":" (symbol-name hd
))))
2147 (setf params
(cons (cons key
(mapconcat 'identity val
" ")) params
))))
2148 '(results exports tangle noweb padline cache shebang comments
))
2151 (defvar *org-babel-use-quick-and-dirty-noweb-expansion
* nil
2152 "Set to true to use regular expressions to expand noweb references.
2153 This results in much faster noweb reference expansion but does
2154 not properly allow code blocks to inherit the \":noweb-ref\"
2155 header argument from buffer or subtree wide properties.")
2157 (defun org-babel-noweb-p (params context
)
2158 "Check if PARAMS require expansion in CONTEXT.
2159 CONTEXT may be one of :tangle, :export or :eval."
2160 (flet ((intersect (as bs
)
2162 (if (member (car as
) bs
)
2164 (intersect (cdr as
) bs
)))))
2165 (intersect (case context
2166 (:tangle
'("yes" "tangle" "no-export" "strip-export"))
2167 (:eval
'("yes" "no-export" "strip-export" "eval"))
2169 (split-string (or (cdr (assoc :noweb params
)) "")))))
2171 (defun org-babel-expand-noweb-references (&optional info parent-buffer
)
2172 "Expand Noweb references in the body of the current source code block.
2174 For example the following reference would be replaced with the
2175 body of the source-code block named 'example-block'.
2179 Note that any text preceding the <<foo>> construct on a line will
2180 be interposed between the lines of the replacement text. So for
2181 example if <<foo>> is placed behind a comment, then the entire
2182 replacement text will also be commented.
2184 This function must be called from inside of the buffer containing
2185 the source-code block which holds BODY.
2187 In addition the following syntax can be used to insert the
2188 results of evaluating the source-code block named 'example-block'.
2192 Any optional arguments can be passed to example-block by placing
2193 the arguments inside the parenthesis following the convention
2194 defined by `org-babel-lob'. For example
2196 <<example-block(a=9)>>
2198 would set the value of argument \"a\" equal to \"9\". Note that
2199 these arguments are not evaluated in the current source-code
2200 block but are passed literally to the \"example-block\"."
2201 (let* ((parent-buffer (or parent-buffer
(current-buffer)))
2202 (info (or info
(org-babel-get-src-block-info)))
2205 (comment (string= "noweb" (cdr (assoc :comments
(nth 2 info
)))))
2206 (rx-prefix (concat "\\(" org-babel-src-name-regexp
"\\|"
2207 ":noweb-ref[ \t]+" "\\)"))
2208 (new-body "") index source-name evaluate prefix blocks-in-buffer
)
2209 (flet ((nb-add (text) (setq new-body
(concat new-body text
)))
2212 (funcall (intern (concat lang
"-mode")))
2213 (comment-region (point) (progn (insert text
) (point)))
2214 (org-babel-trim (buffer-string)))))
2216 (insert body
) (goto-char (point-min))
2217 (setq index
(point))
2218 (while (and (re-search-forward (org-babel-noweb-wrap) nil t
))
2219 (save-match-data (setf source-name
(match-string 1)))
2220 (save-match-data (setq evaluate
(string-match "\(.*\)" source-name
)))
2223 (buffer-substring (match-beginning 0)
2225 (beginning-of-line 1) (point)))))
2226 ;; add interval to new-body (removing noweb reference)
2227 (goto-char (match-beginning 0))
2228 (nb-add (buffer-substring index
(point)))
2229 (goto-char (match-end 0))
2230 (setq index
(point))
2232 (with-current-buffer parent-buffer
2235 (mapconcat ;; interpose PREFIX between every line
2239 (let ((raw (org-babel-ref-resolve source-name
)))
2240 (if (stringp raw
) raw
(format "%S" raw
)))
2242 ;; retrieve from the library of babel
2243 (nth 2 (assoc (intern source-name
)
2244 org-babel-library-of-babel
))
2245 ;; return the contents of headlines literally
2247 (when (org-babel-ref-goto-headline-id source-name
)
2248 (org-babel-ref-headline-body)))
2249 ;; find the expansion of reference in this buffer
2250 (let ((rx (concat rx-prefix source-name
"[ \t\n]"))
2253 (goto-char (point-min))
2254 (if *org-babel-use-quick-and-dirty-noweb-expansion
*
2255 (while (re-search-forward rx nil t
)
2256 (let* ((i (org-babel-get-src-block-info 'light
))
2257 (body (org-babel-expand-noweb-references i
))
2258 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2262 (concat (c-wrap (car cs
)) "\n"
2264 (c-wrap (cadr cs
))))
2265 (org-babel-tangle-comment-links i
))
2267 (setq expansion
(cons sep
(cons full expansion
)))))
2268 (org-babel-map-src-blocks nil
2269 (let ((i (org-babel-get-src-block-info 'light
)))
2270 (when (equal (or (cdr (assoc :noweb-ref
(nth 2 i
)))
2273 (let* ((body (org-babel-expand-noweb-references i
))
2274 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2278 (concat (c-wrap (car cs
)) "\n"
2280 (c-wrap (cadr cs
))))
2281 (org-babel-tangle-comment-links i
))
2284 (cons sep
(cons full expansion
)))))))))
2286 (mapconcat #'identity
(nreverse (cdr expansion
)) "")))
2287 ;; possibly raise an error if named block doesn't exist
2288 (if (member lang org-babel-noweb-error-langs
)
2290 (org-babel-noweb-wrap source-name
)
2291 "could not be resolved (see "
2292 "`org-babel-noweb-error-langs')"))
2294 "[\n\r]") (concat "\n" prefix
))))))
2295 (nb-add (buffer-substring index
(point-max)))))
2298 (defun org-babel-clean-text-properties (text)
2299 "Strip all properties from text return."
2301 (set-text-properties 0 (length text
) nil text
) text
))
2303 (defun org-babel-strip-protective-commas (body &optional lang
)
2304 "Strip protective commas from bodies of source blocks."
2307 (if (and lang
(string= lang
"org"))
2308 (progn (goto-char (point-min))
2309 (while (re-search-forward "^[ \t]*\\(,\\)" nil t
)
2310 (replace-match "" nil nil nil
1)))
2311 (org-strip-protective-commas (point-min) (point-max)))
2314 (defun org-babel-script-escape (str &optional force
)
2315 "Safely convert tables into elisp lists."
2316 (let (in-single in-double out
)
2317 ((lambda (escaped) (condition-case nil
(org-babel-read escaped
) (error escaped
)))
2321 (or (and (string-equal "[" (substring str
0 1))
2322 (string-equal "]" (substring str -
1)))
2323 (and (string-equal "{" (substring str
0 1))
2324 (string-equal "}" (substring str -
1)))
2325 (and (string-equal "(" (substring str
0 1))
2326 (string-equal ")" (substring str -
1))))))
2336 (91 (if (or in-double in-single
) ; [
2339 (93 (if (or in-double in-single
) ; ]
2342 (123 (if (or in-double in-single
) ; {
2345 (125 (if (or in-double in-single
) ; }
2348 (44 (if (or in-double in-single
) ; ,
2349 (cons 44 out
) (cons 32 out
)))
2350 (39 (if in-double
; '
2352 (setq in-single
(not in-single
)) (cons 34 out
)))
2353 (34 (if in-single
; "
2354 (append (list 34 32) out
)
2355 (setq in-double
(not in-double
)) (cons 34 out
)))
2356 (t (cons ch out
)))))
2357 (string-to-list str
))
2358 (apply #'string
(reverse out
)))))
2361 (defun org-babel-read (cell &optional inhibit-lisp-eval
)
2362 "Convert the string value of CELL to a number if appropriate.
2363 Otherwise if cell looks like lisp (meaning it starts with a
2364 \"(\", \"'\", \"`\" or a \"[\") then read it as lisp, otherwise
2365 return it unmodified as a string. Optional argument NO-LISP-EVAL
2366 inhibits lisp evaluation for situations in which is it not
2368 (if (and (stringp cell
) (not (equal cell
"")))
2369 (or (org-babel-number-p cell
)
2370 (if (and (not inhibit-lisp-eval
)
2371 (member (substring cell
0 1) '("(" "'" "`" "[")))
2373 (if (string= (substring cell
0 1) "\"")
2375 (progn (set-text-properties 0 (length cell
) nil cell
) cell
))))
2378 (defun org-babel-number-p (string)
2379 "If STRING represents a number return its value."
2380 (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string
)
2381 (= (length (substring string
(match-beginning 0)
2384 (string-to-number string
)))
2386 (defun org-babel-import-elisp-from-file (file-name &optional separator
)
2387 "Read the results located at FILE-NAME into an elisp table.
2388 If the table is trivial, then return it as a scalar."
2390 (save-window-excursion
2394 (org-table-import file-name separator
)
2395 (delete-file file-name
)
2396 (setq result
(mapcar (lambda (row)
2397 (mapcar #'org-babel-string-read row
))
2398 (org-table-to-lisp))))
2400 (if (null (cdr result
)) ;; if result is trivial vector, then scalarize it
2401 (if (consp (car result
))
2402 (if (null (cdr (car result
)))
2408 (defun org-babel-string-read (cell)
2409 "Strip nested \"s from around strings."
2410 (org-babel-read (or (and (stringp cell
)
2411 (string-match "\\\"\\(.+\\)\\\"" cell
)
2412 (match-string 1 cell
))
2415 (defun org-babel-reverse-string (string)
2416 "Return the reverse of STRING."
2417 (apply 'string
(reverse (string-to-list string
))))
2419 (defun org-babel-chomp (string &optional regexp
)
2420 "Strip trailing spaces and carriage returns from STRING.
2421 Default regexp used is \"[ \f\t\n\r\v]\" but can be
2422 overwritten by specifying a regexp as a second argument."
2423 (let ((regexp (or regexp
"[ \f\t\n\r\v]")))
2424 (while (and (> (length string
) 0)
2425 (string-match regexp
(substring string -
1)))
2426 (setq string
(substring string
0 -
1)))
2429 (defun org-babel-trim (string &optional regexp
)
2430 "Strip leading and trailing spaces and carriage returns from STRING.
2431 Like `org-babel-chomp' only it runs on both the front and back
2433 (org-babel-chomp (org-babel-reverse-string
2434 (org-babel-chomp (org-babel-reverse-string string
) regexp
))
2437 (defvar org-babel-org-babel-call-process-region-original nil
)
2438 (defun org-babel-tramp-handle-call-process-region
2439 (start end program
&optional delete buffer display
&rest args
)
2440 "Use tramp to handle call-process-region.
2441 Fixes a bug in `tramp-handle-call-process-region'."
2442 (if (and (featurep 'tramp
) (file-remote-p default-directory
))
2443 (let ((tmpfile (tramp-compat-make-temp-file "")))
2444 (write-region start end tmpfile
)
2445 (when delete
(delete-region start end
))
2447 ;; (apply 'call-process program tmpfile buffer display args)
2449 (apply 'process-file program tmpfile buffer display args
)
2450 (delete-file tmpfile
)))
2451 ;; org-babel-call-process-region-original is the original emacs
2452 ;; definition. It is in scope from the let binding in
2453 ;; org-babel-execute-src-block
2454 (apply org-babel-call-process-region-original
2455 start end program delete buffer display args
)))
2457 (defun org-babel-local-file-name (file)
2458 "Return the local name component of FILE."
2459 (if (file-remote-p file
)
2461 (with-parsed-tramp-file-name file nil
2465 (defun org-babel-process-file-name (name &optional no-quote-p
)
2466 "Prepare NAME to be used in an external process.
2467 If NAME specifies a remote location, the remote portion of the
2468 name is removed, since in that case the process will be executing
2469 remotely. The file name is then processed by
2470 `expand-file-name'. Unless second argument NO-QUOTE-P is non-nil,
2471 the file name is additionally processed by
2472 `shell-quote-argument'"
2473 ((lambda (f) (if no-quote-p f
(shell-quote-argument f
)))
2474 (expand-file-name (org-babel-local-file-name name
))))
2476 (defvar org-babel-temporary-directory
)
2477 (unless (or noninteractive
(boundp 'org-babel-temporary-directory
))
2478 (defvar org-babel-temporary-directory
2479 (or (and (boundp 'org-babel-temporary-directory
)
2480 (file-exists-p org-babel-temporary-directory
)
2481 org-babel-temporary-directory
)
2482 (make-temp-file "babel-" t
))
2483 "Directory to hold temporary files created to execute code blocks.
2484 Used by `org-babel-temp-file'. This directory will be removed on
2487 (defun org-babel-temp-file (prefix &optional suffix
)
2488 "Create a temporary file in the `org-babel-temporary-directory'.
2489 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2490 value of `temporary-file-directory' temporarily set to the value
2491 of `org-babel-temporary-directory'."
2492 (if (file-remote-p default-directory
)
2494 (concat (file-remote-p default-directory
)
2496 prefix temporary-file-directory
)
2498 (let ((temporary-file-directory
2499 (or (and (boundp 'org-babel-temporary-directory
)
2500 (file-exists-p org-babel-temporary-directory
)
2501 org-babel-temporary-directory
)
2502 temporary-file-directory
)))
2503 (make-temp-file prefix nil suffix
))))
2505 (defun org-babel-remove-temporary-directory ()
2506 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2507 (when (and (boundp 'org-babel-temporary-directory
)
2508 (file-exists-p org-babel-temporary-directory
))
2509 ;; taken from `delete-directory' in files.el
2512 (mapc (lambda (file)
2513 ;; This test is equivalent to
2514 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2515 ;; but more efficient
2516 (if (eq t
(car (file-attributes file
)))
2517 (delete-directory file
)
2518 (delete-file file
)))
2519 ;; We do not want to delete "." and "..".
2520 (directory-files org-babel-temporary-directory
'full
2521 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2522 (delete-directory org-babel-temporary-directory
))
2524 (message "Failed to remove temporary Org-babel directory %s"
2525 (if (boundp 'org-babel-temporary-directory
)
2526 org-babel-temporary-directory
2527 "[directory not defined]"))))))
2529 (add-hook 'kill-emacs-hook
'org-babel-remove-temporary-directory
)