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