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