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