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