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