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