Merge branch 'maint'
[org-mode.git] / lisp / ob-core.el
blob9baff0c80890d004e63aba72ac76fcf9b92ebb3c
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 nil))
615 (setq result
616 ((lambda (result)
617 (if (and (eq (cdr (assoc :result-type params))
618 'value)
619 (or (member "vector" result-params)
620 (member "table" result-params))
621 (not (listp result)))
622 (list (list result)) result))
623 (funcall cmd body params)))
624 ;; if non-empty result and :file then write to :file
625 (when (cdr (assoc :file params))
626 (when result
627 (with-temp-file (cdr (assoc :file params))
628 (insert
629 (org-babel-format-result
630 result (cdr (assoc :sep (nth 2 info)))))))
631 (setq result (cdr (assoc :file params))))
632 ;; possibly perform post process provided its appropriate
633 (when (cdr (assoc :post params))
634 (let ((*this* (if (cdr (assoc :file params))
635 (org-babel-result-to-file
636 (cdr (assoc :file params))
637 (when (assoc :file-desc params)
638 (or (cdr (assoc :file-desc params))
639 result)))
640 result)))
641 (setq result (org-babel-ref-resolve
642 (cdr (assoc :post params))))
643 (when (cdr (assoc :file params))
644 (setq result-params
645 (remove "file" result-params)))))
646 (org-babel-insert-result
647 result result-params info new-hash indent lang))
648 (run-hooks 'org-babel-after-execute-hook)
649 result)
650 (setq call-process-region
651 'org-babel-call-process-region-original)))))))))
653 (defun org-babel-expand-body:generic (body params &optional var-lines)
654 "Expand BODY with PARAMS.
655 Expand a block of code with org-babel according to its header
656 arguments. This generic implementation of body expansion is
657 called for languages which have not defined their own specific
658 org-babel-expand-body:lang function."
659 (mapconcat #'identity (append var-lines (list body)) "\n"))
661 ;;;###autoload
662 (defun org-babel-expand-src-block (&optional arg info params)
663 "Expand the current source code block.
664 Expand according to the source code block's header
665 arguments and pop open the results in a preview buffer."
666 (interactive)
667 (let* ((info (or info (org-babel-get-src-block-info)))
668 (lang (nth 0 info))
669 (params (setf (nth 2 info)
670 (sort (org-babel-merge-params (nth 2 info) params)
671 (lambda (el1 el2) (string< (symbol-name (car el1))
672 (symbol-name (car el2)))))))
673 (body (setf (nth 1 info)
674 (if (org-babel-noweb-p params :eval)
675 (org-babel-expand-noweb-references info) (nth 1 info))))
676 (expand-cmd (intern (concat "org-babel-expand-body:" lang)))
677 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
678 lang)))
679 (expanded
680 (if (fboundp expand-cmd) (funcall expand-cmd body params)
681 (org-babel-expand-body:generic
682 body params (and (fboundp assignments-cmd)
683 (funcall assignments-cmd params))))))
684 (if (org-called-interactively-p 'any)
685 (org-edit-src-code
686 nil expanded
687 (concat "*Org-Babel Preview " (buffer-name) "[ " lang " ]*"))
688 expanded)))
690 (defun org-babel-edit-distance (s1 s2)
691 "Return the edit (levenshtein) distance between strings S1 S2."
692 (let* ((l1 (length s1))
693 (l2 (length s2))
694 (dist (vconcat (mapcar (lambda (_) (make-vector (1+ l2) nil))
695 (number-sequence 1 (1+ l1)))))
696 (in (lambda (i j) (aref (aref dist i) j))))
697 (setf (aref (aref dist 0) 0) 0)
698 (dolist (j (number-sequence 1 l2))
699 (setf (aref (aref dist 0) j) j))
700 (dolist (i (number-sequence 1 l1))
701 (setf (aref (aref dist i) 0) i)
702 (dolist (j (number-sequence 1 l2))
703 (setf (aref (aref dist i) j)
704 (min
705 (1+ (funcall in (1- i) j))
706 (1+ (funcall in i (1- j)))
707 (+ (if (equal (aref s1 (1- i)) (aref s2 (1- j))) 0 1)
708 (funcall in (1- i) (1- j)))))))
709 (funcall in l1 l2)))
711 (defun org-babel-combine-header-arg-lists (original &rest others)
712 "Combine a number of lists of header argument names and arguments."
713 (let ((results (copy-sequence original)))
714 (dolist (new-list others)
715 (dolist (arg-pair new-list)
716 (let ((header (car arg-pair))
717 (args (cdr arg-pair)))
718 (setq results
719 (cons arg-pair (org-remove-if
720 (lambda (pair) (equal header (car pair)))
721 results))))))
722 results))
724 ;;;###autoload
725 (defun org-babel-check-src-block ()
726 "Check for misspelled header arguments in the current code block."
727 (interactive)
728 ;; TODO: report malformed code block
729 ;; TODO: report incompatible combinations of header arguments
730 ;; TODO: report uninitialized variables
731 (let ((too-close 2) ;; <- control closeness to report potential match
732 (names (mapcar #'symbol-name org-babel-header-arg-names)))
733 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg)) 1))
734 (and (org-babel-where-is-src-block-head)
735 (org-babel-parse-header-arguments
736 (org-no-properties
737 (match-string 4))))))
738 (dolist (name names)
739 (when (and (not (string= header name))
740 (<= (org-babel-edit-distance header name) too-close)
741 (not (member header names)))
742 (error "Supplied header \"%S\" is suspiciously close to \"%S\""
743 header name))))
744 (message "No suspicious header arguments found.")))
746 ;;;###autoload
747 (defun org-babel-insert-header-arg ()
748 "Insert a header argument selecting from lists of common args and values."
749 (interactive)
750 (let* ((lang (car (org-babel-get-src-block-info 'light)))
751 (lang-headers (intern (concat "org-babel-header-args:" lang)))
752 (headers (org-babel-combine-header-arg-lists
753 org-babel-common-header-args-w-values
754 (if (boundp lang-headers) (eval lang-headers) nil)))
755 (arg (org-icompleting-read
756 "Header Arg: "
757 (mapcar
758 (lambda (header-spec) (symbol-name (car header-spec)))
759 headers))))
760 (insert ":" arg)
761 (let ((vals (cdr (assoc (intern arg) headers))))
762 (when vals
763 (insert
765 (cond
766 ((eq vals :any)
767 (read-from-minibuffer "value: "))
768 ((listp vals)
769 (mapconcat
770 (lambda (group)
771 (let ((arg (org-icompleting-read
772 "value: "
773 (cons "default" (mapcar #'symbol-name group)))))
774 (if (and arg (not (string= "default" arg)))
775 (concat arg " ")
776 "")))
777 vals ""))))))))
779 ;; Add support for completing-read insertion of header arguments after ":"
780 (defun org-babel-header-arg-expand ()
781 "Call `org-babel-enter-header-arg-w-completion' in appropriate contexts."
782 (when (and (equal (char-before) ?\:) (org-babel-where-is-src-block-head))
783 (org-babel-enter-header-arg-w-completion (match-string 2))))
785 (defun org-babel-enter-header-arg-w-completion (&optional lang)
786 "Insert header argument appropriate for LANG with completion."
787 (let* ((lang-headers-var (intern (concat "org-babel-header-args:" lang)))
788 (lang-headers (when (boundp lang-headers-var) (eval lang-headers-var)))
789 (headers-w-values (org-babel-combine-header-arg-lists
790 org-babel-common-header-args-w-values lang-headers))
791 (headers (mapcar #'symbol-name (mapcar #'car headers-w-values)))
792 (header (org-completing-read "Header Arg: " headers))
793 (args (cdr (assoc (intern header) headers-w-values)))
794 (arg (when (and args (listp args))
795 (org-completing-read
796 (format "%s: " header)
797 (mapcar #'symbol-name (apply #'append args))))))
798 (insert (concat header " " (or arg "")))
799 (cons header arg)))
801 (add-hook 'org-tab-first-hook 'org-babel-header-arg-expand)
803 ;;;###autoload
804 (defun org-babel-load-in-session (&optional arg info)
805 "Load the body of the current source-code block.
806 Evaluate the header arguments for the source block before
807 entering the session. After loading the body this pops open the
808 session."
809 (interactive)
810 (let* ((info (or info (org-babel-get-src-block-info)))
811 (lang (nth 0 info))
812 (params (nth 2 info))
813 (body (if (not info)
814 (user-error "No src code block at point")
815 (setf (nth 1 info)
816 (if (org-babel-noweb-p params :eval)
817 (org-babel-expand-noweb-references info)
818 (nth 1 info)))))
819 (session (cdr (assoc :session params)))
820 (dir (cdr (assoc :dir params)))
821 (default-directory
822 (or (and dir (file-name-as-directory dir)) default-directory))
823 (cmd (intern (concat "org-babel-load-session:" lang))))
824 (unless (fboundp cmd)
825 (error "No org-babel-load-session function for %s!" lang))
826 (pop-to-buffer (funcall cmd session body params))
827 (end-of-line 1)))
829 ;;;###autoload
830 (defun org-babel-initiate-session (&optional arg info)
831 "Initiate session for current code block.
832 If called with a prefix argument then resolve any variable
833 references in the header arguments and assign these variables in
834 the session. Copy the body of the code block to the kill ring."
835 (interactive "P")
836 (let* ((info (or info (org-babel-get-src-block-info (not arg))))
837 (lang (nth 0 info))
838 (body (nth 1 info))
839 (params (nth 2 info))
840 (session (cdr (assoc :session params)))
841 (dir (cdr (assoc :dir params)))
842 (default-directory
843 (or (and dir (file-name-as-directory dir)) default-directory))
844 (init-cmd (intern (format "org-babel-%s-initiate-session" lang)))
845 (prep-cmd (intern (concat "org-babel-prep-session:" lang))))
846 (if (and (stringp session) (string= session "none"))
847 (error "This block is not using a session!"))
848 (unless (fboundp init-cmd)
849 (error "No org-babel-initiate-session function for %s!" lang))
850 (with-temp-buffer (insert (org-babel-trim body))
851 (copy-region-as-kill (point-min) (point-max)))
852 (when arg
853 (unless (fboundp prep-cmd)
854 (error "No org-babel-prep-session function for %s!" lang))
855 (funcall prep-cmd session params))
856 (funcall init-cmd session params)))
858 ;;;###autoload
859 (defun org-babel-switch-to-session (&optional arg info)
860 "Switch to the session of the current code block.
861 Uses `org-babel-initiate-session' to start the session. If called
862 with a prefix argument then this is passed on to
863 `org-babel-initiate-session'."
864 (interactive "P")
865 (pop-to-buffer (org-babel-initiate-session arg info))
866 (end-of-line 1))
868 (defalias 'org-babel-pop-to-session 'org-babel-switch-to-session)
870 ;;;###autoload
871 (defun org-babel-switch-to-session-with-code (&optional arg info)
872 "Switch to code buffer and display session."
873 (interactive "P")
874 (let ((swap-windows
875 (lambda ()
876 (let ((other-window-buffer (window-buffer (next-window))))
877 (set-window-buffer (next-window) (current-buffer))
878 (set-window-buffer (selected-window) other-window-buffer))
879 (other-window 1)))
880 (info (org-babel-get-src-block-info))
881 (org-src-window-setup 'reorganize-frame))
882 (save-excursion
883 (org-babel-switch-to-session arg info))
884 (org-edit-src-code)
885 (funcall swap-windows)))
887 (defmacro org-babel-do-in-edit-buffer (&rest body)
888 "Evaluate BODY in edit buffer if there is a code block at point.
889 Return t if a code block was found at point, nil otherwise."
890 `(let ((org-src-window-setup 'switch-invisibly))
891 (when (and (org-babel-where-is-src-block-head)
892 (org-edit-src-code nil nil nil))
893 (unwind-protect (progn ,@body)
894 (if (org-bound-and-true-p org-edit-src-from-org-mode)
895 (org-edit-src-exit)))
896 t)))
897 (def-edebug-spec org-babel-do-in-edit-buffer (body))
899 (defun org-babel-do-key-sequence-in-edit-buffer (key)
900 "Read key sequence and execute the command in edit buffer.
901 Enter a key sequence to be executed in the language major-mode
902 edit buffer. For example, TAB will alter the contents of the
903 Org-mode code block according to the effect of TAB in the
904 language major-mode buffer. For languages that support
905 interactive sessions, this can be used to send code from the Org
906 buffer to the session for evaluation using the native major-mode
907 evaluation mechanisms."
908 (interactive "kEnter key-sequence to execute in edit buffer: ")
909 (org-babel-do-in-edit-buffer
910 (call-interactively
911 (key-binding (or key (read-key-sequence nil))))))
913 (defvar org-bracket-link-regexp)
915 ;;;###autoload
916 (defun org-babel-open-src-block-result (&optional re-run)
917 "If `point' is on a src block then open the results of the
918 source code block, otherwise return nil. With optional prefix
919 argument RE-RUN the source-code block is evaluated even if
920 results already exist."
921 (interactive "P")
922 (let ((info (org-babel-get-src-block-info 'light)))
923 (when info
924 (save-excursion
925 ;; go to the results, if there aren't any then run the block
926 (goto-char (or (and (not re-run) (org-babel-where-is-src-block-result))
927 (progn (org-babel-execute-src-block)
928 (org-babel-where-is-src-block-result))))
929 (end-of-line 1)
930 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
931 ;; open the results
932 (if (looking-at org-bracket-link-regexp)
933 ;; file results
934 (org-open-at-point)
935 (let ((r (org-babel-format-result
936 (org-babel-read-result) (cdr (assoc :sep (nth 2 info))))))
937 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
938 (delete-region (point-min) (point-max))
939 (insert r)))
940 t))))
942 ;;;###autoload
943 (defmacro org-babel-map-src-blocks (file &rest body)
944 "Evaluate BODY forms on each source-block in FILE.
945 If FILE is nil evaluate BODY forms on source blocks in current
946 buffer. During evaluation of BODY the following local variables
947 are set relative to the currently matched code block.
949 full-block ------- string holding the entirety of the code block
950 beg-block -------- point at the beginning of the code block
951 end-block -------- point at the end of the matched code block
952 lang ------------- string holding the language of the code block
953 beg-lang --------- point at the beginning of the lang
954 end-lang --------- point at the end of the lang
955 switches --------- string holding the switches
956 beg-switches ----- point at the beginning of the switches
957 end-switches ----- point at the end of the switches
958 header-args ------ string holding the header-args
959 beg-header-args -- point at the beginning of the header-args
960 end-header-args -- point at the end of the header-args
961 body ------------- string holding the body of the code block
962 beg-body --------- point at the beginning of the body
963 end-body --------- point at the end of the body"
964 (declare (indent 1))
965 (let ((tempvar (make-symbol "file")))
966 `(let* ((,tempvar ,file)
967 (visited-p (or (null ,tempvar)
968 (get-file-buffer (expand-file-name ,tempvar))))
969 (point (point)) to-be-removed)
970 (save-window-excursion
971 (when ,tempvar (find-file ,tempvar))
972 (setq to-be-removed (current-buffer))
973 (goto-char (point-min))
974 (while (re-search-forward org-babel-src-block-regexp nil t)
975 (goto-char (match-beginning 0))
976 (let ((full-block (match-string 0))
977 (beg-block (match-beginning 0))
978 (end-block (match-end 0))
979 (lang (match-string 2))
980 (beg-lang (match-beginning 2))
981 (end-lang (match-end 2))
982 (switches (match-string 3))
983 (beg-switches (match-beginning 3))
984 (end-switches (match-end 3))
985 (header-args (match-string 4))
986 (beg-header-args (match-beginning 4))
987 (end-header-args (match-end 4))
988 (body (match-string 5))
989 (beg-body (match-beginning 5))
990 (end-body (match-end 5)))
991 ,@body
992 (goto-char end-block))))
993 (unless visited-p (kill-buffer to-be-removed))
994 (goto-char point))))
995 (def-edebug-spec org-babel-map-src-blocks (form body))
997 ;;;###autoload
998 (defmacro org-babel-map-inline-src-blocks (file &rest body)
999 "Evaluate BODY forms on each inline source-block in FILE.
1000 If FILE is nil evaluate BODY forms on source blocks in current
1001 buffer."
1002 (declare (indent 1))
1003 (let ((tempvar (make-symbol "file")))
1004 `(let* ((,tempvar ,file)
1005 (visited-p (or (null ,tempvar)
1006 (get-file-buffer (expand-file-name ,tempvar))))
1007 (point (point)) to-be-removed)
1008 (save-window-excursion
1009 (when ,tempvar (find-file ,tempvar))
1010 (setq to-be-removed (current-buffer))
1011 (goto-char (point-min))
1012 (while (re-search-forward org-babel-inline-src-block-regexp nil t)
1013 (goto-char (match-beginning 1))
1014 (save-match-data ,@body)
1015 (goto-char (match-end 0))))
1016 (unless visited-p (kill-buffer to-be-removed))
1017 (goto-char point))))
1018 (def-edebug-spec org-babel-map-inline-src-blocks (form body))
1020 (defvar org-babel-lob-one-liner-regexp)
1022 ;;;###autoload
1023 (defmacro org-babel-map-call-lines (file &rest body)
1024 "Evaluate BODY forms on each call line in FILE.
1025 If FILE is nil evaluate BODY forms on source blocks in current
1026 buffer."
1027 (declare (indent 1))
1028 (let ((tempvar (make-symbol "file")))
1029 `(let* ((,tempvar ,file)
1030 (visited-p (or (null ,tempvar)
1031 (get-file-buffer (expand-file-name ,tempvar))))
1032 (point (point)) to-be-removed)
1033 (save-window-excursion
1034 (when ,tempvar (find-file ,tempvar))
1035 (setq to-be-removed (current-buffer))
1036 (goto-char (point-min))
1037 (while (re-search-forward org-babel-lob-one-liner-regexp nil t)
1038 (goto-char (match-beginning 1))
1039 (save-match-data ,@body)
1040 (goto-char (match-end 0))))
1041 (unless visited-p (kill-buffer to-be-removed))
1042 (goto-char point))))
1043 (def-edebug-spec org-babel-map-call-lines (form body))
1045 ;;;###autoload
1046 (defmacro org-babel-map-executables (file &rest body)
1047 (declare (indent 1))
1048 (let ((tempvar (make-symbol "file"))
1049 (rx (make-symbol "rx")))
1050 `(let* ((,tempvar ,file)
1051 (,rx (concat "\\(" org-babel-src-block-regexp
1052 "\\|" org-babel-inline-src-block-regexp
1053 "\\|" org-babel-lob-one-liner-regexp "\\)"))
1054 (visited-p (or (null ,tempvar)
1055 (get-file-buffer (expand-file-name ,tempvar))))
1056 (point (point)) to-be-removed)
1057 (save-window-excursion
1058 (when ,tempvar (find-file ,tempvar))
1059 (setq to-be-removed (current-buffer))
1060 (goto-char (point-min))
1061 (while (re-search-forward ,rx nil t)
1062 (goto-char (match-beginning 1))
1063 (when (looking-at org-babel-inline-src-block-regexp)(forward-char 1))
1064 (save-match-data ,@body)
1065 (goto-char (match-end 0))))
1066 (unless visited-p (kill-buffer to-be-removed))
1067 (goto-char point))))
1068 (def-edebug-spec org-babel-map-executables (form body))
1070 ;;;###autoload
1071 (defun org-babel-execute-buffer (&optional arg)
1072 "Execute source code blocks in a buffer.
1073 Call `org-babel-execute-src-block' on every source block in
1074 the current buffer."
1075 (interactive "P")
1076 (org-babel-eval-wipe-error-buffer)
1077 (org-save-outline-visibility t
1078 (org-babel-map-executables nil
1079 (if (looking-at org-babel-lob-one-liner-regexp)
1080 (org-babel-lob-execute-maybe)
1081 (org-babel-execute-src-block arg)))))
1083 ;;;###autoload
1084 (defun org-babel-execute-subtree (&optional arg)
1085 "Execute source code blocks in a subtree.
1086 Call `org-babel-execute-src-block' on every source block in
1087 the current subtree."
1088 (interactive "P")
1089 (save-restriction
1090 (save-excursion
1091 (org-narrow-to-subtree)
1092 (org-babel-execute-buffer arg)
1093 (widen))))
1095 ;;;###autoload
1096 (defun org-babel-sha1-hash (&optional info)
1097 "Generate an sha1 hash based on the value of info."
1098 (interactive)
1099 (let ((print-level nil)
1100 (info (or info (org-babel-get-src-block-info))))
1101 (setf (nth 2 info)
1102 (sort (copy-sequence (nth 2 info))
1103 (lambda (a b) (string< (car a) (car b)))))
1104 (let* ((rm (lambda (lst)
1105 (dolist (p '("replace" "silent" "none"
1106 "append" "prepend"))
1107 (setq lst (remove p lst)))
1108 lst))
1109 (norm (lambda (arg)
1110 (let ((v (if (and (listp (cdr arg)) (null (cddr arg)))
1111 (copy-sequence (cdr arg))
1112 (cdr arg))))
1113 (when (and v (not (and (sequencep v)
1114 (not (consp v))
1115 (= (length v) 0))))
1116 (cond
1117 ((and (listp v) ; lists are sorted
1118 (member (car arg) '(:result-params)))
1119 (sort (funcall rm v) #'string<))
1120 ((and (stringp v) ; strings are sorted
1121 (member (car arg) '(:results :exports)))
1122 (mapconcat #'identity (sort (funcall rm (split-string v))
1123 #'string<) " "))
1124 (t v)))))))
1125 ((lambda (hash)
1126 (when (org-called-interactively-p 'interactive) (message hash)) hash)
1127 (let ((it (format "%s-%s"
1128 (mapconcat
1129 #'identity
1130 (delq nil (mapcar (lambda (arg)
1131 (let ((normalized (funcall norm arg)))
1132 (when normalized
1133 (format "%S" normalized))))
1134 (nth 2 info))) ":")
1135 (nth 1 info))))
1136 (sha1 it))))))
1138 (defun org-babel-current-result-hash ()
1139 "Return the current in-buffer hash."
1140 (org-babel-where-is-src-block-result)
1141 (org-no-properties (match-string 5)))
1143 (defun org-babel-set-current-result-hash (hash)
1144 "Set the current in-buffer hash to HASH."
1145 (org-babel-where-is-src-block-result)
1146 (save-excursion (goto-char (match-beginning 3))
1147 ;; (mapc #'delete-overlay (overlays-at (point)))
1148 (replace-match hash nil nil nil 3)
1149 (org-babel-hide-hash)))
1151 (defun org-babel-hide-hash ()
1152 "Hide the hash in the current results line.
1153 Only the initial `org-babel-hash-show' characters of the hash
1154 will remain visible."
1155 (add-to-invisibility-spec '(org-babel-hide-hash . t))
1156 (save-excursion
1157 (when (and (re-search-forward org-babel-result-regexp nil t)
1158 (match-string 5))
1159 (let* ((start (match-beginning 5))
1160 (hide-start (+ org-babel-hash-show start))
1161 (end (match-end 5))
1162 (hash (match-string 5))
1163 ov1 ov2)
1164 (setq ov1 (make-overlay start hide-start))
1165 (setq ov2 (make-overlay hide-start end))
1166 (overlay-put ov2 'invisible 'org-babel-hide-hash)
1167 (overlay-put ov1 'babel-hash hash)))))
1169 (defun org-babel-hide-all-hashes ()
1170 "Hide the hash in the current buffer.
1171 Only the initial `org-babel-hash-show' characters of each hash
1172 will remain visible. This function should be called as part of
1173 the `org-mode-hook'."
1174 (save-excursion
1175 (while (and (not org-babel-hash-show-time)
1176 (re-search-forward org-babel-result-regexp nil t))
1177 (goto-char (match-beginning 0))
1178 (org-babel-hide-hash)
1179 (goto-char (match-end 0)))))
1180 (add-hook 'org-mode-hook 'org-babel-hide-all-hashes)
1182 (defun org-babel-hash-at-point (&optional point)
1183 "Return the value of the hash at POINT.
1184 The hash is also added as the last element of the kill ring.
1185 This can be called with C-c C-c."
1186 (interactive)
1187 (let ((hash (car (delq nil (mapcar
1188 (lambda (ol) (overlay-get ol 'babel-hash))
1189 (overlays-at (or point (point))))))))
1190 (when hash (kill-new hash) (message hash))))
1191 (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-hash-at-point)
1193 (defun org-babel-result-hide-spec ()
1194 "Hide portions of results lines.
1195 Add `org-babel-hide-result' as an invisibility spec for hiding
1196 portions of results lines."
1197 (add-to-invisibility-spec '(org-babel-hide-result . t)))
1198 (add-hook 'org-mode-hook 'org-babel-result-hide-spec)
1200 (defvar org-babel-hide-result-overlays nil
1201 "Overlays hiding results.")
1203 (defun org-babel-result-hide-all ()
1204 "Fold all results in the current buffer."
1205 (interactive)
1206 (org-babel-show-result-all)
1207 (save-excursion
1208 (while (re-search-forward org-babel-result-regexp nil t)
1209 (save-excursion (goto-char (match-beginning 0))
1210 (org-babel-hide-result-toggle-maybe)))))
1212 (defun org-babel-show-result-all ()
1213 "Unfold all results in the current buffer."
1214 (mapc 'delete-overlay org-babel-hide-result-overlays)
1215 (setq org-babel-hide-result-overlays nil))
1217 ;;;###autoload
1218 (defun org-babel-hide-result-toggle-maybe ()
1219 "Toggle visibility of result at point."
1220 (interactive)
1221 (let ((case-fold-search t))
1222 (if (save-excursion
1223 (beginning-of-line 1)
1224 (looking-at org-babel-result-regexp))
1225 (progn (org-babel-hide-result-toggle)
1226 t) ;; to signal that we took action
1227 nil))) ;; to signal that we did not
1229 (defun org-babel-hide-result-toggle (&optional force)
1230 "Toggle the visibility of the current result."
1231 (interactive)
1232 (save-excursion
1233 (beginning-of-line)
1234 (if (re-search-forward org-babel-result-regexp nil t)
1235 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
1236 (end (progn
1237 (while (looking-at org-babel-multi-line-header-regexp)
1238 (forward-line 1))
1239 (goto-char (- (org-babel-result-end) 1)) (point)))
1241 (if (memq t (mapcar (lambda (overlay)
1242 (eq (overlay-get overlay 'invisible)
1243 'org-babel-hide-result))
1244 (overlays-at start)))
1245 (if (or (not force) (eq force 'off))
1246 (mapc (lambda (ov)
1247 (when (member ov org-babel-hide-result-overlays)
1248 (setq org-babel-hide-result-overlays
1249 (delq ov org-babel-hide-result-overlays)))
1250 (when (eq (overlay-get ov 'invisible)
1251 'org-babel-hide-result)
1252 (delete-overlay ov)))
1253 (overlays-at start)))
1254 (setq ov (make-overlay start end))
1255 (overlay-put ov 'invisible 'org-babel-hide-result)
1256 ;; make the block accessible to isearch
1257 (overlay-put
1258 ov 'isearch-open-invisible
1259 (lambda (ov)
1260 (when (member ov org-babel-hide-result-overlays)
1261 (setq org-babel-hide-result-overlays
1262 (delq ov org-babel-hide-result-overlays)))
1263 (when (eq (overlay-get ov 'invisible)
1264 'org-babel-hide-result)
1265 (delete-overlay ov))))
1266 (push ov org-babel-hide-result-overlays)))
1267 (error "Not looking at a result line"))))
1269 ;; org-tab-after-check-for-cycling-hook
1270 (add-hook 'org-tab-first-hook 'org-babel-hide-result-toggle-maybe)
1271 ;; Remove overlays when changing major mode
1272 (add-hook 'org-mode-hook
1273 (lambda () (org-add-hook 'change-major-mode-hook
1274 'org-babel-show-result-all 'append 'local)))
1276 (defvar org-file-properties)
1277 (defun org-babel-params-from-properties (&optional lang)
1278 "Retrieve parameters specified as properties.
1279 Return an association list of any source block params which
1280 may be specified in the properties of the current outline entry."
1281 (save-match-data
1282 (let (val sym)
1283 (org-babel-parse-multiple-vars
1284 (delq nil
1285 (mapcar
1286 (lambda (header-arg)
1287 (and (setq val (org-entry-get (point) header-arg t))
1288 (cons (intern (concat ":" header-arg))
1289 (org-babel-read val))))
1290 (mapcar
1291 #'symbol-name
1292 (mapcar
1293 #'car
1294 (org-babel-combine-header-arg-lists
1295 org-babel-common-header-args-w-values
1296 (progn
1297 (setq sym (intern (concat "org-babel-header-args:" lang)))
1298 (and (boundp sym) (eval sym))))))))))))
1300 (defvar org-src-preserve-indentation)
1301 (defun org-babel-parse-src-block-match ()
1302 "Parse the results from a match of the `org-babel-src-block-regexp'."
1303 (let* ((block-indentation (length (match-string 1)))
1304 (lang (org-no-properties (match-string 2)))
1305 (lang-headers (intern (concat "org-babel-default-header-args:" lang)))
1306 (switches (match-string 3))
1307 (body (org-no-properties
1308 (let* ((body (match-string 5))
1309 (sub-length (- (length body) 1)))
1310 (if (and (> sub-length 0)
1311 (string= "\n" (substring body sub-length)))
1312 (substring body 0 sub-length)
1313 (or body "")))))
1314 (preserve-indentation (or org-src-preserve-indentation
1315 (save-match-data
1316 (string-match "-i\\>" switches)))))
1317 (list lang
1318 ;; get block body less properties, protective commas, and indentation
1319 (with-temp-buffer
1320 (save-match-data
1321 (insert (org-unescape-code-in-string body))
1322 (unless preserve-indentation (org-do-remove-indentation))
1323 (buffer-string)))
1324 (org-babel-merge-params
1325 org-babel-default-header-args
1326 (org-babel-params-from-properties lang)
1327 (if (boundp lang-headers) (eval lang-headers) nil)
1328 (org-babel-parse-header-arguments
1329 (org-no-properties (or (match-string 4) ""))))
1330 switches
1331 block-indentation)))
1333 (defun org-babel-parse-inline-src-block-match ()
1334 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
1335 (let* ((lang (org-no-properties (match-string 2)))
1336 (lang-headers (intern (concat "org-babel-default-header-args:" lang))))
1337 (list lang
1338 (org-unescape-code-in-string (org-no-properties (match-string 5)))
1339 (org-babel-merge-params
1340 org-babel-default-inline-header-args
1341 (org-babel-params-from-properties lang)
1342 (if (boundp lang-headers) (eval lang-headers) nil)
1343 (org-babel-parse-header-arguments
1344 (org-no-properties (or (match-string 4) "")))))))
1346 (defun org-babel-balanced-split (string alts)
1347 "Split STRING on instances of ALTS.
1348 ALTS is a cons of two character options where each option may be
1349 either the numeric code of a single character or a list of
1350 character alternatives. For example to split on balanced
1351 instances of \"[ \t]:\" set ALTS to '((32 9) . 58)."
1352 (let* ((matches (lambda (ch spec) (if (listp spec) (member ch spec) (equal spec ch))))
1353 (matched (lambda (ch last)
1354 (if (consp alts)
1355 (and (funcall matches ch (cdr alts))
1356 (funcall matches last (car alts)))
1357 (funcall matches ch alts))))
1358 (balance 0) (last 0)
1359 quote partial lst)
1360 (mapc (lambda (ch) ; split on [], (), "" balanced instances of [ \t]:
1361 (setq balance (+ balance
1362 (cond ((or (equal 91 ch) (equal 40 ch)) 1)
1363 ((or (equal 93 ch) (equal 41 ch)) -1)
1364 (t 0))))
1365 (when (and (equal 34 ch) (not (equal 92 last)))
1366 (setq quote (not quote)))
1367 (setq partial (cons ch partial))
1368 (when (and (= balance 0) (not quote) (funcall matched ch last))
1369 (setq lst (cons (apply #'string (nreverse
1370 (if (consp alts)
1371 (cddr partial)
1372 (cdr partial))))
1373 lst))
1374 (setq partial nil))
1375 (setq last ch))
1376 (string-to-list string))
1377 (nreverse (cons (apply #'string (nreverse partial)) lst))))
1379 (defun org-babel-join-splits-near-ch (ch list)
1380 "Join splits where \"=\" is on either end of the split."
1381 (let ((last= (lambda (str) (= ch (aref str (1- (length str))))))
1382 (first= (lambda (str) (= ch (aref str 0)))))
1383 (reverse
1384 (org-reduce (lambda (acc el)
1385 (let ((head (car acc)))
1386 (if (and head (or (funcall last= head) (funcall first= el)))
1387 (cons (concat head el) (cdr acc))
1388 (cons el acc))))
1389 list :initial-value nil))))
1391 (defun org-babel-parse-header-arguments (arg-string)
1392 "Parse a string of header arguments returning an alist."
1393 (when (> (length arg-string) 0)
1394 (org-babel-parse-multiple-vars
1395 (delq nil
1396 (mapcar
1397 (lambda (arg)
1398 (if (string-match
1399 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1400 arg)
1401 (cons (intern (match-string 1 arg))
1402 (org-babel-read (org-babel-chomp (match-string 2 arg))))
1403 (cons (intern (org-babel-chomp arg)) nil)))
1404 ((lambda (raw)
1405 (cons (car raw) (mapcar (lambda (r) (concat ":" r)) (cdr raw))))
1406 (org-babel-balanced-split arg-string '((32 9) . 58))))))))
1408 (defun org-babel-parse-multiple-vars (header-arguments)
1409 "Expand multiple variable assignments behind a single :var keyword.
1411 This allows expression of multiple variables with one :var as
1412 shown below.
1414 #+PROPERTY: var foo=1, bar=2"
1415 (let (results)
1416 (mapc (lambda (pair)
1417 (if (eq (car pair) :var)
1418 (mapcar (lambda (v) (push (cons :var (org-babel-trim v)) results))
1419 (org-babel-join-splits-near-ch
1420 61 (org-babel-balanced-split (cdr pair) 32)))
1421 (push pair results)))
1422 header-arguments)
1423 (nreverse results)))
1425 (defun org-babel-process-params (params)
1426 "Expand variables in PARAMS and add summary parameters."
1427 (let* ((processed-vars (mapcar (lambda (el)
1428 (if (consp (cdr el))
1429 (cdr el)
1430 (org-babel-ref-parse (cdr el))))
1431 (org-babel-get-header params :var)))
1432 (vars-and-names (if (and (assoc :colname-names params)
1433 (assoc :rowname-names params))
1434 (list processed-vars)
1435 (org-babel-disassemble-tables
1436 processed-vars
1437 (cdr (assoc :hlines params))
1438 (cdr (assoc :colnames params))
1439 (cdr (assoc :rownames params)))))
1440 (raw-result (or (cdr (assoc :results params)) ""))
1441 (result-params (append
1442 (split-string (if (stringp raw-result)
1443 raw-result
1444 (eval raw-result)))
1445 (cdr (assoc :result-params params)))))
1446 (append
1447 (mapcar (lambda (var) (cons :var var)) (car vars-and-names))
1448 (list
1449 (cons :colname-names (or (cdr (assoc :colname-names params))
1450 (cadr vars-and-names)))
1451 (cons :rowname-names (or (cdr (assoc :rowname-names params))
1452 (caddr vars-and-names)))
1453 (cons :result-params result-params)
1454 (cons :result-type (cond ((member "output" result-params) 'output)
1455 ((member "value" result-params) 'value)
1456 (t 'value))))
1457 (org-babel-get-header params :var 'other))))
1459 ;; row and column names
1460 (defun org-babel-del-hlines (table)
1461 "Remove all 'hlines from TABLE."
1462 (remove 'hline table))
1464 (defun org-babel-get-colnames (table)
1465 "Return the column names of TABLE.
1466 Return a cons cell, the `car' of which contains the TABLE less
1467 colnames, and the `cdr' of which contains a list of the column
1468 names."
1469 (if (equal 'hline (nth 1 table))
1470 (cons (cddr table) (car table))
1471 (cons (cdr table) (car table))))
1473 (defun org-babel-get-rownames (table)
1474 "Return the row names of TABLE.
1475 Return a cons cell, the `car' of which contains the TABLE less
1476 colnames, and the `cdr' of which contains a list of the column
1477 names. Note: this function removes any hlines in TABLE."
1478 (let* ((trans (lambda (table) (apply #'mapcar* #'list table)))
1479 (width (apply 'max
1480 (mapcar (lambda (el) (if (listp el) (length el) 0)) table)))
1481 (table (funcall trans (mapcar (lambda (row)
1482 (if (not (equal row 'hline))
1484 (setq row '())
1485 (dotimes (n width)
1486 (setq row (cons 'hline row)))
1487 row))
1488 table))))
1489 (cons (mapcar (lambda (row) (if (equal (car row) 'hline) 'hline row))
1490 (funcall trans (cdr table)))
1491 (remove 'hline (car table)))))
1493 (defun org-babel-put-colnames (table colnames)
1494 "Add COLNAMES to TABLE if they exist."
1495 (if colnames (apply 'list colnames 'hline table) table))
1497 (defun org-babel-put-rownames (table rownames)
1498 "Add ROWNAMES to TABLE if they exist."
1499 (if rownames
1500 (mapcar (lambda (row)
1501 (if (listp row)
1502 (cons (or (pop rownames) "") row)
1503 row)) table)
1504 table))
1506 (defun org-babel-pick-name (names selector)
1507 "Select one out of an alist of row or column names.
1508 SELECTOR can be either a list of names in which case those names
1509 will be returned directly, or an index into the list NAMES in
1510 which case the indexed names will be return."
1511 (if (listp selector)
1512 selector
1513 (when names
1514 (if (and selector (symbolp selector) (not (equal t selector)))
1515 (cdr (assoc selector names))
1516 (if (integerp selector)
1517 (nth (- selector 1) names)
1518 (cdr (car (last names))))))))
1520 (defun org-babel-disassemble-tables (vars hlines colnames rownames)
1521 "Parse tables for further processing.
1522 Process the variables in VARS according to the HLINES,
1523 ROWNAMES and COLNAMES header arguments. Return a list consisting
1524 of the vars, cnames and rnames."
1525 (let (cnames rnames)
1526 (list
1527 (mapcar
1528 (lambda (var)
1529 (when (listp (cdr var))
1530 (when (and (not (equal colnames "no"))
1531 (or colnames (and (equal (nth 1 (cdr var)) 'hline)
1532 (not (member 'hline (cddr (cdr var)))))))
1533 (let ((both (org-babel-get-colnames (cdr var))))
1534 (setq cnames (cons (cons (car var) (cdr both))
1535 cnames))
1536 (setq var (cons (car var) (car both)))))
1537 (when (and rownames (not (equal rownames "no")))
1538 (let ((both (org-babel-get-rownames (cdr var))))
1539 (setq rnames (cons (cons (car var) (cdr both))
1540 rnames))
1541 (setq var (cons (car var) (car both)))))
1542 (when (and hlines (not (equal hlines "yes")))
1543 (setq var (cons (car var) (org-babel-del-hlines (cdr var))))))
1544 var)
1545 vars)
1546 (reverse cnames) (reverse rnames))))
1548 (defun org-babel-reassemble-table (table colnames rownames)
1549 "Add column and row names to a table.
1550 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1551 to the table for reinsertion to org-mode."
1552 (if (listp table)
1553 ((lambda (table)
1554 (if (and colnames (listp (car table)) (= (length (car table))
1555 (length colnames)))
1556 (org-babel-put-colnames table colnames) table))
1557 (if (and rownames (= (length table) (length rownames)))
1558 (org-babel-put-rownames table rownames) table))
1559 table))
1561 (defun org-babel-where-is-src-block-head ()
1562 "Find where the current source block begins.
1563 Return the point at the beginning of the current source
1564 block. Specifically at the beginning of the #+BEGIN_SRC line.
1565 If the point is not on a source block then return nil."
1566 (let ((initial (point)) (case-fold-search t) top bottom)
1568 (save-excursion ;; on a source name line or a #+header line
1569 (beginning-of-line 1)
1570 (and (or (looking-at org-babel-src-name-regexp)
1571 (looking-at org-babel-multi-line-header-regexp))
1572 (progn
1573 (while (and (forward-line 1)
1574 (or (looking-at org-babel-src-name-regexp)
1575 (looking-at org-babel-multi-line-header-regexp))))
1576 (looking-at org-babel-src-block-regexp))
1577 (point)))
1578 (save-excursion ;; on a #+begin_src line
1579 (beginning-of-line 1)
1580 (and (looking-at org-babel-src-block-regexp)
1581 (point)))
1582 (save-excursion ;; inside a src block
1583 (and
1584 (re-search-backward "^[ \t]*#\\+begin_src" nil t) (setq top (point))
1585 (re-search-forward "^[ \t]*#\\+end_src" nil t) (setq bottom (point))
1586 (< top initial) (< initial bottom)
1587 (progn (goto-char top) (beginning-of-line 1)
1588 (looking-at org-babel-src-block-regexp))
1589 (point))))))
1591 ;;;###autoload
1592 (defun org-babel-goto-src-block-head ()
1593 "Go to the beginning of the current code block."
1594 (interactive)
1595 ((lambda (head)
1596 (if head (goto-char head) (error "Not currently in a code block")))
1597 (org-babel-where-is-src-block-head)))
1599 ;;;###autoload
1600 (defun org-babel-goto-named-src-block (name)
1601 "Go to a named source-code block."
1602 (interactive
1603 (let ((completion-ignore-case t)
1604 (case-fold-search t)
1605 (under-point (thing-at-point 'line)))
1606 (list (org-icompleting-read
1607 "source-block name: " (org-babel-src-block-names) nil t
1608 (cond
1609 ;; noweb
1610 ((string-match (org-babel-noweb-wrap) under-point)
1611 (let ((block-name (match-string 1 under-point)))
1612 (string-match "[^(]*" block-name)
1613 (match-string 0 block-name)))
1614 ;; #+call:
1615 ((string-match org-babel-lob-one-liner-regexp under-point)
1616 (let ((source-info (car (org-babel-lob-get-info))))
1617 (if (string-match "^\\([^\\[]+?\\)\\(\\[.*\\]\\)?(" source-info)
1618 (let ((source-name (match-string 1 source-info)))
1619 source-name))))
1620 ;; #+results:
1621 ((string-match (concat "#\\+" org-babel-results-keyword
1622 "\\:\s+\\([^\\(]*\\)") under-point)
1623 (match-string 1 under-point))
1624 ;; symbol-at-point
1625 ((and (thing-at-point 'symbol))
1626 (org-babel-find-named-block (thing-at-point 'symbol))
1627 (thing-at-point 'symbol))
1628 (""))))))
1629 (let ((point (org-babel-find-named-block name)))
1630 (if point
1631 ;; taken from `org-open-at-point'
1632 (progn (org-mark-ring-push) (goto-char point) (org-show-context))
1633 (message "source-code block '%s' not found in this buffer" name))))
1635 (defun org-babel-find-named-block (name)
1636 "Find a named source-code block.
1637 Return the location of the source block identified by source
1638 NAME, or nil if no such block exists. Set match data according to
1639 org-babel-named-src-block-regexp."
1640 (save-excursion
1641 (let ((case-fold-search t)
1642 (regexp (org-babel-named-src-block-regexp-for-name name)) msg)
1643 (goto-char (point-min))
1644 (when (or (re-search-forward regexp nil t)
1645 (re-search-backward regexp nil t))
1646 (match-beginning 0)))))
1648 (defun org-babel-src-block-names (&optional file)
1649 "Returns the names of source blocks in FILE or the current buffer."
1650 (save-excursion
1651 (when file (find-file file)) (goto-char (point-min))
1652 (let ((case-fold-search t) names)
1653 (while (re-search-forward org-babel-src-name-w-name-regexp nil t)
1654 (setq names (cons (match-string 3) names)))
1655 names)))
1657 ;;;###autoload
1658 (defun org-babel-goto-named-result (name)
1659 "Go to a named result."
1660 (interactive
1661 (let ((completion-ignore-case t))
1662 (list (org-icompleting-read "source-block name: "
1663 (org-babel-result-names) nil t))))
1664 (let ((point (org-babel-find-named-result name)))
1665 (if point
1666 ;; taken from `org-open-at-point'
1667 (progn (goto-char point) (org-show-context))
1668 (message "result '%s' not found in this buffer" name))))
1670 (defun org-babel-find-named-result (name &optional point)
1671 "Find a named result.
1672 Return the location of the result named NAME in the current
1673 buffer or nil if no such result exists."
1674 (save-excursion
1675 (let ((case-fold-search t))
1676 (goto-char (or point (point-min)))
1677 (catch 'is-a-code-block
1678 (when (re-search-forward
1679 (concat org-babel-result-regexp
1680 "[ \t]" (regexp-quote name) "[ \t]*[\n\f\v\r]") nil t)
1681 (when (and (string= "name" (downcase (match-string 1)))
1682 (or (beginning-of-line 1)
1683 (looking-at org-babel-src-block-regexp)
1684 (looking-at org-babel-multi-line-header-regexp)))
1685 (throw 'is-a-code-block (org-babel-find-named-result name (point))))
1686 (beginning-of-line 0) (point))))))
1688 (defun org-babel-result-names (&optional file)
1689 "Returns the names of results in FILE or the current buffer."
1690 (save-excursion
1691 (when file (find-file file)) (goto-char (point-min))
1692 (let ((case-fold-search t) names)
1693 (while (re-search-forward org-babel-result-w-name-regexp nil t)
1694 (setq names (cons (match-string 4) names)))
1695 names)))
1697 ;;;###autoload
1698 (defun org-babel-next-src-block (&optional arg)
1699 "Jump to the next source block.
1700 With optional prefix argument ARG, jump forward ARG many source blocks."
1701 (interactive "p")
1702 (org-next-block arg nil org-babel-src-block-regexp))
1704 ;;;###autoload
1705 (defun org-babel-previous-src-block (&optional arg)
1706 "Jump to the previous source block.
1707 With optional prefix argument ARG, jump backward ARG many source blocks."
1708 (interactive "p")
1709 (org-previous-block arg org-babel-src-block-regexp))
1711 (defvar org-babel-load-languages)
1713 ;;;###autoload
1714 (defun org-babel-mark-block ()
1715 "Mark current src block."
1716 (interactive)
1717 ((lambda (head)
1718 (when head
1719 (save-excursion
1720 (goto-char head)
1721 (looking-at org-babel-src-block-regexp))
1722 (push-mark (match-end 5) nil t)
1723 (goto-char (match-beginning 5))))
1724 (org-babel-where-is-src-block-head)))
1726 (defun org-babel-demarcate-block (&optional arg)
1727 "Wrap or split the code in the region or on the point.
1728 When called from inside of a code block the current block is
1729 split. When called from outside of a code block a new code block
1730 is created. In both cases if the region is demarcated and if the
1731 region is not active then the point is demarcated."
1732 (interactive "P")
1733 (let ((info (org-babel-get-src-block-info 'light))
1734 (headers (progn (org-babel-where-is-src-block-head)
1735 (match-string 4)))
1736 (stars (concat (make-string (or (org-current-level) 1) ?*) " ")))
1737 (if info
1738 (mapc
1739 (lambda (place)
1740 (save-excursion
1741 (goto-char place)
1742 (let ((lang (nth 0 info))
1743 (indent (make-string (nth 5 info) ? )))
1744 (when (string-match "^[[:space:]]*$"
1745 (buffer-substring (point-at-bol)
1746 (point-at-eol)))
1747 (delete-region (point-at-bol) (point-at-eol)))
1748 (insert (concat
1749 (if (looking-at "^") "" "\n")
1750 indent "#+end_src\n"
1751 (if arg stars indent) "\n"
1752 indent "#+begin_src " lang
1753 (if (> (length headers) 1)
1754 (concat " " headers) headers)
1755 (if (looking-at "[\n\r]")
1757 (concat "\n" (make-string (current-column) ? )))))))
1758 (move-end-of-line 2))
1759 (sort (if (org-region-active-p) (list (mark) (point)) (list (point))) #'>))
1760 (let ((start (point))
1761 (lang (org-icompleting-read "Lang: "
1762 (mapcar (lambda (el) (symbol-name (car el)))
1763 org-babel-load-languages)))
1764 (body (delete-and-extract-region
1765 (if (org-region-active-p) (mark) (point)) (point))))
1766 (insert (concat (if (looking-at "^") "" "\n")
1767 (if arg (concat stars "\n") "")
1768 "#+begin_src " lang "\n"
1769 body
1770 (if (or (= (length body) 0)
1771 (string-match "[\r\n]$" body)) "" "\n")
1772 "#+end_src\n"))
1773 (goto-char start) (move-end-of-line 1)))))
1775 (defvar org-babel-lob-one-liner-regexp)
1776 (defun org-babel-where-is-src-block-result (&optional insert info hash indent)
1777 "Find where the current source block results begin.
1778 Return the point at the beginning of the result of the current
1779 source block. Specifically at the beginning of the results line.
1780 If no result exists for this block then create a results line
1781 following the source block."
1782 (save-excursion
1783 (let* ((case-fold-search t)
1784 (on-lob-line (save-excursion
1785 (beginning-of-line 1)
1786 (looking-at org-babel-lob-one-liner-regexp)))
1787 (inlinep (when (org-babel-get-inline-src-block-matches)
1788 (match-end 0)))
1789 (name (if on-lob-line
1790 (mapconcat #'identity (butlast (org-babel-lob-get-info))
1792 (nth 4 (or info (org-babel-get-src-block-info 'light)))))
1793 (head (unless on-lob-line (org-babel-where-is-src-block-head)))
1794 found beg end)
1795 (when head (goto-char head))
1796 (org-with-wide-buffer
1797 (setq
1798 found ;; was there a result (before we potentially insert one)
1800 inlinep
1801 (and
1802 ;; named results:
1803 ;; - return t if it is found, else return nil
1804 ;; - if it does not need to be rebuilt, then don't set end
1805 ;; - if it does need to be rebuilt then do set end
1806 name (setq beg (org-babel-find-named-result name))
1807 (prog1 beg
1808 (when (and hash (not (string= hash (match-string 5))))
1809 (goto-char beg) (setq end beg) ;; beginning of result
1810 (forward-line 1)
1811 (delete-region end (org-babel-result-end)) nil)))
1812 (and
1813 ;; unnamed results:
1814 ;; - return t if it is found, else return nil
1815 ;; - if it is found, and the hash doesn't match, delete and set end
1816 (or on-lob-line (re-search-forward "^[ \t]*#\\+end_src" nil t))
1817 (progn (end-of-line 1)
1818 (if (eobp) (insert "\n") (forward-char 1))
1819 (setq end (point))
1820 (or (and
1821 (not name)
1822 (progn ;; unnamed results line already exists
1823 (catch 'non-comment
1824 (while (re-search-forward "[^ \f\t\n\r\v]" nil t)
1825 (beginning-of-line 1)
1826 (cond
1827 ((looking-at (concat org-babel-result-regexp "\n"))
1828 (throw 'non-comment t))
1829 ((looking-at "^[ \t]*#") (end-of-line 1))
1830 (t (throw 'non-comment nil))))))
1831 (let ((this-hash (match-string 5)))
1832 (prog1 (point)
1833 ;; must remove and rebuild if hash!=old-hash
1834 (if (and hash (not (string= hash this-hash)))
1835 (prog1 nil
1836 (forward-line 1)
1837 (delete-region
1838 end (org-babel-result-end)))
1839 (setq end nil)))))))))))
1840 (if (not (and insert end)) found
1841 (goto-char end)
1842 (unless beg
1843 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1844 (insert (concat
1845 (when (wholenump indent) (make-string indent ? ))
1846 "#+" org-babel-results-keyword
1847 (when hash
1848 (if org-babel-hash-show-time
1849 (concat
1850 "["(format-time-string "<%Y-%m-%d %H:%M:%S>")" "hash"]")
1851 (concat "["hash"]")))
1853 (when name (concat " " name)) "\n"))
1854 (unless beg (insert "\n") (backward-char))
1855 (beginning-of-line 0)
1856 (if hash (org-babel-hide-hash))
1857 (point)))))
1859 (defvar org-block-regexp)
1860 (defun org-babel-read-result ()
1861 "Read the result at `point' into emacs-lisp."
1862 (let ((case-fold-search t) result-string)
1863 (cond
1864 ((org-at-table-p) (org-babel-read-table))
1865 ((org-at-item-p) (org-babel-read-list))
1866 ((looking-at org-bracket-link-regexp) (org-babel-read-link))
1867 ((looking-at org-block-regexp) (org-babel-trim (match-string 4)))
1868 ((looking-at "^[ \t]*: ")
1869 (setq result-string
1870 (org-babel-trim
1871 (mapconcat (lambda (line)
1872 (if (and (> (length line) 1)
1873 (string-match "^[ \t]*: \\(.+\\)" line))
1874 (match-string 1 line)
1875 line))
1876 (split-string
1877 (buffer-substring
1878 (point) (org-babel-result-end)) "[\r\n]+")
1879 "\n")))
1880 (or (org-babel-number-p result-string) result-string))
1881 ((looking-at org-babel-result-regexp)
1882 (save-excursion (forward-line 1) (org-babel-read-result))))))
1884 (defun org-babel-read-table ()
1885 "Read the table at `point' into emacs-lisp."
1886 (mapcar (lambda (row)
1887 (if (and (symbolp row) (equal row 'hline)) row
1888 (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval)) row)))
1889 (org-table-to-lisp)))
1891 (defun org-babel-read-list ()
1892 "Read the list at `point' into emacs-lisp."
1893 (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval))
1894 (mapcar #'cadr (cdr (org-list-parse-list)))))
1896 (defvar org-link-types-re)
1897 (defun org-babel-read-link ()
1898 "Read the link at `point' into emacs-lisp.
1899 If the path of the link is a file path it is expanded using
1900 `expand-file-name'."
1901 (let* ((case-fold-search t)
1902 (raw (and (looking-at org-bracket-link-regexp)
1903 (org-no-properties (match-string 1))))
1904 (type (and (string-match org-link-types-re raw)
1905 (match-string 1 raw))))
1906 (cond
1907 ((not type) (expand-file-name raw))
1908 ((string= type "file")
1909 (and (string-match "file\\(.*\\):\\(.+\\)" raw)
1910 (expand-file-name (match-string 2 raw))))
1911 (t raw))))
1913 (defun org-babel-format-result (result &optional sep)
1914 "Format RESULT for writing to file."
1915 (let ((echo-res (lambda (r) (if (stringp r) r (format "%S" r)))))
1916 (if (listp result)
1917 ;; table result
1918 (orgtbl-to-generic
1919 result (list :sep (or sep "\t") :fmt echo-res))
1920 ;; scalar result
1921 (funcall echo-res result))))
1923 (defun org-babel-insert-result
1924 (result &optional result-params info hash indent lang)
1925 "Insert RESULT into the current buffer.
1926 By default RESULT is inserted after the end of the
1927 current source block. With optional argument RESULT-PARAMS
1928 controls insertion of results in the org-mode file.
1929 RESULT-PARAMS can take the following values:
1931 replace - (default option) insert results after the source block
1932 replacing any previously inserted results
1934 silent -- no results are inserted into the Org-mode buffer but
1935 the results are echoed to the minibuffer and are
1936 ingested by Emacs (a potentially time consuming
1937 process)
1939 file ---- the results are interpreted as a file path, and are
1940 inserted into the buffer using the Org-mode file syntax
1942 list ---- the results are interpreted as an Org-mode list.
1944 raw ----- results are added directly to the Org-mode file. This
1945 is a good option if you code block will output org-mode
1946 formatted text.
1948 drawer -- results are added directly to the Org-mode file as with
1949 \"raw\", but are wrapped in a RESULTS drawer, allowing
1950 them to later be replaced or removed automatically.
1952 org ----- results are added inside of a \"#+BEGIN_SRC org\" block.
1953 They are not comma-escaped when inserted, but Org syntax
1954 here will be discarded when exporting the file.
1956 html ---- results are added inside of a #+BEGIN_HTML block. This
1957 is a good option if you code block will output html
1958 formatted text.
1960 latex --- results are added inside of a #+BEGIN_LATEX block.
1961 This is a good option if you code block will output
1962 latex formatted text.
1964 code ---- the results are extracted in the syntax of the source
1965 code of the language being evaluated and are added
1966 inside of a #+BEGIN_SRC block with the source-code
1967 language set appropriately. Note this relies on the
1968 optional LANG argument."
1969 (if (stringp result)
1970 (progn
1971 (setq result (org-no-properties result))
1972 (when (member "file" result-params)
1973 (setq result (org-babel-result-to-file
1974 result (when (assoc :file-desc (nth 2 info))
1975 (or (cdr (assoc :file-desc (nth 2 info)))
1976 result))))))
1977 (unless (listp result) (setq result (format "%S" result))))
1978 (if (and result-params (member "silent" result-params))
1979 (progn
1980 (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
1981 result)
1982 (save-excursion
1983 (let* ((inlinep
1984 (save-excursion
1985 (when (or (org-babel-get-inline-src-block-matches)
1986 (org-babel-get-lob-one-liner-matches))
1987 (goto-char (match-end 0))
1988 (insert (if (listp result) "\n" " "))
1989 (point))))
1990 (existing-result (unless inlinep
1991 (org-babel-where-is-src-block-result
1992 t info hash indent)))
1993 (results-switches
1994 (cdr (assoc :results_switches (nth 2 info))))
1995 (visible-beg (copy-marker (point-min)))
1996 (visible-end (copy-marker (point-max)))
1997 ;; When results exist outside of the current visible
1998 ;; region of the buffer, be sure to widen buffer to
1999 ;; update them.
2000 (outside-scope-p (and existing-result
2001 (or (> visible-beg existing-result)
2002 (<= visible-end existing-result))))
2003 beg end)
2004 (when (and (stringp result) ; ensure results end in a newline
2005 (not inlinep)
2006 (> (length result) 0)
2007 (not (or (string-equal (substring result -1) "\n")
2008 (string-equal (substring result -1) "\r"))))
2009 (setq result (concat result "\n")))
2010 (unwind-protect
2011 (progn
2012 (when outside-scope-p (widen))
2013 (if (not existing-result)
2014 (setq beg (or inlinep (point)))
2015 (goto-char existing-result)
2016 (save-excursion
2017 (re-search-forward "#" nil t)
2018 (setq indent (- (current-column) 1)))
2019 (forward-line 1)
2020 (setq beg (point))
2021 (cond
2022 ((member "replace" result-params)
2023 (delete-region (point) (org-babel-result-end)))
2024 ((member "append" result-params)
2025 (goto-char (org-babel-result-end)) (setq beg (point-marker)))
2026 ((member "prepend" result-params)))) ; already there
2027 (setq results-switches
2028 (if results-switches (concat " " results-switches) ""))
2029 (let ((wrap (lambda (start finish &optional no-escape)
2030 (goto-char end) (insert (concat finish "\n"))
2031 (goto-char beg) (insert (concat start "\n"))
2032 (unless no-escape
2033 (org-escape-code-in-region (min (point) end) end))
2034 (goto-char end) (goto-char (point-at-eol))
2035 (setq end (point-marker))))
2036 (proper-list-p (lambda (it) (and (listp it) (null (cdr (last it)))))))
2037 ;; insert results based on type
2038 (cond
2039 ;; do nothing for an empty result
2040 ((null result))
2041 ;; insert a list if preferred
2042 ((member "list" result-params)
2043 (insert
2044 (org-babel-trim
2045 (org-list-to-generic
2046 (cons 'unordered
2047 (mapcar
2048 (lambda (el) (list nil (if (stringp el) el (format "%S" el))))
2049 (if (listp result) result (split-string result "\n" t))))
2050 '(:splicep nil :istart "- " :iend "\n")))
2051 "\n"))
2052 ;; assume the result is a table if it's not a string
2053 ((funcall proper-list-p result)
2054 (goto-char beg)
2055 (insert (concat (orgtbl-to-orgtbl
2056 (if (or (eq 'hline (car result))
2057 (and (listp (car result))
2058 (listp (cdr (car result)))))
2059 result (list result))
2060 '(:fmt (lambda (cell) (format "%s" cell)))) "\n"))
2061 (goto-char beg) (when (org-at-table-p) (org-table-align)))
2062 ((and (listp result) (not (funcall proper-list-p result)))
2063 (insert (format "%s\n" result)))
2064 ((member "file" result-params)
2065 (when inlinep (goto-char inlinep))
2066 (insert result))
2067 (t (goto-char beg) (insert result)))
2068 (when (funcall proper-list-p result) (goto-char (org-table-end)))
2069 (setq end (point-marker))
2070 ;; possibly wrap result
2071 (cond
2072 ((assoc :wrap (nth 2 info))
2073 (let ((name (or (cdr (assoc :wrap (nth 2 info))) "RESULTS")))
2074 (funcall wrap (concat "#+BEGIN_" name)
2075 (concat "#+END_" (car (org-split-string name))))))
2076 ((member "html" result-params)
2077 (funcall wrap "#+BEGIN_HTML" "#+END_HTML"))
2078 ((member "latex" result-params)
2079 (funcall wrap "#+BEGIN_LaTeX" "#+END_LaTeX"))
2080 ((member "org" result-params)
2081 (goto-char beg) (if (org-at-table-p) (org-cycle))
2082 (funcall wrap "#+BEGIN_SRC org" "#+END_SRC"))
2083 ((member "code" result-params)
2084 (funcall wrap (format "#+BEGIN_SRC %s%s" (or lang "none") results-switches)
2085 "#+END_SRC"))
2086 ((member "raw" result-params)
2087 (goto-char beg) (if (org-at-table-p) (org-cycle)))
2088 ((or (member "drawer" result-params)
2089 ;; Stay backward compatible with <7.9.2
2090 (member "wrap" result-params))
2091 (goto-char beg) (if (org-at-table-p) (org-cycle))
2092 (funcall wrap ":RESULTS:" ":END:" 'no-escape))
2093 ((and (not (funcall proper-list-p result))
2094 (not (member "file" result-params)))
2095 (org-babel-examplize-region beg end results-switches)
2096 (setq end (point)))))
2097 ;; possibly indent the results to match the #+results line
2098 (when (and (not inlinep) (numberp indent) indent (> indent 0)
2099 ;; in this case `table-align' does the work for us
2100 (not (and (listp result)
2101 (member "append" result-params))))
2102 (indent-rigidly beg end indent))
2103 (if (null result)
2104 (if (member "value" result-params)
2105 (message "Code block returned no value.")
2106 (message "Code block produced no output."))
2107 (message "Code block evaluation complete.")))
2108 (when outside-scope-p (narrow-to-region visible-beg visible-end))
2109 (set-marker visible-beg nil)
2110 (set-marker visible-end nil))))))
2112 (defun org-babel-remove-result (&optional info)
2113 "Remove the result of the current source block."
2114 (interactive)
2115 (let ((location (org-babel-where-is-src-block-result nil info)) start)
2116 (when location
2117 (setq start (- location 1))
2118 (save-excursion
2119 (goto-char location) (forward-line 1)
2120 (delete-region start (org-babel-result-end))))))
2122 (defun org-babel-result-end ()
2123 "Return the point at the end of the current set of results."
2124 (save-excursion
2125 (cond
2126 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
2127 ((org-at-item-p) (let* ((struct (org-list-struct))
2128 (prvs (org-list-prevs-alist struct)))
2129 (org-list-get-list-end (point-at-bol) struct prvs)))
2130 ((let ((case-fold-search t)) (looking-at "^\\([ \t]*\\):results:"))
2131 (progn (re-search-forward (concat "^" (match-string 1) ":END:"))
2132 (forward-char 1) (point)))
2134 (let ((case-fold-search t))
2135 (if (looking-at (concat "[ \t]*#\\+begin_\\([^ \t\n\r]+\\)"))
2136 (progn (re-search-forward (concat "[ \t]*#\\+end_" (match-string 1))
2137 nil t)
2138 (forward-char 1))
2139 (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
2140 (forward-line 1))))
2141 (point)))))
2143 (defun org-babel-result-to-file (result &optional description)
2144 "Convert RESULT into an `org-mode' link with optional DESCRIPTION.
2145 If the `default-directory' is different from the containing
2146 file's directory then expand relative links."
2147 (when (stringp result)
2148 (format "[[file:%s]%s]"
2149 (if (and default-directory
2150 buffer-file-name
2151 (not (string= (expand-file-name default-directory)
2152 (expand-file-name
2153 (file-name-directory buffer-file-name)))))
2154 (expand-file-name result default-directory)
2155 result)
2156 (if description (concat "[" description "]") ""))))
2158 (defvar org-babel-capitalize-examplize-region-markers nil
2159 "Make true to capitalize begin/end example markers inserted by code blocks.")
2161 (defun org-babel-examplize-region (beg end &optional results-switches)
2162 "Comment out region using the inline '==' or ': ' org example quote."
2163 (interactive "*r")
2164 (let ((chars-between (lambda (b e)
2165 (not (string-match "^[\\s]*$" (buffer-substring b e)))))
2166 (maybe-cap (lambda (str) (if org-babel-capitalize-examplize-region-markers
2167 (upcase str) str))))
2168 (if (or (funcall chars-between (save-excursion (goto-char beg) (point-at-bol)) beg)
2169 (funcall chars-between end (save-excursion (goto-char end) (point-at-eol))))
2170 (save-excursion
2171 (goto-char beg)
2172 (insert (format "=%s=" (prog1 (buffer-substring beg end)
2173 (delete-region beg end)))))
2174 (let ((size (count-lines beg end)))
2175 (save-excursion
2176 (cond ((= size 0)) ; do nothing for an empty result
2177 ((< size org-babel-min-lines-for-block-output)
2178 (goto-char beg)
2179 (dotimes (n size)
2180 (beginning-of-line 1) (insert ": ") (forward-line 1)))
2182 (goto-char beg)
2183 (insert (if results-switches
2184 (format "%s%s\n"
2185 (funcall maybe-cap "#+begin_example")
2186 results-switches)
2187 (funcall maybe-cap "#+begin_example\n")))
2188 (if (markerp end) (goto-char end) (forward-char (- end beg)))
2189 (insert (funcall maybe-cap "#+end_example\n")))))))))
2191 (defun org-babel-update-block-body (new-body)
2192 "Update the body of the current code block to NEW-BODY."
2193 (if (not (org-babel-where-is-src-block-head))
2194 (error "Not in a source block")
2195 (save-match-data
2196 (replace-match (concat (org-babel-trim new-body) "\n") nil t nil 5))
2197 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
2199 (defun org-babel-merge-params (&rest plists)
2200 "Combine all parameter association lists in PLISTS.
2201 Later elements of PLISTS override the values of previous elements.
2202 This takes into account some special considerations for certain
2203 parameters when merging lists."
2204 (let* ((results-exclusive-groups
2205 (mapcar (lambda (group) (mapcar #'symbol-name group))
2206 (cdr (assoc 'results org-babel-common-header-args-w-values))))
2207 (exports-exclusive-groups
2208 (mapcar (lambda (group) (mapcar #'symbol-name group))
2209 (cdr (assoc 'exports org-babel-common-header-args-w-values))))
2210 (variable-index 0)
2211 (e-merge (lambda (exclusive-groups &rest result-params)
2212 ;; maintain exclusivity of mutually exclusive parameters
2213 (let (output)
2214 (mapc (lambda (new-params)
2215 (mapc (lambda (new-param)
2216 (mapc (lambda (exclusive-group)
2217 (when (member new-param exclusive-group)
2218 (mapcar (lambda (excluded-param)
2219 (setq output
2220 (delete
2221 excluded-param
2222 output)))
2223 exclusive-group)))
2224 exclusive-groups)
2225 (setq output (org-uniquify
2226 (cons new-param output))))
2227 new-params))
2228 result-params)
2229 output)))
2230 params results exports tangle noweb cache vars shebang comments padline)
2232 (mapc
2233 (lambda (plist)
2234 (mapc
2235 (lambda (pair)
2236 (case (car pair)
2237 (:var
2238 (let ((name (if (listp (cdr pair))
2239 (cadr pair)
2240 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
2241 (cdr pair))
2242 (intern (match-string 1 (cdr pair)))))))
2243 (if name
2244 (setq vars
2245 (append
2246 (if (member name (mapcar #'car vars))
2247 (delq nil
2248 (mapcar
2249 (lambda (p)
2250 (unless (equal (car p) name) p))
2251 vars))
2252 vars)
2253 (list (cons name pair))))
2254 ;; if no name is given and we already have named variables
2255 ;; then assign to named variables in order
2256 (if (and vars (nth variable-index vars))
2257 (prog1 (setf (cddr (nth variable-index vars))
2258 (concat (symbol-name
2259 (car (nth variable-index vars)))
2260 "=" (cdr pair)))
2261 (incf variable-index))
2262 (error "Variable \"%s\" must be assigned a default value"
2263 (cdr pair))))))
2264 (:results
2265 (setq results (funcall e-merge results-exclusive-groups
2266 results
2267 (split-string
2268 (let ((r (cdr pair)))
2269 (if (stringp r) r (eval r)))))))
2270 (:file
2271 (when (cdr pair)
2272 (setq results (funcall e-merge results-exclusive-groups
2273 results '("file")))
2274 (unless (or (member "both" exports)
2275 (member "none" exports)
2276 (member "code" exports))
2277 (setq exports (funcall e-merge exports-exclusive-groups
2278 exports '("results"))))
2279 (setq params (cons pair (assq-delete-all (car pair) params)))))
2280 (:exports
2281 (setq exports (funcall e-merge exports-exclusive-groups
2282 exports (split-string (cdr pair)))))
2283 (:tangle ;; take the latest -- always overwrite
2284 (setq tangle (or (list (cdr pair)) tangle)))
2285 (:noweb
2286 (setq noweb (funcall e-merge
2287 '(("yes" "no" "tangle" "no-export"
2288 "strip-export" "eval"))
2289 noweb
2290 (split-string (or (cdr pair) "")))))
2291 (:cache
2292 (setq cache (funcall e-merge '(("yes" "no")) cache
2293 (split-string (or (cdr pair) "")))))
2294 (:padline
2295 (setq padline (funcall e-merge '(("yes" "no")) padline
2296 (split-string (or (cdr pair) "")))))
2297 (:shebang ;; take the latest -- always overwrite
2298 (setq shebang (or (list (cdr pair)) shebang)))
2299 (:comments
2300 (setq comments (funcall e-merge '(("yes" "no")) comments
2301 (split-string (or (cdr pair) "")))))
2302 (t ;; replace: this covers e.g. :session
2303 (setq params (cons pair (assq-delete-all (car pair) params))))))
2304 plist))
2305 plists)
2306 (setq vars (reverse vars))
2307 (while vars (setq params (cons (cons :var (cddr (pop vars))) params)))
2308 (mapc
2309 (lambda (hd)
2310 (let ((key (intern (concat ":" (symbol-name hd))))
2311 (val (eval hd)))
2312 (setf params (cons (cons key (mapconcat 'identity val " ")) params))))
2313 '(results exports tangle noweb padline cache shebang comments))
2314 params))
2316 (defvar org-babel-use-quick-and-dirty-noweb-expansion nil
2317 "Set to true to use regular expressions to expand noweb references.
2318 This results in much faster noweb reference expansion but does
2319 not properly allow code blocks to inherit the \":noweb-ref\"
2320 header argument from buffer or subtree wide properties.")
2322 (defun org-babel-noweb-p (params context)
2323 "Check if PARAMS require expansion in CONTEXT.
2324 CONTEXT may be one of :tangle, :export or :eval."
2325 (let* (intersect
2326 (intersect (lambda (as bs)
2327 (when as
2328 (if (member (car as) bs)
2329 (car as)
2330 (funcall intersect (cdr as) bs))))))
2331 (funcall intersect (case context
2332 (:tangle '("yes" "tangle" "no-export" "strip-export"))
2333 (:eval '("yes" "no-export" "strip-export" "eval"))
2334 (:export '("yes")))
2335 (split-string (or (cdr (assoc :noweb params)) "")))))
2337 (defun org-babel-expand-noweb-references (&optional info parent-buffer)
2338 "Expand Noweb references in the body of the current source code block.
2340 For example the following reference would be replaced with the
2341 body of the source-code block named 'example-block'.
2343 <<example-block>>
2345 Note that any text preceding the <<foo>> construct on a line will
2346 be interposed between the lines of the replacement text. So for
2347 example if <<foo>> is placed behind a comment, then the entire
2348 replacement text will also be commented.
2350 This function must be called from inside of the buffer containing
2351 the source-code block which holds BODY.
2353 In addition the following syntax can be used to insert the
2354 results of evaluating the source-code block named 'example-block'.
2356 <<example-block()>>
2358 Any optional arguments can be passed to example-block by placing
2359 the arguments inside the parenthesis following the convention
2360 defined by `org-babel-lob'. For example
2362 <<example-block(a=9)>>
2364 would set the value of argument \"a\" equal to \"9\". Note that
2365 these arguments are not evaluated in the current source-code
2366 block but are passed literally to the \"example-block\"."
2367 (let* ((parent-buffer (or parent-buffer (current-buffer)))
2368 (info (or info (org-babel-get-src-block-info 'light)))
2369 (lang (nth 0 info))
2370 (body (nth 1 info))
2371 (ob-nww-start org-babel-noweb-wrap-start)
2372 (ob-nww-end org-babel-noweb-wrap-end)
2373 (comment (string= "noweb" (cdr (assoc :comments (nth 2 info)))))
2374 (rx-prefix (concat "\\(" org-babel-src-name-regexp "\\|"
2375 ":noweb-ref[ \t]+" "\\)"))
2376 (new-body "")
2377 (nb-add (lambda (text) (setq new-body (concat new-body text))))
2378 (c-wrap (lambda (text)
2379 (with-temp-buffer
2380 (funcall (intern (concat lang "-mode")))
2381 (comment-region (point) (progn (insert text) (point)))
2382 (org-babel-trim (buffer-string)))))
2383 index source-name evaluate prefix blocks-in-buffer)
2384 (with-temp-buffer
2385 (org-set-local 'org-babel-noweb-wrap-start ob-nww-start)
2386 (org-set-local 'org-babel-noweb-wrap-end ob-nww-end)
2387 (insert body) (goto-char (point-min))
2388 (setq index (point))
2389 (while (and (re-search-forward (org-babel-noweb-wrap) nil t))
2390 (save-match-data (setf source-name (match-string 1)))
2391 (save-match-data (setq evaluate (string-match "\(.*\)" source-name)))
2392 (save-match-data
2393 (setq prefix
2394 (buffer-substring (match-beginning 0)
2395 (save-excursion
2396 (beginning-of-line 1) (point)))))
2397 ;; add interval to new-body (removing noweb reference)
2398 (goto-char (match-beginning 0))
2399 (funcall nb-add (buffer-substring index (point)))
2400 (goto-char (match-end 0))
2401 (setq index (point))
2402 (funcall nb-add
2403 (with-current-buffer parent-buffer
2404 (save-restriction
2405 (widen)
2406 (mapconcat ;; interpose PREFIX between every line
2407 #'identity
2408 (split-string
2409 (if evaluate
2410 (let ((raw (org-babel-ref-resolve source-name)))
2411 (if (stringp raw) raw (format "%S" raw)))
2413 ;; retrieve from the library of babel
2414 (nth 2 (assoc (intern source-name)
2415 org-babel-library-of-babel))
2416 ;; return the contents of headlines literally
2417 (save-excursion
2418 (when (org-babel-ref-goto-headline-id source-name)
2419 (org-babel-ref-headline-body)))
2420 ;; find the expansion of reference in this buffer
2421 (let ((rx (concat rx-prefix source-name "[ \t\n]"))
2422 expansion)
2423 (save-excursion
2424 (goto-char (point-min))
2425 (if org-babel-use-quick-and-dirty-noweb-expansion
2426 (while (re-search-forward rx nil t)
2427 (let* ((i (org-babel-get-src-block-info 'light))
2428 (body (org-babel-expand-noweb-references i))
2429 (sep (or (cdr (assoc :noweb-sep (nth 2 i)))
2430 "\n"))
2431 (full (if comment
2432 ((lambda (cs)
2433 (concat (funcall c-wrap (car cs)) "\n"
2434 body "\n"
2435 (funcall c-wrap (cadr cs))))
2436 (org-babel-tangle-comment-links i))
2437 body)))
2438 (setq expansion (cons sep (cons full expansion)))))
2439 (org-babel-map-src-blocks nil
2440 (let ((i (org-babel-get-src-block-info 'light)))
2441 (when (equal (or (cdr (assoc :noweb-ref (nth 2 i)))
2442 (nth 4 i))
2443 source-name)
2444 (let* ((body (org-babel-expand-noweb-references i))
2445 (sep (or (cdr (assoc :noweb-sep (nth 2 i)))
2446 "\n"))
2447 (full (if comment
2448 ((lambda (cs)
2449 (concat (funcall c-wrap (car cs)) "\n"
2450 body "\n"
2451 (funcall c-wrap (cadr cs))))
2452 (org-babel-tangle-comment-links i))
2453 body)))
2454 (setq expansion
2455 (cons sep (cons full expansion)))))))))
2456 (and expansion
2457 (mapconcat #'identity (nreverse (cdr expansion)) "")))
2458 ;; possibly raise an error if named block doesn't exist
2459 (if (member lang org-babel-noweb-error-langs)
2460 (error "%s" (concat
2461 (org-babel-noweb-wrap source-name)
2462 "could not be resolved (see "
2463 "`org-babel-noweb-error-langs')"))
2464 "")))
2465 "[\n\r]") (concat "\n" prefix))))))
2466 (funcall nb-add (buffer-substring index (point-max))))
2467 new-body))
2469 (defun org-babel-script-escape (str &optional force)
2470 "Safely convert tables into elisp lists."
2471 (let (in-single in-double out)
2472 ((lambda (escaped) (condition-case nil (org-babel-read escaped) (error escaped)))
2473 (if (or force
2474 (and (stringp str)
2475 (> (length str) 2)
2476 (or (and (string-equal "[" (substring str 0 1))
2477 (string-equal "]" (substring str -1)))
2478 (and (string-equal "{" (substring str 0 1))
2479 (string-equal "}" (substring str -1)))
2480 (and (string-equal "(" (substring str 0 1))
2481 (string-equal ")" (substring str -1))))))
2482 (org-babel-read
2483 (concat
2485 (progn
2486 (mapc
2487 (lambda (ch)
2488 (setq
2490 (case ch
2491 (91 (if (or in-double in-single) ; [
2492 (cons 91 out)
2493 (cons 40 out)))
2494 (93 (if (or in-double in-single) ; ]
2495 (cons 93 out)
2496 (cons 41 out)))
2497 (123 (if (or in-double in-single) ; {
2498 (cons 123 out)
2499 (cons 40 out)))
2500 (125 (if (or in-double in-single) ; }
2501 (cons 125 out)
2502 (cons 41 out)))
2503 (44 (if (or in-double in-single) ; ,
2504 (cons 44 out) (cons 32 out)))
2505 (39 (if in-double ; '
2506 (cons 39 out)
2507 (setq in-single (not in-single)) (cons 34 out)))
2508 (34 (if in-single ; "
2509 (append (list 34 32) out)
2510 (setq in-double (not in-double)) (cons 34 out)))
2511 (t (cons ch out)))))
2512 (string-to-list str))
2513 (apply #'string (reverse out)))))
2514 str))))
2516 (defun org-babel-read (cell &optional inhibit-lisp-eval)
2517 "Convert the string value of CELL to a number if appropriate.
2518 Otherwise if cell looks like lisp (meaning it starts with a
2519 \"(\", \"'\", \"`\" or a \"[\") then read it as lisp, otherwise
2520 return it unmodified as a string. Optional argument NO-LISP-EVAL
2521 inhibits lisp evaluation for situations in which is it not
2522 appropriate."
2523 (if (and (stringp cell) (not (equal cell "")))
2524 (or (org-babel-number-p cell)
2525 (if (and (not inhibit-lisp-eval)
2526 (or (member (substring cell 0 1) '("(" "'" "`" "["))
2527 (string= cell "*this*")))
2528 (eval (read cell))
2529 (if (string= (substring cell 0 1) "\"")
2530 (read cell)
2531 (progn (set-text-properties 0 (length cell) nil cell) cell))))
2532 cell))
2534 (defun org-babel-number-p (string)
2535 "If STRING represents a number return its value."
2536 (if (and (string-match "[0-9]+" string)
2537 (string-match "^-?[0-9]*\\.?[0-9]*$" string)
2538 (= (length (substring string (match-beginning 0)
2539 (match-end 0)))
2540 (length string)))
2541 (string-to-number string)))
2543 (defun org-babel-import-elisp-from-file (file-name &optional separator)
2544 "Read the results located at FILE-NAME into an elisp table.
2545 If the table is trivial, then return it as a scalar."
2546 (let (result)
2547 (save-window-excursion
2548 (with-temp-buffer
2549 (condition-case err
2550 (progn
2551 (org-table-import file-name separator)
2552 (delete-file file-name)
2553 (setq result (mapcar (lambda (row)
2554 (mapcar #'org-babel-string-read row))
2555 (org-table-to-lisp))))
2556 (error (message "Error reading results: %s" err) nil)))
2557 (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
2558 (if (consp (car result))
2559 (if (null (cdr (car result)))
2560 (caar result)
2561 result)
2562 (car result))
2563 result))))
2565 (defun org-babel-string-read (cell)
2566 "Strip nested \"s from around strings."
2567 (org-babel-read (or (and (stringp cell)
2568 (string-match "\\\"\\(.+\\)\\\"" cell)
2569 (match-string 1 cell))
2570 cell) t))
2572 (defun org-babel-chomp (string &optional regexp)
2573 "Strip trailing spaces and carriage returns from STRING.
2574 Default regexp used is \"[ \f\t\n\r\v]\" but can be
2575 overwritten by specifying a regexp as a second argument."
2576 (let ((regexp (or regexp "[ \f\t\n\r\v]")))
2577 (while (and (> (length string) 0)
2578 (string-match regexp (substring string -1)))
2579 (setq string (substring string 0 -1)))
2580 string))
2582 (defun org-babel-trim (string &optional regexp)
2583 "Strip leading and trailing spaces and carriage returns from STRING.
2584 Like `org-babel-chomp' only it runs on both the front and back
2585 of the string."
2586 (org-babel-chomp (org-reverse-string
2587 (org-babel-chomp (org-reverse-string string) regexp))
2588 regexp))
2590 (defun org-babel-tramp-handle-call-process-region
2591 (start end program &optional delete buffer display &rest args)
2592 "Use Tramp to handle `call-process-region'.
2593 Fixes a bug in `tramp-handle-call-process-region'."
2594 (if (and (featurep 'tramp) (file-remote-p default-directory))
2595 (let ((tmpfile (tramp-compat-make-temp-file "")))
2596 (write-region start end tmpfile)
2597 (when delete (delete-region start end))
2598 (unwind-protect
2599 ;; (apply 'call-process program tmpfile buffer display args)
2600 ;; bug in tramp
2601 (apply 'process-file program tmpfile buffer display args)
2602 (delete-file tmpfile)))
2603 ;; org-babel-call-process-region-original is the original emacs
2604 ;; definition. It is in scope from the let binding in
2605 ;; org-babel-execute-src-block
2606 (apply org-babel-call-process-region-original
2607 start end program delete buffer display args)))
2609 (defun org-babel-local-file-name (file)
2610 "Return the local name component of FILE."
2611 (if (file-remote-p file)
2612 (let (localname)
2613 (with-parsed-tramp-file-name file nil
2614 localname))
2615 file))
2617 (defun org-babel-process-file-name (name &optional no-quote-p)
2618 "Prepare NAME to be used in an external process.
2619 If NAME specifies a remote location, the remote portion of the
2620 name is removed, since in that case the process will be executing
2621 remotely. The file name is then processed by `expand-file-name'.
2622 Unless second argument NO-QUOTE-P is non-nil, the file name is
2623 additionally processed by `shell-quote-argument'"
2624 ((lambda (f) (if no-quote-p f (shell-quote-argument f)))
2625 (expand-file-name (org-babel-local-file-name name))))
2627 (defvar org-babel-temporary-directory)
2628 (unless (or noninteractive (boundp 'org-babel-temporary-directory))
2629 (defvar org-babel-temporary-directory
2630 (or (and (boundp 'org-babel-temporary-directory)
2631 (file-exists-p org-babel-temporary-directory)
2632 org-babel-temporary-directory)
2633 (make-temp-file "babel-" t))
2634 "Directory to hold temporary files created to execute code blocks.
2635 Used by `org-babel-temp-file'. This directory will be removed on
2636 Emacs shutdown."))
2638 (defmacro org-babel-result-cond (result-params scalar-form &rest table-forms)
2639 "Call the code to parse raw string results according to RESULT-PARAMS."
2640 (declare (indent 1)
2641 (debug (form form &rest form)))
2642 (org-with-gensyms (params)
2643 `(let ((,params ,result-params))
2644 (unless (member "none" ,params)
2645 (if (or (member "scalar" ,params)
2646 (member "verbatim" ,params)
2647 (member "html" ,params)
2648 (member "code" ,params)
2649 (member "pp" ,params)
2650 (and (or (member "output" ,params)
2651 (member "raw" ,params)
2652 (member "org" ,params)
2653 (member "drawer" ,params))
2654 (not (member "table" ,params))))
2655 ,scalar-form
2656 ,@table-forms)))))
2657 (def-edebug-spec org-babel-result-cond (form form body))
2659 (defun org-babel-temp-file (prefix &optional suffix)
2660 "Create a temporary file in the `org-babel-temporary-directory'.
2661 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2662 value of `temporary-file-directory' temporarily set to the value
2663 of `org-babel-temporary-directory'."
2664 (if (file-remote-p default-directory)
2665 (let ((prefix
2666 (concat (file-remote-p default-directory)
2667 (expand-file-name prefix temporary-file-directory))))
2668 (make-temp-file prefix nil suffix))
2669 (let ((temporary-file-directory
2670 (or (and (boundp 'org-babel-temporary-directory)
2671 (file-exists-p org-babel-temporary-directory)
2672 org-babel-temporary-directory)
2673 temporary-file-directory)))
2674 (make-temp-file prefix nil suffix))))
2676 (defun org-babel-remove-temporary-directory ()
2677 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2678 (when (and (boundp 'org-babel-temporary-directory)
2679 (file-exists-p org-babel-temporary-directory))
2680 ;; taken from `delete-directory' in files.el
2681 (condition-case nil
2682 (progn
2683 (mapc (lambda (file)
2684 ;; This test is equivalent to
2685 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2686 ;; but more efficient
2687 (if (eq t (car (file-attributes file)))
2688 (delete-directory file)
2689 (delete-file file)))
2690 ;; We do not want to delete "." and "..".
2691 (directory-files org-babel-temporary-directory 'full
2692 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2693 (delete-directory org-babel-temporary-directory))
2694 (error
2695 (message "Failed to remove temporary Org-babel directory %s"
2696 (if (boundp 'org-babel-temporary-directory)
2697 org-babel-temporary-directory
2698 "[directory not defined]"))))))
2700 (add-hook 'kill-emacs-hook 'org-babel-remove-temporary-directory)
2702 (provide 'ob-core)
2704 ;; Local variables:
2705 ;; generated-autoload-file: "org-loaddefs.el"
2706 ;; End:
2708 ;;; ob-core.el ends here