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