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