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