Use the default face instead of fancy colors.
[org-mode.git] / lisp / ob.el
blob493f8c65d20212befc7afef64b70487c3b8e99d7
1 ;;; ob.el --- working with code blocks in org-mode
3 ;; Copyright (C) 2009-2011 Free Software Foundation, Inc.
5 ;; Author: Eric Schulte
6 ;; Dan Davison
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/>.
25 ;;; Code:
26 (eval-when-compile
27 (require 'cl))
28 (require 'ob-eval)
29 (require 'org-macs)
31 (defvar org-babel-call-process-region-original)
32 (defvar org-src-lang-modes)
33 (defvar org-babel-library-of-babel)
34 (declare-function show-all "outline" ())
35 (declare-function tramp-compat-make-temp-file "tramp-compat"
36 (filename &optional dir-flag))
37 (declare-function tramp-dissect-file-name "tramp" (name &optional nodefault))
38 (declare-function tramp-file-name-user "tramp" (vec))
39 (declare-function tramp-file-name-host "tramp" (vec))
40 (declare-function with-parsed-tramp-file-name "tramp" (filename var &rest body))
41 (declare-function org-icompleting-read "org" (&rest args))
42 (declare-function org-edit-src-code "org-src"
43 (&optional context code edit-buffer-name quietp))
44 (declare-function org-edit-src-exit "org-src" (&optional context))
45 (declare-function org-open-at-point "org" (&optional in-emacs reference-buffer))
46 (declare-function org-save-outline-visibility "org" (use-markers &rest body))
47 (declare-function org-outline-overlay-data "org" (&optional use-markers))
48 (declare-function org-set-outline-overlay-data "org" (data))
49 (declare-function org-narrow-to-subtree "org" ())
50 (declare-function org-entry-get "org"
51 (pom property &optional inherit literal-nil))
52 (declare-function org-make-options-regexp "org" (kwds &optional extra))
53 (declare-function org-do-remove-indentation "org" (&optional n))
54 (declare-function org-show-context "org" (&optional key))
55 (declare-function org-at-table-p "org" (&optional table-type))
56 (declare-function org-cycle "org" (&optional arg))
57 (declare-function org-uniquify "org" (list))
58 (declare-function org-current-level "org" ())
59 (declare-function org-table-import "org-table" (file arg))
60 (declare-function org-add-hook "org-compat"
61 (hook function &optional append local))
62 (declare-function org-table-align "org-table" ())
63 (declare-function org-table-end "org-table" (&optional table-type))
64 (declare-function orgtbl-to-generic "org-table" (table params))
65 (declare-function orgtbl-to-orgtbl "org-table" (table params))
66 (declare-function org-babel-tangle-comment-links "ob-tangle" (&optional info))
67 (declare-function org-babel-lob-get-info "ob-lob" nil)
68 (declare-function org-babel-ref-split-args "ob-ref" (arg-string))
69 (declare-function org-babel-ref-parse "ob-ref" (assignment))
70 (declare-function org-babel-ref-resolve "ob-ref" (ref))
71 (declare-function org-babel-ref-goto-headline-id "ob-ref" (id))
72 (declare-function org-babel-ref-headline-body "ob-ref" ())
73 (declare-function org-babel-lob-execute-maybe "ob-lob" ())
74 (declare-function org-babel-map-call-lines "ob-lob" (file &rest body))
75 (declare-function org-number-sequence "org-compat" (from &optional to inc))
76 (declare-function org-at-item-p "org-list" ())
77 (declare-function org-list-parse-list "org-list" (&optional delete))
78 (declare-function org-list-to-generic "org-list" (LIST PARAMS))
79 (declare-function org-list-struct "org-list" ())
80 (declare-function org-list-prevs-alist "org-list" (struct))
81 (declare-function org-list-get-list-end "org-list" (item struct prevs))
83 (defgroup org-babel nil
84 "Code block evaluation and management in `org-mode' documents."
85 :tag "Babel"
86 :group 'org)
88 (defcustom org-confirm-babel-evaluate t
89 "Confirm before evaluation.
90 Require confirmation before interactively evaluating code
91 blocks in Org-mode buffers. The default value of this variable
92 is t, meaning confirmation is required for any code block
93 evaluation. This variable can be set to nil to inhibit any
94 future confirmation requests. This variable can also be set to a
95 function which takes two arguments the language of the code block
96 and the body of the code block. Such a function should then
97 return a non-nil value if the user should be prompted for
98 execution or nil if no prompt is required.
100 Warning: Disabling confirmation may result in accidental
101 evaluation of potentially harmful code. It may be advisable
102 remove code block execution from C-c C-c as further protection
103 against accidental code block evaluation. The
104 `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
105 remove code block execution from the C-c C-c keybinding."
106 :group 'org-babel
107 :type '(choice boolean function))
108 ;; don't allow this variable to be changed through file settings
109 (put 'org-confirm-babel-evaluate 'safe-local-variable (lambda (x) (eq x t)))
111 (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
112 "Remove code block evaluation from the C-c C-c key binding."
113 :group 'org-babel
114 :type 'boolean)
116 (defvar org-babel-src-name-regexp
117 "^[ \t]*#\\+name:[ \t]*"
118 "Regular expression used to match a source name line.")
120 (defvar org-babel-multi-line-header-regexp
121 "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
122 "Regular expression used to match multi-line header arguments.")
124 (defvar org-babel-src-name-w-name-regexp
125 (concat org-babel-src-name-regexp
126 "\\("
127 org-babel-multi-line-header-regexp
128 "\\)*"
129 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)")
130 "Regular expression matching source name lines with a name.")
132 (defvar org-babel-src-block-regexp
133 (concat
134 ;; (1) indentation (2) lang
135 "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
136 ;; (3) switches
137 "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
138 ;; (4) header arguments
139 "\\([^\n]*\\)\n"
140 ;; (5) body
141 "\\([^\000]*?\n\\)?[ \t]*#\\+end_src")
142 "Regexp used to identify code blocks.")
144 (defvar org-babel-inline-src-block-regexp
145 (concat
146 ;; (1) replacement target (2) lang
147 "\\(?:^\\|[^-[:alnum:]]\\)\\(src_\\([^ \f\t\n\r\v]+\\)"
148 ;; (3,4) (unused, headers)
149 "\\(\\|\\[\\(.*?\\)\\]\\)"
150 ;; (5) body
151 "{\\([^\f\n\r\v]+?\\)}\\)")
152 "Regexp used to identify inline src-blocks.")
154 (defun org-babel-get-header (params key &optional others)
155 "Select only header argument of type KEY from a list.
156 Optional argument OTHERS indicates that only the header that do
157 not match KEY should be returned."
158 (delq nil
159 (mapcar
160 (lambda (p) (when (funcall (if others #'not #'identity) (eq (car p) key)) p))
161 params)))
163 (defun org-babel-get-inline-src-block-matches()
164 "Set match data if within body of an inline source block.
165 Returns non-nil if match-data set"
166 (let ((src-at-0-p (save-excursion
167 (beginning-of-line 1)
168 (string= "src" (thing-at-point 'word))))
169 (first-line-p (= 1 (line-number-at-pos)))
170 (orig (point)))
171 (let ((search-for (cond ((and src-at-0-p first-line-p "src_"))
172 (first-line-p "[ \t]src_")
173 (t "[ \f\t\n\r\v]src_")))
174 (lower-limit (if first-line-p
176 (- (point-at-bol) 1))))
177 (save-excursion
178 (when (or (and src-at-0-p (bobp))
179 (and (re-search-forward "}" (point-at-eol) t)
180 (re-search-backward search-for lower-limit t)
181 (> orig (point))))
182 (when (looking-at org-babel-inline-src-block-regexp)
183 t ))))))
185 (defvar org-babel-inline-lob-one-liner-regexp)
186 (defun org-babel-get-lob-one-liner-matches()
187 "Set match data if on line of an lob one liner.
188 Returns non-nil if match-data set"
189 (save-excursion
190 (unless (= (point) (point-at-bol)) ;; move before inline block
191 (re-search-backward "[ \f\t\n\r\v]" nil t))
192 (if (looking-at org-babel-inline-lob-one-liner-regexp)
194 nil)))
196 (defun org-babel-get-src-block-info (&optional light)
197 "Get information on the current source block.
199 Optional argument LIGHT does not resolve remote variable
200 references; a process which could likely result in the execution
201 of other code blocks.
203 Returns a list
204 (language body header-arguments-alist switches name indent)."
205 (let ((case-fold-search t) head info name indent)
206 ;; full code block
207 (if (setq head (org-babel-where-is-src-block-head))
208 (save-excursion
209 (goto-char head)
210 (setq info (org-babel-parse-src-block-match))
211 (setq indent (car (last info)))
212 (setq info (butlast info))
213 (while (and (forward-line -1)
214 (looking-at org-babel-multi-line-header-regexp))
215 (setf (nth 2 info)
216 (org-babel-merge-params
217 (nth 2 info)
218 (org-babel-parse-header-arguments (match-string 1)))))
219 (when (looking-at org-babel-src-name-w-name-regexp)
220 (setq name (org-babel-clean-text-properties (match-string 3)))
221 (when (and (match-string 5) (> (length (match-string 5)) 0))
222 (setf (nth 2 info) ;; merge functional-syntax vars and header-args
223 (org-babel-merge-params
224 (mapcar
225 (lambda (ref) (cons :var ref))
226 (mapcar
227 (lambda (var) ;; check that each variable is initialized
228 (if (string-match ".+=.+" var)
230 (error
231 "variable \"%s\"%s must be assigned a default value"
232 var (if name (format " in block \"%s\"" name) ""))))
233 (org-babel-ref-split-args (match-string 5))))
234 (nth 2 info))))))
235 ;; inline source block
236 (when (org-babel-get-inline-src-block-matches)
237 (setq info (org-babel-parse-inline-src-block-match))))
238 ;; resolve variable references and add summary parameters
239 (when (and info (not light))
240 (setf (nth 2 info) (org-babel-process-params (nth 2 info))))
241 (when info (append info (list name indent)))))
243 (defun org-babel-confirm-evaluate (info)
244 "Confirm evaluation of the code block INFO.
245 This behavior can be suppressed by setting the value of
246 `org-confirm-babel-evaluate' to nil, in which case all future
247 interactive code block evaluations will proceed without any
248 confirmation from the user.
250 Note disabling confirmation may result in accidental evaluation
251 of potentially harmful code."
252 (let* ((eval (or (cdr (assoc :eval (nth 2 info)))
253 (when (assoc :noeval (nth 2 info)) "no")))
254 (query (cond ((equal eval "query") t)
255 ((and org-current-export-file
256 (equal eval "query-export")) t)
257 ((functionp org-confirm-babel-evaluate)
258 (funcall org-confirm-babel-evaluate
259 (nth 0 info) (nth 1 info)))
260 (t org-confirm-babel-evaluate))))
261 (if (or (equal eval "never") (equal eval "no")
262 (and org-current-export-file (or (equal eval "no-export")
263 (equal eval "never-export")))
264 (and query
265 (not (yes-or-no-p
266 (format "Evaluate this%scode block%son your system? "
267 (if info (format " %s " (nth 0 info)) " ")
268 (if (nth 4 info)
269 (format " (%s) " (nth 4 info)) " "))))))
270 (prog1 nil (message "Evaluation %s"
271 (if (or (equal eval "never") (equal eval "no")
272 (equal eval "no-export")
273 (equal eval "never-export"))
274 "Disabled" "Aborted")))
275 t)))
277 ;;;###autoload
278 (defun org-babel-execute-safely-maybe ()
279 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
280 (org-babel-execute-maybe)))
282 (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-execute-safely-maybe)
284 ;;;###autoload
285 (defun org-babel-execute-maybe ()
286 (interactive)
287 (or (org-babel-execute-src-block-maybe)
288 (org-babel-lob-execute-maybe)))
290 (defun org-babel-execute-src-block-maybe ()
291 "Conditionally execute a source block.
292 Detect if this is context for a Babel src-block and if so
293 then run `org-babel-execute-src-block'."
294 (interactive)
295 (let ((info (org-babel-get-src-block-info)))
296 (if info
297 (progn (org-babel-eval-wipe-error-buffer)
298 (org-babel-execute-src-block current-prefix-arg info) t) nil)))
300 ;;;###autoload
301 (defun org-babel-view-src-block-info ()
302 "Display information on the current source block.
303 This includes header arguments, language and name, and is largely
304 a window into the `org-babel-get-src-block-info' function."
305 (interactive)
306 (let ((info (org-babel-get-src-block-info 'light)))
307 (flet ((full (it) (> (length it) 0))
308 (printf (fmt &rest args) (princ (apply #'format fmt args))))
309 (when info
310 (with-help-window (help-buffer)
311 (let ((name (nth 4 info))
312 (lang (nth 0 info))
313 (switches (nth 3 info))
314 (header-args (nth 2 info)))
315 (when name (printf "Name: %s\n" name))
316 (when lang (printf "Lang: %s\n" lang))
317 (when (full switches) (printf "Switches: %s\n" switches))
318 (printf "Header Arguments:\n")
319 (dolist (pair (sort header-args
320 (lambda (a b) (string< (symbol-name (car a))
321 (symbol-name (car b))))))
322 (when (full (cdr pair))
323 (printf "\t%S%s\t%s\n"
324 (car pair)
325 (if (> (length (format "%S" (car pair))) 7) "" "\t")
326 (cdr pair))))))))))
328 ;;;###autoload
329 (defun org-babel-expand-src-block-maybe ()
330 "Conditionally expand a source block.
331 Detect if this is context for a org-babel src-block and if so
332 then run `org-babel-expand-src-block'."
333 (interactive)
334 (let ((info (org-babel-get-src-block-info)))
335 (if info
336 (progn (org-babel-expand-src-block current-prefix-arg info) t)
337 nil)))
339 ;;;###autoload
340 (defun org-babel-load-in-session-maybe ()
341 "Conditionally load a source block in a session.
342 Detect if this is context for a org-babel src-block and if so
343 then run `org-babel-load-in-session'."
344 (interactive)
345 (let ((info (org-babel-get-src-block-info)))
346 (if info
347 (progn (org-babel-load-in-session current-prefix-arg info) t)
348 nil)))
350 (add-hook 'org-metaup-hook 'org-babel-load-in-session-maybe)
352 ;;;###autoload
353 (defun org-babel-pop-to-session-maybe ()
354 "Conditionally pop to a session.
355 Detect if this is context for a org-babel src-block and if so
356 then run `org-babel-pop-to-session'."
357 (interactive)
358 (let ((info (org-babel-get-src-block-info)))
359 (if info (progn (org-babel-pop-to-session current-prefix-arg info) t) nil)))
361 (add-hook 'org-metadown-hook 'org-babel-pop-to-session-maybe)
363 (defconst org-babel-common-header-args-w-values
364 '((cache . ((no yes)))
365 (cmdline . :any)
366 (colnames . ((nil no yes)))
367 (comments . ((no link yes org both noweb)))
368 (dir . :any)
369 (eval . ((never query)))
370 (exports . ((code results both none)))
371 (file . :any)
372 (hlines . ((no yes)))
373 (mkdirp . ((yes no)))
374 (no-expand)
375 (noeval)
376 (noweb . ((yes no tangle)))
377 (noweb-ref . :any)
378 (padline . ((yes no)))
379 (results . ((file list vector table scalar verbatim)
380 (raw org html latex code pp wrap)
381 (replace silent append prepend)
382 (output value)))
383 (rownames . ((no yes)))
384 (sep . :any)
385 (session . :any)
386 (shebang . :any)
387 (tangle . ((tangle yes no :any)))
388 (var . :any)))
390 (defconst org-babel-header-arg-names
391 (mapcar #'car org-babel-common-header-args-w-values)
392 "Common header arguments used by org-babel.
393 Note that individual languages may define their own language
394 specific header arguments as well.")
396 (defvar org-babel-default-header-args
397 '((:session . "none") (:results . "replace") (:exports . "code")
398 (:cache . "no") (:noweb . "no") (:hlines . "no") (:tangle . "no")
399 (:padnewline . "yes"))
400 "Default arguments to use when evaluating a source block.")
402 (defvar org-babel-default-inline-header-args
403 '((:session . "none") (:results . "replace") (:exports . "results"))
404 "Default arguments to use when evaluating an inline source block.")
406 (defvar org-babel-data-names '("TBLNAME" "RESULTS" "NAME"))
408 (defvar org-babel-result-regexp
409 (concat "^[ \t]*#\\+"
410 (regexp-opt org-babel-data-names t)
411 "\\(\\[\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*")
412 "Regular expression used to match result lines.
413 If the results are associated with a hash key then the hash will
414 be saved in the second match data.")
416 (defvar org-babel-result-w-name-regexp
417 (concat org-babel-result-regexp
418 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
420 (defvar org-babel-min-lines-for-block-output 10
421 "The minimum number of lines for block output.
422 If number of lines of output is equal to or exceeds this
423 value, the output is placed in a #+begin_example...#+end_example
424 block. Otherwise the output is marked as literal by inserting
425 colons at the starts of the lines. This variable only takes
426 effect if the :results output option is in effect.")
428 (defvar org-babel-noweb-error-langs nil
429 "Languages for which Babel will raise literate programming errors.
430 List of languages for which errors should be raised when the
431 source code block satisfying a noweb reference in this language
432 can not be resolved.")
434 (defvar org-babel-hash-show 4
435 "Number of initial characters to show of a hidden results hash.")
437 (defvar org-babel-after-execute-hook nil
438 "Hook for functions to be called after `org-babel-execute-src-block'")
440 (defun org-babel-named-src-block-regexp-for-name (name)
441 "This generates a regexp used to match a src block named NAME."
442 (concat org-babel-src-name-regexp (regexp-quote name)
443 "\\([ \t]\\|$\\|(\\)" ".*[\r\n]"
444 (substring org-babel-src-block-regexp 1)))
446 (defun org-babel-named-data-regexp-for-name (name)
447 "This generates a regexp used to match data named NAME."
448 (concat org-babel-result-regexp (regexp-quote name) "\\([ \t]\\|$\\)"))
450 ;;; functions
451 (defvar call-process-region)
452 ;;;###autoload
454 (defun org-babel-execute-src-block (&optional arg info params)
455 "Execute the current source code block.
456 Insert the results of execution into the buffer. Source code
457 execution and the collection and formatting of results can be
458 controlled through a variety of header arguments.
460 With prefix argument ARG, force re-execution even if an existing
461 result cached in the buffer would otherwise have been returned.
463 Optionally supply a value for INFO in the form returned by
464 `org-babel-get-src-block-info'.
466 Optionally supply a value for PARAMS which will be merged with
467 the header arguments specified at the front of the source code
468 block."
469 (interactive)
470 (let ((info (or info (org-babel-get-src-block-info))))
471 (when (org-babel-confirm-evaluate info)
472 (let* ((lang (nth 0 info))
473 (params (if params
474 (org-babel-process-params
475 (org-babel-merge-params (nth 2 info) params))
476 (nth 2 info)))
477 (cache? (and (not arg) (cdr (assoc :cache params))
478 (string= "yes" (cdr (assoc :cache params)))))
479 (result-params (cdr (assoc :result-params params)))
480 (new-hash (when cache? (org-babel-sha1-hash info)))
481 (old-hash (when cache? (org-babel-current-result-hash)))
482 (body (setf (nth 1 info)
483 (let ((noweb (cdr (assoc :noweb params))))
484 (if (and noweb
485 (or (string= "yes" noweb)
486 (string= "tangle" noweb)))
487 (org-babel-expand-noweb-references info)
488 (nth 1 info)))))
489 (dir (cdr (assoc :dir params)))
490 (default-directory
491 (or (and dir (file-name-as-directory dir)) default-directory))
492 (org-babel-call-process-region-original
493 (if (boundp 'org-babel-call-process-region-original)
494 org-babel-call-process-region-original
495 (symbol-function 'call-process-region)))
496 (indent (car (last info)))
497 result cmd)
498 (unwind-protect
499 (flet ((call-process-region (&rest args)
500 (apply 'org-babel-tramp-handle-call-process-region args)))
501 (flet ((lang-check (f)
502 (let ((f (intern (concat "org-babel-execute:" f))))
503 (when (fboundp f) f))))
504 (setq cmd
505 (or (lang-check lang)
506 (lang-check (symbol-name
507 (cdr (assoc lang org-src-lang-modes))))
508 (error "No org-babel-execute function for %s!" lang))))
509 (if (and (not arg) new-hash (equal new-hash old-hash))
510 (save-excursion ;; return cached result
511 (goto-char (org-babel-where-is-src-block-result nil info))
512 (end-of-line 1) (forward-char 1)
513 (setq result (org-babel-read-result))
514 (message (replace-regexp-in-string
515 "%" "%%" (format "%S" result))) result)
516 (message "executing %s code block%s..."
517 (capitalize lang)
518 (if (nth 4 info) (format " (%s)" (nth 4 info)) ""))
519 (setq result
520 ((lambda (result)
521 (if (and (eq (cdr (assoc :result-type params)) 'value)
522 (or (member "vector" result-params)
523 (member "table" result-params))
524 (not (listp result)))
525 (list (list result)) result))
526 (funcall cmd body params)))
527 ;; if non-empty result and :file then write to :file
528 (when (cdr (assoc :file params))
529 (when result
530 (with-temp-file (cdr (assoc :file params))
531 (insert
532 (org-babel-format-result
533 result (cdr (assoc :sep (nth 2 info)))))))
534 (setq result (cdr (assoc :file params))))
535 (org-babel-insert-result
536 result result-params info new-hash indent lang)
537 (run-hooks 'org-babel-after-execute-hook)
538 result))
539 (setq call-process-region 'org-babel-call-process-region-original))))))
541 (defun org-babel-expand-body:generic (body params &optional var-lines)
542 "Expand BODY with PARAMS.
543 Expand a block of code with org-babel according to its header
544 arguments. This generic implementation of body expansion is
545 called for languages which have not defined their own specific
546 org-babel-expand-body:lang function."
547 (mapconcat #'identity (append var-lines (list body)) "\n"))
549 ;;;###autoload
550 (defun org-babel-expand-src-block (&optional arg info params)
551 "Expand the current source code block.
552 Expand according to the source code block's header
553 arguments and pop open the results in a preview buffer."
554 (interactive)
555 (let* ((info (or info (org-babel-get-src-block-info)))
556 (lang (nth 0 info))
557 (params (setf (nth 2 info)
558 (sort (org-babel-merge-params (nth 2 info) params)
559 (lambda (el1 el2) (string< (symbol-name (car el1))
560 (symbol-name (car el2)))))))
561 (body (setf (nth 1 info)
562 (if (and (cdr (assoc :noweb params))
563 (string= "yes" (cdr (assoc :noweb params))))
564 (org-babel-expand-noweb-references info) (nth 1 info))))
565 (expand-cmd (intern (concat "org-babel-expand-body:" lang)))
566 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
567 lang)))
568 (expanded
569 (if (fboundp expand-cmd) (funcall expand-cmd body params)
570 (org-babel-expand-body:generic
571 body params (and (fboundp assignments-cmd)
572 (funcall assignments-cmd params))))))
573 (org-edit-src-code
574 nil expanded (concat "*Org-Babel Preview " (buffer-name) "[ " lang " ]*"))))
576 (defun org-babel-edit-distance (s1 s2)
577 "Return the edit (levenshtein) distance between strings S1 S2."
578 (let* ((l1 (length s1))
579 (l2 (length s2))
580 (dist (map 'vector (lambda (_) (make-vector (1+ l2) nil))
581 (number-sequence 1 (1+ l1)))))
582 (flet ((in (i j) (aref (aref dist i) j))
583 (mmin (&rest lst) (apply #'min (remove nil lst))))
584 (setf (aref (aref dist 0) 0) 0)
585 (dolist (i (number-sequence 1 l1))
586 (dolist (j (number-sequence 1 l2))
587 (setf (aref (aref dist i) j)
588 (+ (if (equal (aref s1 (1- i)) (aref s2 (1- j))) 0 1)
589 (mmin (in (1- i) j) (in i (1- j)) (in (1- i) (1- j)))))))
590 (in l1 l2))))
592 ;;;###autoload
593 (defun org-babel-check-src-block ()
594 "Check for misspelled header arguments in the current code block."
595 (interactive)
596 ;; TODO: report malformed code block
597 ;; TODO: report incompatible combinations of header arguments
598 ;; TODO: report uninitialized variables
599 (let ((too-close 2)) ;; <- control closeness to report potential match
600 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg)) 1))
601 (and (org-babel-where-is-src-block-head)
602 (org-babel-parse-header-arguments
603 (org-babel-clean-text-properties
604 (match-string 4))))))
605 (dolist (name (mapcar #'symbol-name org-babel-header-arg-names))
606 (when (and (not (string= header name))
607 (<= (org-babel-edit-distance header name) too-close))
608 (error "supplied header \"%S\" is suspiciously close to \"%S\""
609 header name))))
610 (message "No suspicious header arguments found.")))
612 ;;;###autoload
613 (defun org-babel-insert-header-arg ()
614 "Insert a header argument selecting from lists of common args and values."
615 (interactive)
616 (let* ((lang (car (org-babel-get-src-block-info 'light)))
617 (lang-headers (intern (concat "org-babel-header-arg-names:" lang)))
618 (headers (append (if (boundp lang-headers)
619 (mapcar (lambda (h) (cons h :any))
620 (eval lang-headers))
621 nil)
622 org-babel-common-header-args-w-values))
623 (arg (org-icompleting-read
624 "Header Arg: "
625 (mapcar
626 (lambda (header-spec) (symbol-name (car header-spec)))
627 headers))))
628 (insert ":" arg)
629 (let ((vals (cdr (assoc (intern arg) headers))))
630 (when vals
631 (insert
633 (cond
634 ((eq vals :any)
635 (read-from-minibuffer "value: "))
636 ((listp vals)
637 (mapconcat
638 (lambda (group)
639 (let ((arg (org-icompleting-read
640 "value: "
641 (cons "default" (mapcar #'symbol-name group)))))
642 (if (and arg (not (string= "default" arg)))
643 (concat arg " ")
644 "")))
645 vals ""))))))))
647 ;;;###autoload
648 (defun org-babel-load-in-session (&optional arg info)
649 "Load the body of the current source-code block.
650 Evaluate the header arguments for the source block before
651 entering the session. After loading the body this pops open the
652 session."
653 (interactive)
654 (let* ((info (or info (org-babel-get-src-block-info)))
655 (lang (nth 0 info))
656 (params (nth 2 info))
657 (body (setf (nth 1 info)
658 (if (and (cdr (assoc :noweb params))
659 (string= "yes" (cdr (assoc :noweb params))))
660 (org-babel-expand-noweb-references info)
661 (nth 1 info))))
662 (session (cdr (assoc :session params)))
663 (dir (cdr (assoc :dir params)))
664 (default-directory
665 (or (and dir (file-name-as-directory dir)) default-directory))
666 (cmd (intern (concat "org-babel-load-session:" lang))))
667 (unless (fboundp cmd)
668 (error "No org-babel-load-session function for %s!" lang))
669 (pop-to-buffer (funcall cmd session body params))
670 (end-of-line 1)))
672 ;;;###autoload
673 (defun org-babel-initiate-session (&optional arg info)
674 "Initiate session for current code block.
675 If called with a prefix argument then resolve any variable
676 references in the header arguments and assign these variables in
677 the session. Copy the body of the code block to the kill ring."
678 (interactive "P")
679 (let* ((info (or info (org-babel-get-src-block-info (not arg))))
680 (lang (nth 0 info))
681 (body (nth 1 info))
682 (params (nth 2 info))
683 (session (cdr (assoc :session params)))
684 (dir (cdr (assoc :dir params)))
685 (default-directory
686 (or (and dir (file-name-as-directory dir)) default-directory))
687 (init-cmd (intern (format "org-babel-%s-initiate-session" lang)))
688 (prep-cmd (intern (concat "org-babel-prep-session:" lang))))
689 (if (and (stringp session) (string= session "none"))
690 (error "This block is not using a session!"))
691 (unless (fboundp init-cmd)
692 (error "No org-babel-initiate-session function for %s!" lang))
693 (with-temp-buffer (insert (org-babel-trim body))
694 (copy-region-as-kill (point-min) (point-max)))
695 (when arg
696 (unless (fboundp prep-cmd)
697 (error "No org-babel-prep-session function for %s!" lang))
698 (funcall prep-cmd session params))
699 (funcall init-cmd session params)))
701 ;;;###autoload
702 (defun org-babel-switch-to-session (&optional arg info)
703 "Switch to the session of the current code block.
704 Uses `org-babel-initiate-session' to start the session. If called
705 with a prefix argument then this is passed on to
706 `org-babel-initiate-session'."
707 (interactive "P")
708 (pop-to-buffer (org-babel-initiate-session arg info))
709 (end-of-line 1))
711 (defalias 'org-babel-pop-to-session 'org-babel-switch-to-session)
713 ;;;###autoload
714 (defun org-babel-switch-to-session-with-code (&optional arg info)
715 "Switch to code buffer and display session."
716 (interactive "P")
717 (flet ((swap-windows
719 (let ((other-window-buffer (window-buffer (next-window))))
720 (set-window-buffer (next-window) (current-buffer))
721 (set-window-buffer (selected-window) other-window-buffer))
722 (other-window 1)))
723 (let ((info (org-babel-get-src-block-info))
724 (org-src-window-setup 'reorganize-frame))
725 (save-excursion
726 (org-babel-switch-to-session arg info))
727 (org-edit-src-code))
728 (swap-windows)))
730 (defmacro org-babel-do-in-edit-buffer (&rest body)
731 "Evaluate BODY in edit buffer if there is a code block at point.
732 Return t if a code block was found at point, nil otherwise."
733 `(let ((org-src-window-setup 'switch-invisibly))
734 (when (and (org-babel-where-is-src-block-head)
735 (org-edit-src-code nil nil nil))
736 (unwind-protect (progn ,@body)
737 (if (org-bound-and-true-p org-edit-src-from-org-mode)
738 (org-edit-src-exit)))
739 t)))
740 (def-edebug-spec org-babel-do-in-edit-buffer (body))
742 (defun org-babel-do-key-sequence-in-edit-buffer (key)
743 "Read key sequence and execute the command in edit buffer.
744 Enter a key sequence to be executed in the language major-mode
745 edit buffer. For example, TAB will alter the contents of the
746 Org-mode code block according to the effect of TAB in the
747 language major-mode buffer. For languages that support
748 interactive sessions, this can be used to send code from the Org
749 buffer to the session for evaluation using the native major-mode
750 evaluation mechanisms."
751 (interactive "kEnter key-sequence to execute in edit buffer: ")
752 (org-babel-do-in-edit-buffer
753 (call-interactively
754 (key-binding (or key (read-key-sequence nil))))))
756 (defvar org-bracket-link-regexp)
757 ;;;###autoload
758 (defun org-babel-open-src-block-result (&optional re-run)
759 "If `point' is on a src block then open the results of the
760 source code block, otherwise return nil. With optional prefix
761 argument RE-RUN the source-code block is evaluated even if
762 results already exist."
763 (interactive "P")
764 (let ((info (org-babel-get-src-block-info)))
765 (when info
766 (save-excursion
767 ;; go to the results, if there aren't any then run the block
768 (goto-char (or (and (not re-run) (org-babel-where-is-src-block-result))
769 (progn (org-babel-execute-src-block)
770 (org-babel-where-is-src-block-result))))
771 (end-of-line 1)
772 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
773 ;; open the results
774 (if (looking-at org-bracket-link-regexp)
775 ;; file results
776 (org-open-at-point)
777 (let ((r (org-babel-format-result
778 (org-babel-read-result) (cdr (assoc :sep (nth 2 info))))))
779 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
780 (delete-region (point-min) (point-max))
781 (insert r)))
782 t))))
784 ;;;###autoload
785 (defmacro org-babel-map-src-blocks (file &rest body)
786 "Evaluate BODY forms on each source-block in FILE.
787 If FILE is nil evaluate BODY forms on source blocks in current
788 buffer. During evaluation of BODY the following local variables
789 are set relative to the currently matched code block.
791 full-block ------- string holding the entirety of the code block
792 beg-block -------- point at the beginning of the code block
793 end-block -------- point at the end of the matched code block
794 lang ------------- string holding the language of the code block
795 beg-lang --------- point at the beginning of the lang
796 end-lang --------- point at the end of the lang
797 switches --------- string holding the switches
798 beg-switches ----- point at the beginning of the switches
799 end-switches ----- point at the end of the switches
800 header-args ------ string holding the header-args
801 beg-header-args -- point at the beginning of the header-args
802 end-header-args -- point at the end of the header-args
803 body ------------- string holding the body of the code block
804 beg-body --------- point at the beginning of the body
805 end-body --------- point at the end of the body"
806 (declare (indent 1))
807 (let ((tempvar (make-symbol "file")))
808 `(let* ((,tempvar ,file)
809 (visited-p (or (null ,tempvar)
810 (get-file-buffer (expand-file-name ,tempvar))))
811 (point (point)) to-be-removed)
812 (save-window-excursion
813 (when ,tempvar (find-file ,tempvar))
814 (setq to-be-removed (current-buffer))
815 (goto-char (point-min))
816 (while (re-search-forward org-babel-src-block-regexp nil t)
817 (goto-char (match-beginning 0))
818 (let ((full-block (match-string 0))
819 (beg-block (match-beginning 0))
820 (end-block (match-end 0))
821 (lang (match-string 2))
822 (beg-lang (match-beginning 2))
823 (end-lang (match-end 2))
824 (switches (match-string 3))
825 (beg-switches (match-beginning 3))
826 (end-switches (match-end 3))
827 (header-args (match-string 4))
828 (beg-header-args (match-beginning 4))
829 (end-header-args (match-end 4))
830 (body (match-string 5))
831 (beg-body (match-beginning 5))
832 (end-body (match-end 5)))
833 ,@body
834 (goto-char end-block))))
835 (unless visited-p (kill-buffer to-be-removed))
836 (goto-char point))))
837 (def-edebug-spec org-babel-map-src-blocks (form body))
839 ;;;###autoload
840 (defmacro org-babel-map-inline-src-blocks (file &rest body)
841 "Evaluate BODY forms on each inline source-block in FILE.
842 If FILE is nil evaluate BODY forms on source blocks in current
843 buffer."
844 (declare (indent 1))
845 (let ((tempvar (make-symbol "file")))
846 `(let* ((,tempvar ,file)
847 (visited-p (or (null ,tempvar)
848 (get-file-buffer (expand-file-name ,tempvar))))
849 (point (point)) to-be-removed)
850 (save-window-excursion
851 (when ,tempvar (find-file ,tempvar))
852 (setq to-be-removed (current-buffer))
853 (goto-char (point-min))
854 (while (re-search-forward org-babel-inline-src-block-regexp nil t)
855 (goto-char (match-beginning 1))
856 (save-match-data ,@body)
857 (goto-char (match-end 0))))
858 (unless visited-p (kill-buffer to-be-removed))
859 (goto-char point))))
860 (def-edebug-spec org-babel-map-inline-src-blocks (form body))
862 ;;;###autoload
863 (defun org-babel-execute-buffer (&optional arg)
864 "Execute source code blocks in a buffer.
865 Call `org-babel-execute-src-block' on every source block in
866 the current buffer."
867 (interactive "P")
868 (org-babel-eval-wipe-error-buffer)
869 (org-save-outline-visibility t
870 (org-babel-map-src-blocks nil
871 (org-babel-execute-src-block arg))
872 (org-babel-map-inline-src-blocks nil
873 (org-babel-execute-src-block arg))
874 (org-babel-map-call-lines nil
875 (org-babel-lob-execute-maybe))))
877 ;;;###autoload
878 (defun org-babel-execute-subtree (&optional arg)
879 "Execute source code blocks in a subtree.
880 Call `org-babel-execute-src-block' on every source block in
881 the current subtree."
882 (interactive "P")
883 (save-restriction
884 (save-excursion
885 (org-narrow-to-subtree)
886 (org-babel-execute-buffer arg)
887 (widen))))
889 ;;;###autoload
890 (defun org-babel-sha1-hash (&optional info)
891 "Generate an sha1 hash based on the value of info."
892 (interactive)
893 (let ((print-level nil)
894 (info (or info (org-babel-get-src-block-info))))
895 (setf (nth 2 info)
896 (sort (copy-sequence (nth 2 info))
897 (lambda (a b) (string< (car a) (car b)))))
898 (labels ((rm (lst)
899 (dolist (p '("replace" "silent" "append" "prepend"))
900 (setq lst (remove p lst)))
901 lst)
902 (norm (arg)
903 (let ((v (if (and (listp (cdr arg)) (null (cddr arg)))
904 (copy-sequence (cdr arg))
905 (cdr arg))))
906 (when (and v (not (and (sequencep v)
907 (not (consp v))
908 (= (length v) 0))))
909 (cond
910 ((and (listp v) ; lists are sorted
911 (member (car arg) '(:result-params)))
912 (sort (rm v) #'string<))
913 ((and (stringp v) ; strings are sorted
914 (member (car arg) '(:results :exports)))
915 (mapconcat #'identity (sort (rm (split-string v))
916 #'string<) " "))
917 (t v))))))
918 ((lambda (hash)
919 (when (org-called-interactively-p 'interactive) (message hash)) hash)
920 (let ((it (format "%s-%s"
921 (mapconcat
922 #'identity
923 (delq nil (mapcar (lambda (arg)
924 (let ((normalized (norm arg)))
925 (when normalized
926 (format "%S" normalized))))
927 (nth 2 info))) ":")
928 (nth 1 info))))
929 (sha1 it))))))
931 (defun org-babel-current-result-hash ()
932 "Return the in-buffer hash associated with INFO."
933 (org-babel-where-is-src-block-result)
934 (org-babel-clean-text-properties (match-string 3)))
936 (defun org-babel-hide-hash ()
937 "Hide the hash in the current results line.
938 Only the initial `org-babel-hash-show' characters of the hash
939 will remain visible."
940 (add-to-invisibility-spec '(org-babel-hide-hash . t))
941 (save-excursion
942 (when (and (re-search-forward org-babel-result-regexp nil t)
943 (match-string 3))
944 (let* ((start (match-beginning 3))
945 (hide-start (+ org-babel-hash-show start))
946 (end (match-end 3))
947 (hash (match-string 3))
948 ov1 ov2)
949 (setq ov1 (make-overlay start hide-start))
950 (setq ov2 (make-overlay hide-start end))
951 (overlay-put ov2 'invisible 'org-babel-hide-hash)
952 (overlay-put ov1 'babel-hash hash)))))
954 (defun org-babel-hide-all-hashes ()
955 "Hide the hash in the current buffer.
956 Only the initial `org-babel-hash-show' characters of each hash
957 will remain visible. This function should be called as part of
958 the `org-mode-hook'."
959 (save-excursion
960 (while (re-search-forward org-babel-result-regexp nil t)
961 (goto-char (match-beginning 0))
962 (org-babel-hide-hash)
963 (goto-char (match-end 0)))))
964 (add-hook 'org-mode-hook 'org-babel-hide-all-hashes)
966 (defun org-babel-hash-at-point (&optional point)
967 "Return the value of the hash at POINT.
968 The hash is also added as the last element of the kill ring.
969 This can be called with C-c C-c."
970 (interactive)
971 (let ((hash (car (delq nil (mapcar
972 (lambda (ol) (overlay-get ol 'babel-hash))
973 (overlays-at (or point (point))))))))
974 (when hash (kill-new hash) (message hash))))
975 (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-hash-at-point)
977 (defvar org-file-properties)
978 (defun org-babel-params-from-properties (&optional lang)
979 "Retrieve parameters specified as properties.
980 Return an association list of any source block params which
981 may be specified in the properties of the current outline entry."
982 (save-match-data
983 (let (val sym)
984 (org-babel-parse-multiple-vars
985 (delq nil
986 (mapcar
987 (lambda (header-arg)
988 (and (setq val (org-entry-get (point) header-arg t))
989 (cons (intern (concat ":" header-arg))
990 (org-babel-read val))))
991 (mapcar
992 'symbol-name
993 (append
994 org-babel-header-arg-names
995 (progn
996 (setq sym (intern (concat "org-babel-header-arg-names:"
997 lang)))
998 (and (boundp sym) (eval sym)))))))))))
1000 (defvar org-src-preserve-indentation)
1001 (defun org-babel-parse-src-block-match ()
1002 "Parse the results from a match of the `org-babel-src-block-regexp'."
1003 (let* ((block-indentation (length (match-string 1)))
1004 (lang (org-babel-clean-text-properties (match-string 2)))
1005 (lang-headers (intern (concat "org-babel-default-header-args:" lang)))
1006 (switches (match-string 3))
1007 (body (org-babel-clean-text-properties
1008 (let* ((body (match-string 5))
1009 (sub-length (- (length body) 1)))
1010 (if (and (> sub-length 0)
1011 (string= "\n" (substring body sub-length)))
1012 (substring body 0 sub-length)
1013 (or body "")))))
1014 (preserve-indentation (or org-src-preserve-indentation
1015 (string-match "-i\\>" switches))))
1016 (list lang
1017 ;; get block body less properties, protective commas, and indentation
1018 (with-temp-buffer
1019 (save-match-data
1020 (insert (org-babel-strip-protective-commas body))
1021 (unless preserve-indentation (org-do-remove-indentation))
1022 (buffer-string)))
1023 (org-babel-merge-params
1024 org-babel-default-header-args
1025 (org-babel-params-from-properties lang)
1026 (if (boundp lang-headers) (eval lang-headers) nil)
1027 (org-babel-parse-header-arguments
1028 (org-babel-clean-text-properties (or (match-string 4) ""))))
1029 switches
1030 block-indentation)))
1032 (defun org-babel-parse-inline-src-block-match ()
1033 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
1034 (let* ((lang (org-babel-clean-text-properties (match-string 2)))
1035 (lang-headers (intern (concat "org-babel-default-header-args:" lang))))
1036 (list lang
1037 (org-babel-strip-protective-commas
1038 (org-babel-clean-text-properties (match-string 5)))
1039 (org-babel-merge-params
1040 org-babel-default-inline-header-args
1041 (org-babel-params-from-properties lang)
1042 (if (boundp lang-headers) (eval lang-headers) nil)
1043 (org-babel-parse-header-arguments
1044 (org-babel-clean-text-properties (or (match-string 4) "")))))))
1046 (defun org-babel-balanced-split (string alts)
1047 "Split STRING on instances of ALTS.
1048 ALTS is a cons of two character options where each option may be
1049 either the numeric code of a single character or a list of
1050 character alternatives. For example to split on balanced
1051 instances of \"[ \t]:\" set ALTS to '((32 9) . 58)."
1052 (flet ((matches (ch spec) (or (and (numberp spec) (= spec ch))
1053 (member ch spec)))
1054 (matched (ch last)
1055 (if (consp alts)
1056 (and (matches ch (cdr alts))
1057 (matches last (car alts)))
1058 (matches ch alts))))
1059 (let ((balance 0) (quote nil) (partial nil) (lst nil) (last 0))
1060 (mapc (lambda (ch) ; split on [], (), "" balanced instances of [ \t]:
1061 (setq balance (+ balance
1062 (cond ((or (equal 91 ch) (equal 40 ch)) 1)
1063 ((or (equal 93 ch) (equal 41 ch)) -1)
1064 (t 0))))
1065 (when (and (equal 34 ch) (not (equal 92 last)))
1066 (setq quote (not quote)))
1067 (setq partial (cons ch partial))
1068 (when (and (= balance 0) (not quote) (matched ch last))
1069 (setq lst (cons (apply #'string (nreverse
1070 (if (consp alts)
1071 (cddr partial)
1072 (cdr partial))))
1073 lst))
1074 (setq partial nil))
1075 (setq last ch))
1076 (string-to-list string))
1077 (nreverse (cons (apply #'string (nreverse partial)) lst)))))
1079 (defun org-babel-join-splits-near-ch (ch list)
1080 "Join splits where \"=\" is on either end of the split."
1081 (flet ((last= (str) (= ch (aref str (1- (length str)))))
1082 (first= (str) (= ch (aref str 0))))
1083 (reverse
1084 (org-reduce (lambda (acc el)
1085 (let ((head (car acc)))
1086 (if (and head (or (last= head) (first= el)))
1087 (cons (concat head el) (cdr acc))
1088 (cons el acc))))
1089 list :initial-value nil))))
1091 (defun org-babel-parse-header-arguments (arg-string)
1092 "Parse a string of header arguments returning an alist."
1093 (when (> (length arg-string) 0)
1094 (org-babel-parse-multiple-vars
1095 (delq nil
1096 (mapcar
1097 (lambda (arg)
1098 (if (string-match
1099 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1100 arg)
1101 (cons (intern (match-string 1 arg))
1102 (org-babel-read (org-babel-chomp (match-string 2 arg))))
1103 (cons (intern (org-babel-chomp arg)) nil)))
1104 ((lambda (raw)
1105 (cons (car raw) (mapcar (lambda (r) (concat ":" r)) (cdr raw))))
1106 (org-babel-balanced-split arg-string '((32 9) . 58))))))))
1108 (defun org-babel-parse-multiple-vars (header-arguments)
1109 "Expand multiple variable assignments behind a single :var keyword.
1111 This allows expression of multiple variables with one :var as
1112 shown below.
1114 #+PROPERTY: var foo=1, bar=2"
1115 (let (results)
1116 (mapc (lambda (pair)
1117 (if (eq (car pair) :var)
1118 (mapcar (lambda (v) (push (cons :var (org-babel-trim v)) results))
1119 (org-babel-join-splits-near-ch
1120 61 (org-babel-balanced-split (cdr pair) 32)))
1121 (push pair results)))
1122 header-arguments)
1123 (nreverse results)))
1125 (defun org-babel-process-params (params)
1126 "Expand variables in PARAMS and add summary parameters."
1127 (let* ((processed-vars (mapcar (lambda (el)
1128 (if (consp (cdr el))
1129 (cdr el)
1130 (org-babel-ref-parse (cdr el))))
1131 (org-babel-get-header params :var)))
1132 (vars-and-names (if (and (assoc :colname-names params)
1133 (assoc :rowname-names params))
1134 (list processed-vars)
1135 (org-babel-disassemble-tables
1136 processed-vars
1137 (cdr (assoc :hlines params))
1138 (cdr (assoc :colnames params))
1139 (cdr (assoc :rownames params)))))
1140 (raw-result (or (cdr (assoc :results params)) ""))
1141 (result-params (append
1142 (split-string (if (stringp raw-result)
1143 raw-result
1144 (eval raw-result)))
1145 (cdr (assoc :result-params params)))))
1146 (append
1147 (mapcar (lambda (var) (cons :var var)) (car vars-and-names))
1148 (list
1149 (cons :colname-names (or (cdr (assoc :colname-names params))
1150 (cadr vars-and-names)))
1151 (cons :rowname-names (or (cdr (assoc :rowname-names params))
1152 (caddr vars-and-names)))
1153 (cons :result-params result-params)
1154 (cons :result-type (cond ((member "output" result-params) 'output)
1155 ((member "value" result-params) 'value)
1156 (t 'value))))
1157 (org-babel-get-header params :var 'other))))
1159 ;; row and column names
1160 (defun org-babel-del-hlines (table)
1161 "Remove all 'hlines from TABLE."
1162 (remove 'hline table))
1164 (defun org-babel-get-colnames (table)
1165 "Return the column names of TABLE.
1166 Return a cons cell, the `car' of which contains the TABLE less
1167 colnames, and the `cdr' of which contains a list of the column
1168 names."
1169 (if (equal 'hline (nth 1 table))
1170 (cons (cddr table) (car table))
1171 (cons (cdr table) (car table))))
1173 (defun org-babel-get-rownames (table)
1174 "Return the row names of TABLE.
1175 Return a cons cell, the `car' of which contains the TABLE less
1176 colnames, and the `cdr' of which contains a list of the column
1177 names. Note: this function removes any hlines in TABLE."
1178 (flet ((trans (table) (apply #'mapcar* #'list table)))
1179 (let* ((width (apply 'max
1180 (mapcar (lambda (el) (if (listp el) (length el) 0)) table)))
1181 (table (trans (mapcar (lambda (row)
1182 (if (not (equal row 'hline))
1184 (setq row '())
1185 (dotimes (n width)
1186 (setq row (cons 'hline row)))
1187 row))
1188 table))))
1189 (cons (mapcar (lambda (row) (if (equal (car row) 'hline) 'hline row))
1190 (trans (cdr table)))
1191 (remove 'hline (car table))))))
1193 (defun org-babel-put-colnames (table colnames)
1194 "Add COLNAMES to TABLE if they exist."
1195 (if colnames (apply 'list colnames 'hline table) table))
1197 (defun org-babel-put-rownames (table rownames)
1198 "Add ROWNAMES to TABLE if they exist."
1199 (if rownames
1200 (mapcar (lambda (row)
1201 (if (listp row)
1202 (cons (or (pop rownames) "") row)
1203 row)) table)
1204 table))
1206 (defun org-babel-pick-name (names selector)
1207 "Select one out of an alist of row or column names.
1208 SELECTOR can be either a list of names in which case those names
1209 will be returned directly, or an index into the list NAMES in
1210 which case the indexed names will be return."
1211 (if (listp selector)
1212 selector
1213 (when names
1214 (if (and selector (symbolp selector) (not (equal t selector)))
1215 (cdr (assoc selector names))
1216 (if (integerp selector)
1217 (nth (- selector 1) names)
1218 (cdr (car (last names))))))))
1220 (defun org-babel-disassemble-tables (vars hlines colnames rownames)
1221 "Parse tables for further processing.
1222 Process the variables in VARS according to the HLINES,
1223 ROWNAMES and COLNAMES header arguments. Return a list consisting
1224 of the vars, cnames and rnames."
1225 (let (cnames rnames)
1226 (list
1227 (mapcar
1228 (lambda (var)
1229 (when (listp (cdr var))
1230 (when (and (not (equal colnames "no"))
1231 (or colnames (and (equal (nth 1 (cdr var)) 'hline)
1232 (not (member 'hline (cddr (cdr var)))))))
1233 (let ((both (org-babel-get-colnames (cdr var))))
1234 (setq cnames (cons (cons (car var) (cdr both))
1235 cnames))
1236 (setq var (cons (car var) (car both)))))
1237 (when (and rownames (not (equal rownames "no")))
1238 (let ((both (org-babel-get-rownames (cdr var))))
1239 (setq rnames (cons (cons (car var) (cdr both))
1240 rnames))
1241 (setq var (cons (car var) (car both)))))
1242 (when (and hlines (not (equal hlines "yes")))
1243 (setq var (cons (car var) (org-babel-del-hlines (cdr var))))))
1244 var)
1245 vars)
1246 (reverse cnames) (reverse rnames))))
1248 (defun org-babel-reassemble-table (table colnames rownames)
1249 "Add column and row names to a table.
1250 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1251 to the table for reinsertion to org-mode."
1252 (if (listp table)
1253 ((lambda (table)
1254 (if (and colnames (listp (car table)) (= (length (car table))
1255 (length colnames)))
1256 (org-babel-put-colnames table colnames) table))
1257 (if (and rownames (= (length table) (length rownames)))
1258 (org-babel-put-rownames table rownames) table))
1259 table))
1261 (defun org-babel-where-is-src-block-head ()
1262 "Find where the current source block begins.
1263 Return the point at the beginning of the current source
1264 block. Specifically at the beginning of the #+BEGIN_SRC line.
1265 If the point is not on a source block then return nil."
1266 (let ((initial (point)) top bottom)
1268 (save-excursion ;; on a source name line or a #+header line
1269 (beginning-of-line 1)
1270 (and (or (looking-at org-babel-src-name-regexp)
1271 (looking-at org-babel-multi-line-header-regexp))
1272 (progn
1273 (while (and (forward-line 1)
1274 (looking-at org-babel-multi-line-header-regexp)))
1275 (looking-at org-babel-src-block-regexp))
1276 (point)))
1277 (save-excursion ;; on a #+begin_src line
1278 (beginning-of-line 1)
1279 (and (looking-at org-babel-src-block-regexp)
1280 (point)))
1281 (save-excursion ;; inside a src block
1282 (and
1283 (re-search-backward "^[ \t]*#\\+begin_src" nil t) (setq top (point))
1284 (re-search-forward "^[ \t]*#\\+end_src" nil t) (setq bottom (point))
1285 (< top initial) (< initial bottom)
1286 (progn (goto-char top) (beginning-of-line 1)
1287 (looking-at org-babel-src-block-regexp))
1288 (point))))))
1290 ;;;###autoload
1291 (defun org-babel-goto-src-block-head ()
1292 "Go to the beginning of the current code block."
1293 (interactive)
1294 ((lambda (head)
1295 (if head (goto-char head) (error "not currently in a code block")))
1296 (org-babel-where-is-src-block-head)))
1298 ;;;###autoload
1299 (defun org-babel-goto-named-src-block (name)
1300 "Go to a named source-code block."
1301 (interactive
1302 (let ((completion-ignore-case t))
1303 (list (org-icompleting-read "source-block name: "
1304 (org-babel-src-block-names) nil t))))
1305 (let ((point (org-babel-find-named-block name)))
1306 (if point
1307 ;; taken from `org-open-at-point'
1308 (progn (goto-char point) (org-show-context))
1309 (message "source-code block '%s' not found in this buffer" name))))
1311 (defun org-babel-find-named-block (name)
1312 "Find a named source-code block.
1313 Return the location of the source block identified by source
1314 NAME, or nil if no such block exists. Set match data according to
1315 org-babel-named-src-block-regexp."
1316 (save-excursion
1317 (let ((case-fold-search t)
1318 (regexp (org-babel-named-src-block-regexp-for-name name)) msg)
1319 (goto-char (point-min))
1320 (when (or (re-search-forward regexp nil t)
1321 (re-search-backward regexp nil t))
1322 (match-beginning 0)))))
1324 (defun org-babel-src-block-names (&optional file)
1325 "Returns the names of source blocks in FILE or the current buffer."
1326 (save-excursion
1327 (when file (find-file file)) (goto-char (point-min))
1328 (let (names)
1329 (while (re-search-forward org-babel-src-name-w-name-regexp nil t)
1330 (setq names (cons (match-string 3) names)))
1331 names)))
1333 ;;;###autoload
1334 (defun org-babel-goto-named-result (name)
1335 "Go to a named result."
1336 (interactive
1337 (let ((completion-ignore-case t))
1338 (list (org-icompleting-read "source-block name: "
1339 (org-babel-result-names) nil t))))
1340 (let ((point (org-babel-find-named-result name)))
1341 (if point
1342 ;; taken from `org-open-at-point'
1343 (progn (goto-char point) (org-show-context))
1344 (message "result '%s' not found in this buffer" name))))
1346 (defun org-babel-find-named-result (name &optional point)
1347 "Find a named result.
1348 Return the location of the result named NAME in the current
1349 buffer or nil if no such result exists."
1350 (save-excursion
1351 (goto-char (or point (point-min)))
1352 (catch 'is-a-code-block
1353 (when (re-search-forward
1354 (concat org-babel-result-regexp
1355 "[ \t]" (regexp-quote name) "[ \t\n\f\v\r]") nil t)
1356 (when (and (string= "name" (downcase (match-string 1)))
1357 (or (looking-at org-babel-src-block-regexp)
1358 (looking-at org-babel-multi-line-header-regexp)))
1359 (throw 'is-a-code-block (org-babel-find-named-result name (point))))
1360 (beginning-of-line 0) (point)))))
1362 (defun org-babel-result-names (&optional file)
1363 "Returns the names of results in FILE or the current buffer."
1364 (save-excursion
1365 (when file (find-file file)) (goto-char (point-min))
1366 (let (names)
1367 (while (re-search-forward org-babel-result-w-name-regexp nil t)
1368 (setq names (cons (match-string 4) names)))
1369 names)))
1371 ;;;###autoload
1372 (defun org-babel-next-src-block (&optional arg)
1373 "Jump to the next source block.
1374 With optional prefix argument ARG, jump forward ARG many source blocks."
1375 (interactive "P")
1376 (when (looking-at org-babel-src-block-regexp) (forward-char 1))
1377 (condition-case nil
1378 (re-search-forward org-babel-src-block-regexp nil nil (or arg 1))
1379 (error (error "No further code blocks")))
1380 (goto-char (match-beginning 0)) (org-show-context))
1382 ;;;###autoload
1383 (defun org-babel-previous-src-block (&optional arg)
1384 "Jump to the previous source block.
1385 With optional prefix argument ARG, jump backward ARG many source blocks."
1386 (interactive "P")
1387 (condition-case nil
1388 (re-search-backward org-babel-src-block-regexp nil nil (or arg 1))
1389 (error (error "No previous code blocks")))
1390 (goto-char (match-beginning 0)) (org-show-context))
1392 (defvar org-babel-load-languages)
1394 ;;;###autoload
1395 (defun org-babel-mark-block ()
1396 "Mark current src block"
1397 (interactive)
1398 ((lambda (head)
1399 (when head
1400 (save-excursion
1401 (goto-char head)
1402 (looking-at org-babel-src-block-regexp))
1403 (push-mark (match-end 5) nil t)
1404 (goto-char (match-beginning 5))))
1405 (org-babel-where-is-src-block-head)))
1407 (defun org-babel-demarcate-block (&optional arg)
1408 "Wrap or split the code in the region or on the point.
1409 When called from inside of a code block the current block is
1410 split. When called from outside of a code block a new code block
1411 is created. In both cases if the region is demarcated and if the
1412 region is not active then the point is demarcated."
1413 (interactive "P")
1414 (let ((info (org-babel-get-src-block-info 'light))
1415 (headers (progn (org-babel-where-is-src-block-head)
1416 (match-string 4)))
1417 (stars (concat (make-string (or (org-current-level) 1) ?*) " ")))
1418 (if info
1419 (mapc
1420 (lambda (place)
1421 (save-excursion
1422 (goto-char place)
1423 (let ((lang (nth 0 info))
1424 (indent (make-string (nth 5 info) ? )))
1425 (when (string-match "^[[:space:]]*$"
1426 (buffer-substring (point-at-bol)
1427 (point-at-eol)))
1428 (delete-region (point-at-bol) (point-at-eol)))
1429 (insert (concat
1430 (if (looking-at "^") "" "\n")
1431 indent "#+end_src\n"
1432 (if arg stars indent) "\n"
1433 indent "#+begin_src " lang
1434 (if (> (length headers) 1)
1435 (concat " " headers) headers)
1436 (if (looking-at "[\n\r]")
1438 (concat "\n" (make-string (current-column) ? )))))))
1439 (move-end-of-line 2))
1440 (sort (if (region-active-p) (list (mark) (point)) (list (point))) #'>))
1441 (let ((start (point))
1442 (lang (org-icompleting-read "Lang: "
1443 (mapcar (lambda (el) (symbol-name (car el)))
1444 org-babel-load-languages)))
1445 (body (delete-and-extract-region
1446 (if (region-active-p) (mark) (point)) (point))))
1447 (insert (concat (if (looking-at "^") "" "\n")
1448 (if arg (concat stars "\n") "")
1449 "#+begin_src " lang "\n"
1450 body
1451 (if (or (= (length body) 0)
1452 (string-match "[\r\n]$" body)) "" "\n")
1453 "#+end_src\n"))
1454 (goto-char start) (move-end-of-line 1)))))
1456 (defvar org-babel-lob-one-liner-regexp)
1457 (defun org-babel-where-is-src-block-result (&optional insert info hash indent)
1458 "Find where the current source block results begin.
1459 Return the point at the beginning of the result of the current
1460 source block. Specifically at the beginning of the results line.
1461 If no result exists for this block then create a results line
1462 following the source block."
1463 (save-excursion
1464 (let* ((on-lob-line (save-excursion
1465 (beginning-of-line 1)
1466 (looking-at org-babel-lob-one-liner-regexp)))
1467 (inlinep (when (org-babel-get-inline-src-block-matches)
1468 (match-end 0)))
1469 (name (if on-lob-line
1470 (nth 0 (org-babel-lob-get-info))
1471 (nth 4 (or info (org-babel-get-src-block-info 'light)))))
1472 (head (unless on-lob-line (org-babel-where-is-src-block-head)))
1473 found beg end)
1474 (when head (goto-char head))
1475 (setq
1476 found ;; was there a result (before we potentially insert one)
1478 inlinep
1479 (and
1480 ;; named results:
1481 ;; - return t if it is found, else return nil
1482 ;; - if it does not need to be rebuilt, then don't set end
1483 ;; - if it does need to be rebuilt then do set end
1484 name (setq beg (org-babel-find-named-result name))
1485 (prog1 beg
1486 (when (and hash (not (string= hash (match-string 3))))
1487 (goto-char beg) (setq end beg) ;; beginning of result
1488 (forward-line 1)
1489 (delete-region end (org-babel-result-end)) nil)))
1490 (and
1491 ;; unnamed results:
1492 ;; - return t if it is found, else return nil
1493 ;; - if it is found, and the hash doesn't match, delete and set end
1494 (or on-lob-line (re-search-forward "^[ \t]*#\\+end_src" nil t))
1495 (progn (end-of-line 1)
1496 (if (eobp) (insert "\n") (forward-char 1))
1497 (setq end (point))
1498 (or (and (not name)
1499 (progn ;; unnamed results line already exists
1500 (re-search-forward "[^ \f\t\n\r\v]" nil t)
1501 (beginning-of-line 1)
1502 (looking-at
1503 (concat org-babel-result-regexp "\n")))
1504 (prog1 (point)
1505 ;; must remove and rebuild if hash!=old-hash
1506 (if (and hash (not (string= hash (match-string 3))))
1507 (prog1 nil
1508 (forward-line 1)
1509 (delete-region
1510 end (org-babel-result-end)))
1511 (setq end nil)))))))))
1512 (if (and insert end)
1513 (progn
1514 (goto-char end)
1515 (unless beg
1516 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1517 (insert (concat
1518 (if indent
1519 (mapconcat
1520 (lambda (el) " ")
1521 (org-number-sequence 1 indent) "")
1523 "#+results"
1524 (when hash (concat "["hash"]"))
1526 (when name (concat " " name)) "\n"))
1527 (unless beg (insert "\n") (backward-char))
1528 (beginning-of-line 0)
1529 (if hash (org-babel-hide-hash))
1530 (point))
1531 found))))
1533 (defvar org-block-regexp)
1534 (defun org-babel-read-result ()
1535 "Read the result at `point' into emacs-lisp."
1536 (let ((case-fold-search t) result-string)
1537 (cond
1538 ((org-at-table-p) (org-babel-read-table))
1539 ((org-at-item-p) (org-babel-read-list))
1540 ((looking-at org-bracket-link-regexp) (org-babel-read-link))
1541 ((looking-at org-block-regexp) (org-babel-trim (match-string 4)))
1542 ((looking-at "^[ \t]*: ")
1543 (setq result-string
1544 (org-babel-trim
1545 (mapconcat (lambda (line)
1546 (if (and (> (length line) 1)
1547 (string-match "^[ \t]*: \\(.+\\)" line))
1548 (match-string 1 line)
1549 line))
1550 (split-string
1551 (buffer-substring
1552 (point) (org-babel-result-end)) "[\r\n]+")
1553 "\n")))
1554 (or (org-babel-number-p result-string) result-string))
1555 ((looking-at org-babel-result-regexp)
1556 (save-excursion (forward-line 1) (org-babel-read-result))))))
1558 (defun org-babel-read-table ()
1559 "Read the table at `point' into emacs-lisp."
1560 (mapcar (lambda (row)
1561 (if (and (symbolp row) (equal row 'hline)) row
1562 (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval)) row)))
1563 (org-table-to-lisp)))
1565 (defun org-babel-read-list ()
1566 "Read the list at `point' into emacs-lisp."
1567 (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval))
1568 (mapcar #'cadr (cdr (org-list-parse-list)))))
1570 (defvar org-link-types-re)
1571 (defun org-babel-read-link ()
1572 "Read the link at `point' into emacs-lisp.
1573 If the path of the link is a file path it is expanded using
1574 `expand-file-name'."
1575 (let* ((case-fold-search t)
1576 (raw (and (looking-at org-bracket-link-regexp)
1577 (org-babel-clean-text-properties (match-string 1))))
1578 (type (and (string-match org-link-types-re raw)
1579 (match-string 1 raw))))
1580 (cond
1581 ((not type) (expand-file-name raw))
1582 ((string= type "file")
1583 (and (string-match "file\\(.*\\):\\(.+\\)" raw)
1584 (expand-file-name (match-string 2 raw))))
1585 (t raw))))
1587 (defun org-babel-format-result (result &optional sep)
1588 "Format RESULT for writing to file."
1589 (flet ((echo-res (result)
1590 (if (stringp result) result (format "%S" result))))
1591 (if (listp result)
1592 ;; table result
1593 (orgtbl-to-generic
1594 result
1595 (list
1596 :sep (or sep "\t")
1597 :fmt 'echo-res))
1598 ;; scalar result
1599 (echo-res result))))
1601 (defun org-babel-insert-result
1602 (result &optional result-params info hash indent lang)
1603 "Insert RESULT into the current buffer.
1604 By default RESULT is inserted after the end of the
1605 current source block. With optional argument RESULT-PARAMS
1606 controls insertion of results in the org-mode file.
1607 RESULT-PARAMS can take the following values...
1609 replace - (default option) insert results after the source block
1610 replacing any previously inserted results
1612 silent -- no results are inserted
1614 file ---- the results are interpreted as a file path, and are
1615 inserted into the buffer using the Org-mode file syntax
1617 list ---- the results are interpreted as an Org-mode list.
1619 raw ----- results are added directly to the Org-mode file. This
1620 is a good option if you code block will output org-mode
1621 formatted text.
1623 wrap ---- results are added directly to the Org-mode file as with
1624 \"raw\", but are wrapped in a RESULTS drawer, allowing
1625 them to later be replaced or removed automatically.
1627 org ----- similar in effect to raw, only the results are wrapped
1628 in an org code block. Similar to the raw option, on
1629 export the results will be interpreted as org-formatted
1630 text, however by wrapping the results in an org code
1631 block they can be replaced upon re-execution of the
1632 code block.
1634 html ---- results are added inside of a #+BEGIN_HTML block. This
1635 is a good option if you code block will output html
1636 formatted text.
1638 latex --- results are added inside of a #+BEGIN_LATEX block.
1639 This is a good option if you code block will output
1640 latex formatted text.
1642 code ---- the results are extracted in the syntax of the source
1643 code of the language being evaluated and are added
1644 inside of a #+BEGIN_SRC block with the source-code
1645 language set appropriately. Note this relies on the
1646 optional LANG argument."
1647 (if (stringp result)
1648 (progn
1649 (setq result (org-babel-clean-text-properties result))
1650 (when (member "file" result-params)
1651 (setq result (org-babel-result-to-file result))))
1652 (unless (listp result) (setq result (format "%S" result))))
1653 (if (and result-params (member "silent" result-params))
1654 (progn
1655 (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
1656 result)
1657 (save-excursion
1658 (let* ((inlinep
1659 (save-excursion
1660 (when (or (org-babel-get-inline-src-block-matches)
1661 (org-babel-get-lob-one-liner-matches))
1662 (goto-char (match-end 0))
1663 (insert (if (listp result) "\n" " "))
1664 (point))))
1665 (existing-result (unless inlinep
1666 (org-babel-where-is-src-block-result
1667 t info hash indent)))
1668 (results-switches
1669 (cdr (assoc :results_switches (nth 2 info))))
1670 beg end)
1671 (when (and (stringp result) ; ensure results end in a newline
1672 (not inlinep)
1673 (> (length result) 0)
1674 (not (or (string-equal (substring result -1) "\n")
1675 (string-equal (substring result -1) "\r"))))
1676 (setq result (concat result "\n")))
1677 (if (not existing-result)
1678 (setq beg (or inlinep (point)))
1679 (goto-char existing-result)
1680 (save-excursion
1681 (re-search-forward "#" nil t)
1682 (setq indent (- (current-column) 1)))
1683 (forward-line 1)
1684 (setq beg (point))
1685 (cond
1686 ((member "replace" result-params)
1687 (delete-region (point) (org-babel-result-end)))
1688 ((member "append" result-params)
1689 (goto-char (org-babel-result-end)) (setq beg (point-marker)))
1690 ((member "prepend" result-params)))) ; already there
1691 (setq results-switches
1692 (if results-switches (concat " " results-switches) ""))
1693 (flet ((wrap (start finish)
1694 (goto-char beg) (insert (concat start "\n"))
1695 (goto-char end) (insert (concat finish "\n"))
1696 (setq end (point-marker)))
1697 (proper-list-p (it) (and (listp it) (null (cdr (last it))))))
1698 ;; insert results based on type
1699 (cond
1700 ;; do nothing for an empty result
1701 ((null result))
1702 ;; insert a list if preferred
1703 ((member "list" result-params)
1704 (insert
1705 (org-babel-trim
1706 (org-list-to-generic
1707 (cons 'unordered
1708 (mapcar
1709 (lambda (el) (list nil (if (stringp el) el (format "%S" el))))
1710 (if (listp result) result (list result))))
1711 '(:splicep nil :istart "- " :iend "\n")))
1712 "\n"))
1713 ;; assume the result is a table if it's not a string
1714 ((proper-list-p result)
1715 (goto-char beg)
1716 (insert (concat (orgtbl-to-orgtbl
1717 (if (or (eq 'hline (car result))
1718 (and (listp (car result))
1719 (listp (cdr (car result)))))
1720 result (list result))
1721 '(:fmt (lambda (cell) (format "%s" cell)))) "\n"))
1722 (goto-char beg) (when (org-at-table-p) (org-table-align)))
1723 ((and (listp result) (not (proper-list-p result)))
1724 (insert (format "%s\n" result)))
1725 ((member "file" result-params)
1726 (when inlinep (goto-char inlinep))
1727 (insert result))
1728 (t (goto-char beg) (insert result)))
1729 (when (proper-list-p result) (goto-char (org-table-end)))
1730 (setq end (point-marker))
1731 ;; possibly wrap result
1732 (cond
1733 ((member "html" result-params)
1734 (wrap "#+BEGIN_HTML" "#+END_HTML"))
1735 ((member "latex" result-params)
1736 (wrap "#+BEGIN_LaTeX" "#+END_LaTeX"))
1737 ((member "code" result-params)
1738 (wrap (format "#+BEGIN_SRC %s%s" (or lang "none") results-switches)
1739 "#+END_SRC"))
1740 ((member "org" result-params)
1741 (wrap "#+BEGIN_ORG" "#+END_ORG"))
1742 ((member "raw" result-params)
1743 (goto-char beg) (if (org-at-table-p) (org-cycle)))
1744 ((member "wrap" result-params)
1745 (wrap ":RESULTS:" ":END:"))
1746 ((and (not (proper-list-p result))
1747 (not (member "file" result-params)))
1748 (org-babel-examplize-region beg end results-switches)
1749 (setq end (point)))))
1750 ;; possibly indent the results to match the #+results line
1751 (when (and (not inlinep) (numberp indent) indent (> indent 0)
1752 ;; in this case `table-align' does the work for us
1753 (not (and (listp result)
1754 (member "append" result-params))))
1755 (indent-rigidly beg end indent))))
1756 (if (null result)
1757 (if (member "value" result-params)
1758 (message "Code block returned no value.")
1759 (message "Code block produced no output."))
1760 (message "Code block evaluation complete."))))
1762 (defun org-babel-remove-result (&optional info)
1763 "Remove the result of the current source block."
1764 (interactive)
1765 (let ((location (org-babel-where-is-src-block-result nil info)) start)
1766 (when location
1767 (setq start (- location 1))
1768 (save-excursion
1769 (goto-char location) (forward-line 1)
1770 (delete-region start (org-babel-result-end))))))
1772 (defun org-babel-result-end ()
1773 "Return the point at the end of the current set of results"
1774 (save-excursion
1775 (cond
1776 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
1777 ((org-at-item-p) (let* ((struct (org-list-struct))
1778 (prvs (org-list-prevs-alist struct)))
1779 (org-list-get-list-end (point-at-bol) struct prvs)))
1780 ((looking-at "^\\([ \t]*\\):RESULTS:")
1781 (re-search-forward (concat "^" (match-string 1) ":END:")))
1783 (let ((case-fold-search t)
1784 (blocks-re (regexp-opt
1785 (list "latex" "html" "example" "src" "result" "org"))))
1786 (if (looking-at (concat "[ \t]*#\\+begin_" blocks-re))
1787 (progn (re-search-forward (concat "[ \t]*#\\+end_" blocks-re) nil t)
1788 (forward-char 1))
1789 (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
1790 (forward-line 1))))
1791 (point)))))
1793 (defun org-babel-result-to-file (result)
1794 "Convert RESULT into an `org-mode' link.
1795 If the `default-directory' is different from the containing
1796 file's directory then expand relative links."
1797 (flet ((cond-exp (file)
1798 (if (and default-directory
1799 buffer-file-name
1800 (not (string= (expand-file-name default-directory)
1801 (expand-file-name
1802 (file-name-directory buffer-file-name)))))
1803 (expand-file-name file default-directory)
1804 file)))
1805 (if (stringp result)
1806 (format "[[file:%s]]" (cond-exp result))
1807 (when (and (listp result) (= 2 (length result))
1808 (stringp (car result)) (stringp (cadr result)))
1809 (format "[[file:%s][%s]]" (car result) (cadr result))))))
1811 (defun org-babel-examplize-region (beg end &optional results-switches)
1812 "Comment out region using the inline '==' or ': ' org example quote."
1813 (interactive "*r")
1814 (flet ((chars-between (b e) (string-match "[\\S]" (buffer-substring b e))))
1815 (if (or (chars-between (save-excursion (goto-char beg) (point-at-bol)) beg)
1816 (chars-between end (save-excursion (goto-char end) (point-at-eol))))
1817 (save-excursion
1818 (goto-char beg)
1819 (insert (format "=%s=" (prog1 (buffer-substring beg end)
1820 (delete-region beg end)))))
1821 (let ((size (count-lines beg end)))
1822 (save-excursion
1823 (cond ((= size 0)) ; do nothing for an empty result
1824 ((< size org-babel-min-lines-for-block-output)
1825 (goto-char beg)
1826 (dotimes (n size)
1827 (beginning-of-line 1) (insert ": ") (forward-line 1)))
1829 (goto-char beg)
1830 (insert (if results-switches
1831 (format "#+begin_example%s\n" results-switches)
1832 "#+begin_example\n"))
1833 (if (markerp end) (goto-char end) (forward-char (- end beg)))
1834 (insert "#+end_example\n"))))))))
1836 (defun org-babel-update-block-body (new-body)
1837 "Update the body of the current code block to NEW-BODY."
1838 (if (not (org-babel-where-is-src-block-head))
1839 (error "not in source block")
1840 (save-match-data
1841 (replace-match (concat (org-babel-trim new-body) "\n") nil t nil 5))
1842 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
1844 (defun org-babel-merge-params (&rest plists)
1845 "Combine all parameter association lists in PLISTS.
1846 Later elements of PLISTS override the values of previous elements.
1847 This takes into account some special considerations for certain
1848 parameters when merging lists."
1849 (let ((results-exclusive-groups
1850 (mapcar (lambda (group) (mapcar #'symbol-name group))
1851 (cdr (assoc 'results org-babel-common-header-args-w-values))))
1852 (exports-exclusive-groups
1853 (mapcar (lambda (group) (mapcar #'symbol-name group))
1854 (cdr (assoc 'exports org-babel-common-header-args-w-values))))
1855 (variable-index 0)
1856 params results exports tangle noweb cache vars shebang comments padline)
1857 (flet ((e-merge (exclusive-groups &rest result-params)
1858 ;; maintain exclusivity of mutually exclusive parameters
1859 (let (output)
1860 (mapc (lambda (new-params)
1861 (mapc (lambda (new-param)
1862 (mapc (lambda (exclusive-group)
1863 (when (member new-param exclusive-group)
1864 (mapcar (lambda (excluded-param)
1865 (setq output
1866 (delete
1867 excluded-param
1868 output)))
1869 exclusive-group)))
1870 exclusive-groups)
1871 (setq output (org-uniquify
1872 (cons new-param output))))
1873 new-params))
1874 result-params)
1875 output)))
1876 (mapc
1877 (lambda (plist)
1878 (mapc
1879 (lambda (pair)
1880 (case (car pair)
1881 (:var
1882 (let ((name (if (listp (cdr pair))
1883 (cadr pair)
1884 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
1885 (cdr pair))
1886 (intern (match-string 1 (cdr pair)))))))
1887 (if name
1888 (setq vars
1889 (append
1890 (if (member name (mapcar #'car vars))
1891 (delq nil
1892 (mapcar
1893 (lambda (p)
1894 (unless (equal (car p) name) p))
1895 vars))
1896 vars)
1897 (list (cons name pair))))
1898 ;; if no name is given and we already have named variables
1899 ;; then assign to named variables in order
1900 (if (and vars (nth variable-index vars))
1901 (prog1 (setf (cddr (nth variable-index vars))
1902 (concat (symbol-name
1903 (car (nth variable-index vars)))
1904 "=" (cdr pair)))
1905 (incf variable-index))
1906 (error "variable \"%s\" must be assigned a default value"
1907 (cdr pair))))))
1908 (:results
1909 (setq results (e-merge results-exclusive-groups
1910 results
1911 (split-string
1912 (let ((r (cdr pair)))
1913 (if (stringp r) r (eval r)))))))
1914 (:file
1915 (when (cdr pair)
1916 (setq results (e-merge results-exclusive-groups
1917 results '("file")))
1918 (unless (or (member "both" exports)
1919 (member "none" exports)
1920 (member "code" exports))
1921 (setq exports (e-merge exports-exclusive-groups
1922 exports '("results"))))
1923 (setq params (cons pair (assq-delete-all (car pair) params)))))
1924 (:exports
1925 (setq exports (e-merge exports-exclusive-groups
1926 exports (split-string (cdr pair)))))
1927 (:tangle ;; take the latest -- always overwrite
1928 (setq tangle (or (list (cdr pair)) tangle)))
1929 (:noweb
1930 (setq noweb (e-merge '(("yes" "no" "tangle")) noweb
1931 (split-string (or (cdr pair) "")))))
1932 (:cache
1933 (setq cache (e-merge '(("yes" "no")) cache
1934 (split-string (or (cdr pair) "")))))
1935 (:padline
1936 (setq padline (e-merge '(("yes" "no")) padline
1937 (split-string (or (cdr pair) "")))))
1938 (:shebang ;; take the latest -- always overwrite
1939 (setq shebang (or (list (cdr pair)) shebang)))
1940 (:comments
1941 (setq comments (e-merge '(("yes" "no")) comments
1942 (split-string (or (cdr pair) "")))))
1943 (t ;; replace: this covers e.g. :session
1944 (setq params (cons pair (assq-delete-all (car pair) params))))))
1945 plist))
1946 plists))
1947 (setq vars (reverse vars))
1948 (while vars (setq params (cons (cons :var (cddr (pop vars))) params)))
1949 (mapc
1950 (lambda (hd)
1951 (let ((key (intern (concat ":" (symbol-name hd))))
1952 (val (eval hd)))
1953 (setf params (cons (cons key (mapconcat 'identity val " ")) params))))
1954 '(results exports tangle noweb padline cache shebang comments))
1955 params))
1957 (defun org-babel-expand-noweb-references (&optional info parent-buffer)
1958 "Expand Noweb references in the body of the current source code block.
1960 For example the following reference would be replaced with the
1961 body of the source-code block named 'example-block'.
1963 <<example-block>>
1965 Note that any text preceding the <<foo>> construct on a line will
1966 be interposed between the lines of the replacement text. So for
1967 example if <<foo>> is placed behind a comment, then the entire
1968 replacement text will also be commented.
1970 This function must be called from inside of the buffer containing
1971 the source-code block which holds BODY.
1973 In addition the following syntax can be used to insert the
1974 results of evaluating the source-code block named 'example-block'.
1976 <<example-block()>>
1978 Any optional arguments can be passed to example-block by placing
1979 the arguments inside the parenthesis following the convention
1980 defined by `org-babel-lob'. For example
1982 <<example-block(a=9)>>
1984 would set the value of argument \"a\" equal to \"9\". Note that
1985 these arguments are not evaluated in the current source-code
1986 block but are passed literally to the \"example-block\"."
1987 (let* ((parent-buffer (or parent-buffer (current-buffer)))
1988 (info (or info (org-babel-get-src-block-info)))
1989 (lang (nth 0 info))
1990 (body (nth 1 info))
1991 (comment (string= "noweb" (cdr (assoc :comments (nth 2 info)))))
1992 (rx-prefix (concat "\\(" org-babel-src-name-regexp "\\|"
1993 ":noweb-ref[ \t]+" "\\)"))
1994 (new-body "") index source-name evaluate prefix blocks-in-buffer)
1995 (flet ((nb-add (text) (setq new-body (concat new-body text)))
1996 (c-wrap (text)
1997 (with-temp-buffer
1998 (funcall (intern (concat lang "-mode")))
1999 (comment-region (point) (progn (insert text) (point)))
2000 (org-babel-trim (buffer-string)))))
2001 (with-temp-buffer
2002 (insert body) (goto-char (point-min))
2003 (setq index (point))
2004 (while (and (re-search-forward "<<\\(.+?\\)>>" nil t))
2005 (save-match-data (setf source-name (match-string 1)))
2006 (save-match-data (setq evaluate (string-match "\(.*\)" source-name)))
2007 (save-match-data
2008 (setq prefix
2009 (buffer-substring (match-beginning 0)
2010 (save-excursion
2011 (beginning-of-line 1) (point)))))
2012 ;; add interval to new-body (removing noweb reference)
2013 (goto-char (match-beginning 0))
2014 (nb-add (buffer-substring index (point)))
2015 (goto-char (match-end 0))
2016 (setq index (point))
2017 (nb-add
2018 (with-current-buffer parent-buffer
2019 (mapconcat ;; interpose PREFIX between every line
2020 #'identity
2021 (split-string
2022 (if evaluate
2023 (let ((raw (org-babel-ref-resolve source-name)))
2024 (if (stringp raw) raw (format "%S" raw)))
2026 ;; retrieve from the library of babel
2027 (nth 2 (assoc (intern source-name)
2028 org-babel-library-of-babel))
2029 ;; return the contents of headlines literally
2030 (save-excursion
2031 (when (org-babel-ref-goto-headline-id source-name)
2032 (org-babel-ref-headline-body)))
2033 ;; find the expansion of reference in this buffer
2034 (let ((rx (concat rx-prefix source-name))
2035 expansion)
2036 (save-excursion
2037 (goto-char (point-min))
2038 (while (re-search-forward rx nil t)
2039 (let* ((i (org-babel-get-src-block-info 'light))
2040 (body (org-babel-expand-noweb-references i)))
2041 (if comment
2042 ((lambda (cs)
2043 (concat (c-wrap (car cs)) "\n"
2044 body "\n" (c-wrap (cadr cs))))
2045 (org-babel-tangle-comment-links i))
2046 (setq expansion (concat expansion body))))))
2047 expansion)
2048 ;; possibly raise an error if named block doesn't exist
2049 (if (member lang org-babel-noweb-error-langs)
2050 (error "%s" (concat
2051 "<<" source-name ">> "
2052 "could not be resolved (see "
2053 "`org-babel-noweb-error-langs')"))
2054 "")))
2055 "[\n\r]") (concat "\n" prefix)))))
2056 (nb-add (buffer-substring index (point-max)))))
2057 new-body))
2059 (defun org-babel-clean-text-properties (text)
2060 "Strip all properties from text return."
2061 (when text
2062 (set-text-properties 0 (length text) nil text) text))
2064 (defun org-babel-strip-protective-commas (body)
2065 "Strip protective commas from bodies of source blocks."
2066 (when body
2067 (replace-regexp-in-string "^,#" "#" body)))
2069 (defun org-babel-script-escape (str &optional force)
2070 "Safely convert tables into elisp lists."
2071 (let (in-single in-double out)
2072 ((lambda (escaped) (condition-case nil (org-babel-read escaped) (error escaped)))
2073 (if (or force
2074 (and (stringp str)
2075 (> (length str) 2)
2076 (or (and (string-equal "[" (substring str 0 1))
2077 (string-equal "]" (substring str -1)))
2078 (and (string-equal "{" (substring str 0 1))
2079 (string-equal "}" (substring str -1)))
2080 (and (string-equal "(" (substring str 0 1))
2081 (string-equal ")" (substring str -1))))))
2082 (org-babel-read
2083 (concat
2085 (progn
2086 (mapc
2087 (lambda (ch)
2088 (setq
2090 (case ch
2091 (91 (if (or in-double in-single) ; [
2092 (cons 91 out)
2093 (cons 40 out)))
2094 (93 (if (or in-double in-single) ; ]
2095 (cons 93 out)
2096 (cons 41 out)))
2097 (123 (if (or in-double in-single) ; {
2098 (cons 123 out)
2099 (cons 40 out)))
2100 (125 (if (or in-double in-single) ; }
2101 (cons 125 out)
2102 (cons 41 out)))
2103 (44 (if (or in-double in-single) ; ,
2104 (cons 44 out) (cons 32 out)))
2105 (39 (if in-double ; '
2106 (cons 39 out)
2107 (setq in-single (not in-single)) (cons 34 out)))
2108 (34 (if in-single ; "
2109 (append (list 34 32) out)
2110 (setq in-double (not in-double)) (cons 34 out)))
2111 (t (cons ch out)))))
2112 (string-to-list str))
2113 (apply #'string (reverse out)))))
2114 str))))
2116 (defun org-babel-read (cell &optional inhibit-lisp-eval)
2117 "Convert the string value of CELL to a number if appropriate.
2118 Otherwise if cell looks like lisp (meaning it starts with a
2119 \"(\", \"'\", \"`\" or a \"[\") then read it as lisp, otherwise
2120 return it unmodified as a string. Optional argument NO-LISP-EVAL
2121 inhibits lisp evaluation for situations in which is it not
2122 appropriate."
2123 (if (and (stringp cell) (not (equal cell "")))
2124 (or (org-babel-number-p cell)
2125 (if (and (not inhibit-lisp-eval)
2126 (member (substring cell 0 1) '("(" "'" "`" "[")))
2127 (eval (read cell))
2128 (if (string= (substring cell 0 1) "\"")
2129 (read cell)
2130 (progn (set-text-properties 0 (length cell) nil cell) cell))))
2131 cell))
2133 (defun org-babel-number-p (string)
2134 "If STRING represents a number return its value."
2135 (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string)
2136 (= (length (substring string (match-beginning 0)
2137 (match-end 0)))
2138 (length string)))
2139 (string-to-number string)))
2141 (defun org-babel-import-elisp-from-file (file-name &optional separator)
2142 "Read the results located at FILE-NAME into an elisp table.
2143 If the table is trivial, then return it as a scalar."
2144 (let (result)
2145 (save-window-excursion
2146 (with-temp-buffer
2147 (condition-case nil
2148 (progn
2149 (org-table-import file-name separator)
2150 (delete-file file-name)
2151 (setq result (mapcar (lambda (row)
2152 (mapcar #'org-babel-string-read row))
2153 (org-table-to-lisp))))
2154 (error nil)))
2155 (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
2156 (if (consp (car result))
2157 (if (null (cdr (car result)))
2158 (caar result)
2159 result)
2160 (car result))
2161 result))))
2163 (defun org-babel-string-read (cell)
2164 "Strip nested \"s from around strings."
2165 (org-babel-read (or (and (stringp cell)
2166 (string-match "\\\"\\(.+\\)\\\"" cell)
2167 (match-string 1 cell))
2168 cell)))
2170 (defun org-babel-reverse-string (string)
2171 "Return the reverse of STRING."
2172 (apply 'string (reverse (string-to-list string))))
2174 (defun org-babel-chomp (string &optional regexp)
2175 "Strip trailing spaces and carriage returns from STRING.
2176 Default regexp used is \"[ \f\t\n\r\v]\" but can be
2177 overwritten by specifying a regexp as a second argument."
2178 (let ((regexp (or regexp "[ \f\t\n\r\v]")))
2179 (while (and (> (length string) 0)
2180 (string-match regexp (substring string -1)))
2181 (setq string (substring string 0 -1)))
2182 string))
2184 (defun org-babel-trim (string &optional regexp)
2185 "Strip leading and trailing spaces and carriage returns from STRING.
2186 Like `org-babel-chomp' only it runs on both the front and back
2187 of the string."
2188 (org-babel-chomp (org-babel-reverse-string
2189 (org-babel-chomp (org-babel-reverse-string string) regexp))
2190 regexp))
2192 (defvar org-babel-org-babel-call-process-region-original nil)
2193 (defun org-babel-tramp-handle-call-process-region
2194 (start end program &optional delete buffer display &rest args)
2195 "Use tramp to handle call-process-region.
2196 Fixes a bug in `tramp-handle-call-process-region'."
2197 (if (and (featurep 'tramp) (file-remote-p default-directory))
2198 (let ((tmpfile (tramp-compat-make-temp-file "")))
2199 (write-region start end tmpfile)
2200 (when delete (delete-region start end))
2201 (unwind-protect
2202 ;; (apply 'call-process program tmpfile buffer display args)
2203 ;; bug in tramp
2204 (apply 'process-file program tmpfile buffer display args)
2205 (delete-file tmpfile)))
2206 ;; org-babel-call-process-region-original is the original emacs
2207 ;; definition. It is in scope from the let binding in
2208 ;; org-babel-execute-src-block
2209 (apply org-babel-call-process-region-original
2210 start end program delete buffer display args)))
2212 (defun org-babel-local-file-name (file)
2213 "Return the local name component of FILE."
2214 (if (file-remote-p file)
2215 (let (localname)
2216 (with-parsed-tramp-file-name file nil
2217 localname))
2218 file))
2220 (defun org-babel-process-file-name (name &optional no-quote-p)
2221 "Prepare NAME to be used in an external process.
2222 If NAME specifies a remote location, the remote portion of the
2223 name is removed, since in that case the process will be executing
2224 remotely. The file name is then processed by
2225 `expand-file-name'. Unless second argument NO-QUOTE-P is non-nil,
2226 the file name is additionally processed by
2227 `shell-quote-argument'"
2228 ((lambda (f) (if no-quote-p f (shell-quote-argument f)))
2229 (expand-file-name (org-babel-local-file-name name))))
2231 (defvar org-babel-temporary-directory)
2232 (unless (or noninteractive (boundp 'org-babel-temporary-directory))
2233 (defvar org-babel-temporary-directory
2234 (or (and (boundp 'org-babel-temporary-directory)
2235 (file-exists-p org-babel-temporary-directory)
2236 org-babel-temporary-directory)
2237 (make-temp-file "babel-" t))
2238 "Directory to hold temporary files created to execute code blocks.
2239 Used by `org-babel-temp-file'. This directory will be removed on
2240 Emacs shutdown."))
2242 (defun org-babel-temp-file (prefix &optional suffix)
2243 "Create a temporary file in the `org-babel-temporary-directory'.
2244 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2245 value of `temporary-file-directory' temporarily set to the value
2246 of `org-babel-temporary-directory'."
2247 (if (file-remote-p default-directory)
2248 (make-temp-file
2249 (concat (file-remote-p default-directory)
2250 (expand-file-name
2251 prefix temporary-file-directory)
2252 nil suffix))
2253 (let ((temporary-file-directory
2254 (or (and (boundp 'org-babel-temporary-directory)
2255 (file-exists-p org-babel-temporary-directory)
2256 org-babel-temporary-directory)
2257 temporary-file-directory)))
2258 (make-temp-file prefix nil suffix))))
2260 (defun org-babel-remove-temporary-directory ()
2261 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2262 (when (and (boundp 'org-babel-temporary-directory)
2263 (file-exists-p org-babel-temporary-directory))
2264 ;; taken from `delete-directory' in files.el
2265 (condition-case nil
2266 (progn
2267 (mapc (lambda (file)
2268 ;; This test is equivalent to
2269 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2270 ;; but more efficient
2271 (if (eq t (car (file-attributes file)))
2272 (delete-directory file)
2273 (delete-file file)))
2274 ;; We do not want to delete "." and "..".
2275 (directory-files org-babel-temporary-directory 'full
2276 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2277 (delete-directory org-babel-temporary-directory))
2278 (error
2279 (message "Failed to remove temporary Org-babel directory %s"
2280 (if (boundp 'org-babel-temporary-directory)
2281 org-babel-temporary-directory
2282 "[directory not defined]"))))))
2284 (add-hook 'kill-emacs-hook 'org-babel-remove-temporary-directory)
2286 (provide 'ob)
2290 ;;; ob.el ends here