1 ;;; ob-core.el --- working with code blocks in org-mode
3 ;; Copyright (C) 2009-2016 Free Software Foundation, Inc.
5 ;; Authors: Eric Schulte
7 ;; Keywords: literate programming, reproducible research
8 ;; Homepage: http://orgmode.org
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
32 (defconst org-babel-exeext
33 (if (memq system-type
'(windows-nt cygwin
))
37 ;; dynamically scoped for tramp
38 (defvar org-babel-call-process-region-original nil
)
39 (defvar org-babel-library-of-babel
)
40 (defvar org-edit-src-content-indentation
)
41 (defvar org-src-lang-modes
)
43 (declare-function outline-show-all
"outline" ())
44 (declare-function org-every
"org" (pred seq
))
45 (declare-function org-get-indentation
"org" (&optional line
))
46 (declare-function org-remove-indentation
"org" (code &optional n
))
47 (declare-function org-reduce
"org" (CL-FUNC CL-SEQ
&rest CL-KEYS
))
48 (declare-function org-mark-ring-push
"org" (&optional pos buffer
))
49 (declare-function tramp-compat-make-temp-file
"tramp-compat"
50 (filename &optional dir-flag
))
51 (declare-function tramp-dissect-file-name
"tramp" (name &optional nodefault
))
52 (declare-function tramp-file-name-user
"tramp" (vec))
53 (declare-function tramp-file-name-host
"tramp" (vec))
54 (declare-function with-parsed-tramp-file-name
"tramp" (filename var
&rest body
))
55 (declare-function org-icompleting-read
"org" (&rest args
))
56 (declare-function org-edit-src-code
"org-src" (&optional code edit-buffer-name
))
57 (declare-function org-edit-src-exit
"org-src" ())
58 (declare-function org-open-at-point
"org" (&optional in-emacs reference-buffer
))
59 (declare-function org-save-outline-visibility
"org-macs" (use-markers &rest body
))
60 (declare-function org-outline-overlay-data
"org" (&optional use-markers
))
61 (declare-function org-set-outline-overlay-data
"org" (data))
62 (declare-function org-narrow-to-subtree
"org" ())
63 (declare-function org-split-string
"org" (string &optional separators
))
64 (declare-function org-entry-get
"org"
65 (pom property
&optional inherit literal-nil
))
66 (declare-function org-make-options-regexp
"org" (kwds &optional extra
))
67 (declare-function org-do-remove-indentation
"org" (&optional n
))
68 (declare-function org-next-block
"org" (arg &optional backward block-regexp
))
69 (declare-function org-previous-block
"org" (arg &optional block-regexp
))
70 (declare-function org-show-context
"org" (&optional key
))
71 (declare-function org-at-table-p
"org" (&optional table-type
))
72 (declare-function org-cycle
"org" (&optional arg
))
73 (declare-function org-uniquify
"org" (list))
74 (declare-function org-current-level
"org" ())
75 (declare-function org-table-import
"org-table" (file arg
))
76 (declare-function org-add-hook
"org-compat"
77 (hook function
&optional append local
))
78 (declare-function org-table-align
"org-table" ())
79 (declare-function org-table-end
"org-table" (&optional table-type
))
80 (declare-function orgtbl-to-generic
"org-table" (table params
))
81 (declare-function orgtbl-to-orgtbl
"org-table" (table params
))
82 (declare-function org-babel-tangle-comment-links
"ob-tangle" (&optional info
))
83 (declare-function org-babel-lob-get-info
"ob-lob" nil
)
84 (declare-function org-babel-ref-split-args
"ob-ref" (arg-string))
85 (declare-function org-babel-ref-parse
"ob-ref" (assignment))
86 (declare-function org-babel-ref-resolve
"ob-ref" (ref))
87 (declare-function org-babel-ref-goto-headline-id
"ob-ref" (id))
88 (declare-function org-babel-ref-headline-body
"ob-ref" ())
89 (declare-function org-babel-lob-execute-maybe
"ob-lob" ())
90 (declare-function org-number-sequence
"org-compat" (from &optional to inc
))
91 (declare-function org-at-item-p
"org-list" ())
92 (declare-function org-list-parse-list
"org-list" (&optional delete
))
93 (declare-function org-list-to-generic
"org-list" (LIST PARAMS
))
94 (declare-function org-list-struct
"org-list" ())
95 (declare-function org-list-prevs-alist
"org-list" (struct))
96 (declare-function org-list-get-list-end
"org-list" (item struct prevs
))
97 (declare-function org-remove-if
"org" (predicate seq
))
98 (declare-function org-completing-read
"org" (&rest args
))
99 (declare-function org-escape-code-in-region
"org-src" (beg end
))
100 (declare-function org-unescape-code-in-string
"org-src" (s))
101 (declare-function org-table-to-lisp
"org-table" (&optional txt
))
102 (declare-function org-reverse-string
"org" (string))
103 (declare-function org-element-context
"org-element" (&optional element
))
104 (declare-function org-element-type
"org-element" (element))
105 (declare-function org-element-at-point
"org-element" ())
106 (declare-function org-element-normalize-string
"org-element" (s))
107 (declare-function org-element-property
"org-element" (property element
))
108 (declare-function org-every
"org" (pred seq
))
109 (declare-function org-macro-escape-arguments
"org-macro" (&rest args
))
111 (defgroup org-babel nil
112 "Code block evaluation and management in `org-mode' documents."
116 (defcustom org-confirm-babel-evaluate t
117 "Confirm before evaluation.
119 Require confirmation before interactively evaluating code
120 blocks in Org-mode buffers. The default value of this variable
121 is t, meaning confirmation is required for any code block
122 evaluation. This variable can be set to nil to inhibit any
123 future confirmation requests. This variable can also be set to a
124 function which takes two arguments the language of the code block
125 and the body of the code block. Such a function should then
126 return a non-nil value if the user should be prompted for
127 execution or nil if no prompt is required.
129 Warning: Disabling confirmation may result in accidental
130 evaluation of potentially harmful code. It may be advisable
131 remove code block execution from \\[org-ctrl-c-ctrl-c] \
132 as further protection
133 against accidental code block evaluation. The
134 `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
135 remove code block execution from the \\[org-ctrl-c-ctrl-c] keybinding."
138 :type
'(choice boolean function
))
139 ;; don't allow this variable to be changed through file settings
140 (put 'org-confirm-babel-evaluate
'safe-local-variable
(lambda (x) (eq x t
)))
142 (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
144 Remove code block evaluation from the \\[org-ctrl-c-ctrl-c] key binding."
149 (defcustom org-babel-results-keyword
"RESULTS"
150 "Keyword used to name results generated by code blocks.
151 It should be \"RESULTS\". However any capitalization may be
155 :package-version
'(Org .
"8.0")
159 (eq (compare-strings "RESULTS" nil nil v nil nil t
)
162 (defcustom org-babel-noweb-wrap-start
"<<"
163 "String used to begin a noweb reference in a code block.
164 See also `org-babel-noweb-wrap-end'."
168 (defcustom org-babel-noweb-wrap-end
">>"
169 "String used to end a noweb reference in a code block.
170 See also `org-babel-noweb-wrap-start'."
174 (defcustom org-babel-inline-result-wrap
"=%s="
175 "Format string used to wrap inline results.
176 This string must include a \"%s\" which will be replaced by the results."
179 (put 'org-babel-inline-result-wrap
183 (string-match-p "%s" value
))))
185 (defun org-babel-noweb-wrap (&optional regexp
)
186 (concat org-babel-noweb-wrap-start
187 (or regexp
"\\([^ \t\n].+?[^ \t]\\|[^ \t\n]\\)")
188 org-babel-noweb-wrap-end
))
190 (defvar org-babel-src-name-regexp
191 "^[ \t]*#\\+name:[ \t]*"
192 "Regular expression used to match a source name line.")
194 (defvar org-babel-multi-line-header-regexp
195 "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
196 "Regular expression used to match multi-line header arguments.")
198 (defvar org-babel-src-block-regexp
200 ;; (1) indentation (2) lang
201 "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
203 "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
204 ;; (4) header arguments
207 "\\([^\000]*?\n\\)??[ \t]*#\\+end_src")
208 "Regexp used to identify code blocks.")
210 (defvar org-babel-inline-src-block-regexp
212 ;; (1) replacement target (2) lang
213 "\\(?:^\\|[^-[:alnum:]]?\\)\\(src_\\([^ \f\t\n\r\v[]+\\)"
214 ;; (3,4) (unused, headers)
215 "\\(\\|\\[[ \t]*\\(.*?\\)\\]\\)"
217 "{\\([^\f\n\r\v]+?\\)}\\)")
218 "Regexp used to identify inline src-blocks.")
220 (defun org-babel-get-header (params key
&optional others
)
221 "Select only header argument of type KEY from a list.
222 Optional argument OTHERS indicates that only the header that do
223 not match KEY should be returned."
226 (lambda (p) (when (funcall (if others
#'not
#'identity
) (eq (car p
) key
)) p
))
229 (defun org-babel-get-inline-src-block-matches ()
230 "Set match data if within body of an inline source block.
231 Returns non-nil if match-data set"
233 (let ((datum (org-element-context)))
234 (when (eq (org-element-type datum
) 'inline-src-block
)
235 (goto-char (org-element-property :begin datum
))
236 (when (looking-at org-babel-inline-src-block-regexp
)
239 (defvar org-babel-inline-lob-one-liner-regexp
)
240 (defun org-babel-get-lob-one-liner-matches ()
241 "Set match data if on line of an lob one liner.
242 Returns non-nil if match-data set"
244 (let ((datum (org-element-context)))
245 (when (eq (org-element-type datum
) 'inline-babel-call
)
246 (goto-char (org-element-property :begin datum
))))
247 (if (looking-at org-babel-inline-lob-one-liner-regexp
)
251 (defun org-babel-get-src-block-info (&optional light
)
252 "Get information on the current source block.
254 Optional argument LIGHT does not resolve remote variable
255 references; a process which could likely result in the execution
256 of other code blocks.
259 (language body header-arguments-alist switches name indent block-head)."
260 (let ((case-fold-search t
) head info name indent
)
262 (if (setq head
(org-babel-where-is-src-block-head))
265 (setq info
(org-babel-parse-src-block-match))
266 (setq indent
(car (last info
)))
267 (setq info
(butlast info
))
268 (while (and (= 0 (forward-line -
1))
269 (looking-at org-babel-multi-line-header-regexp
))
271 (org-babel-merge-params
273 (org-babel-parse-header-arguments (match-string 1)))))
274 (when (looking-at (org-babel-named-src-block-regexp-for-name))
275 (setq name
(org-match-string-no-properties 9))))
276 ;; inline source block
277 (when (org-babel-get-inline-src-block-matches)
278 (setq head
(match-beginning 0))
279 (setq info
(org-babel-parse-inline-src-block-match))))
280 ;; resolve variable references and add summary parameters
281 (when (and info
(not light
))
282 (setf (nth 2 info
) (org-babel-process-params (nth 2 info
))))
284 (setf (nth 2 info
) (org-babel-generate-file-param name
(nth 2 info
))))
285 (when info
(append info
(list name indent head
)))))
287 (defvar org-babel-exp-reference-buffer nil
288 "Buffer containing original contents of the exported buffer.
289 This is used by Babel to resolve references in source blocks.
290 Its value is dynamically bound during export.")
292 (defmacro org-babel-check-confirm-evaluate
(info &rest body
)
293 "Evaluate BODY with special execution confirmation variables set.
295 Specifically; NOEVAL will indicate if evaluation is allowed,
296 QUERY will indicate if a user query is required, CODE-BLOCK will
297 hold the language of the code block, and BLOCK-NAME will hold the
298 name of the code block."
299 (declare (indent defun
))
301 (lang block-body headers name head eval eval-no export eval-no-export
)
302 `(let* ((,lang
(nth 0 ,info
))
303 (,block-body
(nth 1 ,info
))
304 (,headers
(nth 2 ,info
))
305 (,name
(nth 4 ,info
))
306 (,head
(nth 6 ,info
))
307 (,eval
(or (cdr (assoc :eval
,headers
))
308 (when (assoc :noeval
,headers
) "no")))
309 (,eval-no
(or (equal ,eval
"no")
310 (equal ,eval
"never")))
311 (,export org-babel-exp-reference-buffer
)
312 (,eval-no-export
(and ,export
(or (equal ,eval
"no-export")
313 (equal ,eval
"never-export"))))
314 (noeval (or ,eval-no
,eval-no-export
))
315 (query (or (equal ,eval
"query")
316 (and ,export
(equal ,eval
"query-export"))
317 (if (functionp org-confirm-babel-evaluate
)
320 (funcall org-confirm-babel-evaluate
322 org-confirm-babel-evaluate
)))
323 (code-block (if ,info
(format " %s " ,lang
) " "))
324 (block-name (if ,name
(format " (%s) " ,name
) " ")))
325 ;; Silence byte-compiler if `body' doesn't use those vars.
326 (ignore noeval query
)
329 (defsubst org-babel-check-evaluate
(info)
330 "Check if code block INFO should be evaluated.
331 Do not query the user."
332 (org-babel-check-confirm-evaluate info
334 (message "Evaluation of this%scode-block%sis disabled."
335 code-block block-name
)))))
337 ;; dynamically scoped for asynchronous export
338 (defvar org-babel-confirm-evaluate-answer-no
)
340 (defsubst org-babel-confirm-evaluate
(info)
341 "Confirm evaluation of the code block INFO.
343 If the variable `org-babel-confirm-evaluate-answer-no' is bound
344 to a non-nil value, auto-answer with \"no\".
346 This query can also be suppressed by setting the value of
347 `org-confirm-babel-evaluate' to nil, in which case all future
348 interactive code block evaluations will proceed without any
349 confirmation from the user.
351 Note disabling confirmation may result in accidental evaluation
352 of potentially harmful code."
353 (org-babel-check-confirm-evaluate info
356 (and (not (org-bound-and-true-p
357 org-babel-confirm-evaluate-answer-no
))
359 (format "Evaluate this%scode block%son your system? "
360 code-block block-name
)))
361 (message "Evaluation of this%scode-block%sis aborted."
362 code-block block-name
))))))
365 (defun org-babel-execute-safely-maybe ()
366 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
367 (org-babel-execute-maybe)))
369 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-execute-safely-maybe
)
372 (defun org-babel-execute-maybe ()
374 (or (org-babel-execute-src-block-maybe)
375 (org-babel-lob-execute-maybe)))
377 (defmacro org-babel-when-in-src-block
(&rest body
)
378 "Execute BODY if point is in a source block and return t.
380 Otherwise do nothing and return nil."
381 `(if (or (org-babel-where-is-src-block-head)
382 (org-babel-get-inline-src-block-matches))
388 (defun org-babel-execute-src-block-maybe ()
389 "Conditionally execute a source block.
390 Detect if this is context for a Babel src-block and if so
391 then run `org-babel-execute-src-block'."
393 (org-babel-when-in-src-block
394 (org-babel-eval-wipe-error-buffer)
395 (org-babel-execute-src-block current-prefix-arg
)))
398 (defun org-babel-view-src-block-info ()
399 "Display information on the current source block.
400 This includes header arguments, language and name, and is largely
401 a window into the `org-babel-get-src-block-info' function."
403 (let ((info (org-babel-get-src-block-info 'light
))
404 (full (lambda (it) (> (length it
) 0)))
405 (printf (lambda (fmt &rest args
) (princ (apply #'format fmt args
)))))
407 (with-help-window (help-buffer)
408 (let ((name (nth 4 info
))
410 (switches (nth 3 info
))
411 (header-args (nth 2 info
)))
412 (when name
(funcall printf
"Name: %s\n" name
))
413 (when lang
(funcall printf
"Lang: %s\n" lang
))
414 (funcall printf
"Properties:\n")
415 (funcall printf
"\t:header-args \t%s\n" (org-entry-get (point) "header-args" t
))
416 (funcall printf
"\t:header-args:%s \t%s\n" lang
(org-entry-get (point) (concat "header-args:" lang
) t
))
418 (when (funcall full switches
) (funcall printf
"Switches: %s\n" switches
))
419 (funcall printf
"Header Arguments:\n")
420 (dolist (pair (sort header-args
421 (lambda (a b
) (string< (symbol-name (car a
))
422 (symbol-name (car b
))))))
423 (when (funcall full
(format "%s" (cdr pair
)))
424 (funcall printf
"\t%S%s\t%s\n"
426 (if (> (length (format "%S" (car pair
))) 7) "" "\t")
430 (defun org-babel-expand-src-block-maybe ()
431 "Conditionally expand a source block.
432 Detect if this is context for a org-babel src-block and if so
433 then run `org-babel-expand-src-block'."
435 (org-babel-when-in-src-block
436 (org-babel-expand-src-block current-prefix-arg
)))
439 (defun org-babel-load-in-session-maybe ()
440 "Conditionally load a source block in a session.
441 Detect if this is context for a org-babel src-block and if so
442 then run `org-babel-load-in-session'."
444 (org-babel-when-in-src-block
445 (org-babel-load-in-session current-prefix-arg
)))
447 (add-hook 'org-metaup-hook
'org-babel-load-in-session-maybe
)
450 (defun org-babel-pop-to-session-maybe ()
451 "Conditionally pop to a session.
452 Detect if this is context for a org-babel src-block and if so
453 then run `org-babel-switch-to-session'."
455 (org-babel-when-in-src-block
456 (org-babel-switch-to-session current-prefix-arg
)))
458 (add-hook 'org-metadown-hook
'org-babel-pop-to-session-maybe
)
460 (defconst org-babel-common-header-args-w-values
461 '((cache .
((no yes
)))
463 (colnames .
((nil no yes
)))
464 (comments .
((no link yes org both noweb
)))
466 (eval .
((yes no no-export strip-export never-export eval never
468 (exports .
((code results both none
)))
473 (hlines .
((no yes
)))
474 (mkdirp .
((yes no
)))
477 (noweb .
((yes no tangle no-export strip-export
)))
481 (padline .
((yes no
)))
484 (results .
((file list vector table scalar verbatim
)
485 (raw html latex org code pp drawer
)
486 (replace silent none append prepend
)
488 (rownames .
((no yes
)))
492 (tangle .
((tangle yes no
:any
)))
493 (tangle-mode .
((#o755
#o555
#o444
:any
)))
497 (defconst org-babel-header-arg-names
498 (mapcar #'car org-babel-common-header-args-w-values
)
499 "Common header arguments used by org-babel.
500 Note that individual languages may define their own language
501 specific header arguments as well.")
503 (defconst org-babel-safe-header-args
504 '(:cache
:colnames
:comments
:exports
:epilogue
:hlines
:noeval
505 :noweb
:noweb-ref
:noweb-sep
:padline
:prologue
:rownames
506 :sep
:session
:tangle
:wrap
507 (:eval .
("never" "query"))
508 (:results .
(lambda (str) (not (string-match "file" str
)))))
509 "A list of safe header arguments for babel source blocks.
511 The list can have entries of the following forms:
512 - :ARG -> :ARG is always a safe header arg
513 - (:ARG . (VAL1 VAL2 ...)) -> :ARG is safe as a header arg if it is
514 `equal' to one of the VALs.
515 - (:ARG . FN) -> :ARG is safe as a header arg if the function FN
516 returns non-nil. FN is passed one
517 argument, the value of the header arg
520 (defmacro org-babel-header-args-safe-fn
(safe-list)
521 "Return a function that determines whether a list of header args are safe.
524 \(put \\='org-babel-default-header-args \\='safe-local-variable
525 (org-babel-header-args-safe-p org-babel-safe-header-args)
527 This allows org-babel languages to extend the list of safe values for
528 their `org-babel-default-header-args:foo' variable.
530 For the format of SAFE-LIST, see `org-babel-safe-header-args'."
536 (org-babel-one-header-arg-safe-p pair
,safe-list
)))
539 (defvar org-babel-default-header-args
540 '((:session .
"none") (:results .
"replace") (:exports .
"code")
541 (:cache .
"no") (:noweb .
"no") (:hlines .
"no") (:tangle .
"no"))
542 "Default arguments to use when evaluating a source block.")
543 (put 'org-babel-default-header-args
'safe-local-variable
544 (org-babel-header-args-safe-fn org-babel-safe-header-args
))
546 (defvar org-babel-default-inline-header-args
547 '((:session .
"none") (:results .
"replace")
548 (:exports .
"results") (:hlines .
"yes"))
549 "Default arguments to use when evaluating an inline source block.")
550 (put 'org-babel-default-inline-header-args
'safe-local-variable
551 (org-babel-header-args-safe-fn org-babel-safe-header-args
))
553 (defvar org-babel-data-names
'("tblname" "results" "name"))
555 (defvar org-babel-result-regexp
556 (concat "^[ \t]*#\\+"
557 (regexp-opt org-babel-data-names t
)
559 ;; FIXME The string below is `org-ts-regexp'
560 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
561 " \\)?\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*")
562 "Regular expression used to match result lines.
563 If the results are associated with a hash key then the hash will
564 be saved in the second match data.")
566 (defvar org-babel-result-w-name-regexp
567 (concat org-babel-result-regexp
568 "\\([^ ()\f\t\n\r\v]+\\)\\((\\(.*\\))\\|\\)"))
570 (defvar org-babel-min-lines-for-block-output
10
571 "The minimum number of lines for block output.
572 If number of lines of output is equal to or exceeds this
573 value, the output is placed in a #+begin_example...#+end_example
574 block. Otherwise the output is marked as literal by inserting
575 colons at the starts of the lines. This variable only takes
576 effect if the :results output option is in effect.")
578 (defvar org-babel-noweb-error-all-langs nil
579 "Raise errors when noweb references don't resolve.
580 Also see `org-babel-noweb-error-langs' to control noweb errors on
581 a language by language bases.")
583 (defvar org-babel-noweb-error-langs nil
584 "Languages for which Babel will raise literate programming errors.
585 List of languages for which errors should be raised when the
586 source code block satisfying a noweb reference in this language
587 can not be resolved. Also see `org-babel-noweb-error-all-langs'
588 to raise errors for all languages.")
590 (defvar org-babel-hash-show
4
591 "Number of initial characters to show of a hidden results hash.")
593 (defvar org-babel-hash-show-time nil
594 "Non-nil means show the time the code block was evaluated in the result hash.")
596 (defvar org-babel-after-execute-hook nil
597 "Hook for functions to be called after `org-babel-execute-src-block'")
599 (defun org-babel-named-src-block-regexp-for-name (&optional name
)
600 "This generates a regexp used to match a src block named NAME.
601 If NAME is nil, match any name. Matched name is then put in
602 match group 9. Other match groups are defined in
603 `org-babel-src-block-regexp'."
604 (concat org-babel-src-name-regexp
605 (concat (if name
(regexp-quote name
) "\\(?9:.*?\\)") "[ \t]*" )
606 "\\(?:\n[ \t]*#\\+\\S-+:.*\\)*?"
608 (substring org-babel-src-block-regexp
1)))
610 (defun org-babel-named-data-regexp-for-name (name)
611 "This generates a regexp used to match data named NAME."
612 (concat org-babel-result-regexp
(regexp-quote name
) "\\([ \t]\\|$\\)"))
615 (defvar call-process-region
)
616 (defvar org-babel-current-src-block-location nil
617 "Marker pointing to the src block currently being executed.
618 This may also point to a call line or an inline code block. If
619 multiple blocks are being executed (e.g., in chained execution
620 through use of the :var header argument) this marker points to
621 the outer-most code block.")
626 (defun org-babel-execute-src-block (&optional arg info params
)
627 "Execute the current source code block.
628 Insert the results of execution into the buffer. Source code
629 execution and the collection and formatting of results can be
630 controlled through a variety of header arguments.
632 With prefix argument ARG, force re-execution even if an existing
633 result cached in the buffer would otherwise have been returned.
635 Optionally supply a value for INFO in the form returned by
636 `org-babel-get-src-block-info'.
638 Optionally supply a value for PARAMS which will be merged with
639 the header arguments specified at the front of the source code
642 (let* ((org-babel-current-src-block-location
643 (or org-babel-current-src-block-location
645 (org-babel-where-is-src-block-head)
647 (and (org-babel-get-inline-src-block-matches)
648 (match-beginning 0))))
651 (org-babel-get-src-block-info)))
652 (merged-params (org-babel-merge-params (nth 2 info
) params
)))
653 (when (org-babel-check-evaluate
654 (let ((i info
)) (setf (nth 2 i
) merged-params
) i
))
655 (let* ((params (if params
656 (org-babel-process-params merged-params
)
658 (cachep (and (not arg
) (cdr (assoc :cache params
))
659 (string= "yes" (cdr (assoc :cache params
)))))
660 (new-hash (when cachep
(org-babel-sha1-hash info
)))
661 (old-hash (when cachep
(org-babel-current-result-hash)))
662 (cache-current-p (and (not arg
) new-hash
663 (equal new-hash old-hash
))))
666 (save-excursion ;; return cached result
667 (goto-char (org-babel-where-is-src-block-result nil info
))
669 (skip-chars-forward " \t")
670 (let ((result (org-babel-read-result)))
671 (message (replace-regexp-in-string
672 "%" "%%" (format "%S" result
)))
674 ((org-babel-confirm-evaluate
675 (let ((i info
)) (setf (nth 2 i
) merged-params
) i
))
676 (let* ((lang (nth 0 info
))
677 (result-params (cdr (assoc :result-params params
)))
678 (body (setf (nth 1 info
)
679 (if (org-babel-noweb-p params
:eval
)
680 (org-babel-expand-noweb-references info
)
682 (dir (cdr (assoc :dir params
)))
684 (or (and dir
(file-name-as-directory (expand-file-name dir
)))
686 (org-babel-call-process-region-original ;; for tramp handler
687 (or (org-bound-and-true-p
688 org-babel-call-process-region-original
)
689 (symbol-function 'call-process-region
)))
690 (indent (nth 5 info
))
693 (let ((call-process-region
695 (apply 'org-babel-tramp-handle-call-process-region
699 (let ((f (intern (concat "org-babel-execute:" f
))))
700 (when (fboundp f
) f
)))))
702 (or (funcall lang-check lang
)
705 (cdr (assoc lang org-src-lang-modes
))))
706 (error "No org-babel-execute function for %s!"
708 (message "executing %s code block%s..."
710 (if (nth 4 info
) (format " (%s)" (nth 4 info
)) ""))
711 (if (member "none" result-params
)
713 (funcall cmd body params
)
714 (message "result silenced")
717 (let ((result (funcall cmd body params
)))
718 (if (and (eq (cdr (assoc :result-type params
))
720 (or (member "vector" result-params
)
721 (member "table" result-params
))
722 (not (listp result
)))
723 (list (list result
)) result
)))
724 ;; If non-empty result and :file then write to :file.
725 (when (cdr (assoc :file params
))
727 (with-temp-file (cdr (assoc :file params
))
729 (org-babel-format-result
730 result
(cdr (assoc :sep
(nth 2 info
)))))))
731 (setq result
(cdr (assoc :file params
))))
732 ;; Possibly perform post process provided its appropriate.
733 (when (cdr (assoc :post params
))
734 (let ((*this
* (if (cdr (assoc :file params
))
735 (org-babel-result-to-file
736 (cdr (assoc :file params
))
737 (when (assoc :file-desc params
)
738 (or (cdr (assoc :file-desc params
))
741 (setq result
(org-babel-ref-resolve
742 (cdr (assoc :post params
))))
743 (when (cdr (assoc :file params
))
745 (remove "file" result-params
)))))
746 (org-babel-insert-result
747 result result-params info new-hash indent lang
))
748 (run-hooks 'org-babel-after-execute-hook
)
750 (setq call-process-region
751 'org-babel-call-process-region-original
)))))))))
753 (defun org-babel-expand-body:generic
(body params
&optional var-lines
)
754 "Expand BODY with PARAMS.
755 Expand a block of code with org-babel according to its header
756 arguments. This generic implementation of body expansion is
757 called for languages which have not defined their own specific
758 org-babel-expand-body:lang function."
759 (let ((pro (cdr (assoc :prologue params
)))
760 (epi (cdr (assoc :epilogue params
))))
761 (mapconcat #'identity
762 (append (when pro
(list pro
))
765 (when epi
(list epi
)))
769 (defun org-babel-expand-src-block (&optional _arg info params
)
770 "Expand the current source code block.
771 Expand according to the source code block's header
772 arguments and pop open the results in a preview buffer."
774 (let* ((info (or info
(org-babel-get-src-block-info)))
776 (params (setf (nth 2 info
)
777 (sort (org-babel-merge-params (nth 2 info
) params
)
778 (lambda (el1 el2
) (string< (symbol-name (car el1
))
779 (symbol-name (car el2
)))))))
780 (body (setf (nth 1 info
)
781 (if (org-babel-noweb-p params
:eval
)
782 (org-babel-expand-noweb-references info
) (nth 1 info
))))
783 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
784 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
787 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
788 (org-babel-expand-body:generic
789 body params
(and (fboundp assignments-cmd
)
790 (funcall assignments-cmd params
))))))
791 (if (org-called-interactively-p 'any
)
793 expanded
(concat "*Org-Babel Preview " (buffer-name) "[ " lang
" ]*"))
796 (defun org-babel-edit-distance (s1 s2
)
797 "Return the edit (levenshtein) distance between strings S1 S2."
798 (let* ((l1 (length s1
))
800 (dist (vconcat (mapcar (lambda (_) (make-vector (1+ l2
) nil
))
801 (number-sequence 1 (1+ l1
)))))
802 (in (lambda (i j
) (aref (aref dist i
) j
))))
803 (setf (aref (aref dist
0) 0) 0)
804 (dolist (j (number-sequence 1 l2
))
805 (setf (aref (aref dist
0) j
) j
))
806 (dolist (i (number-sequence 1 l1
))
807 (setf (aref (aref dist i
) 0) i
)
808 (dolist (j (number-sequence 1 l2
))
809 (setf (aref (aref dist i
) j
)
811 (1+ (funcall in
(1- i
) j
))
812 (1+ (funcall in i
(1- j
)))
813 (+ (if (equal (aref s1
(1- i
)) (aref s2
(1- j
))) 0 1)
814 (funcall in
(1- i
) (1- j
)))))))
817 (defun org-babel-combine-header-arg-lists (original &rest others
)
818 "Combine a number of lists of header argument names and arguments."
819 (let ((results (copy-sequence original
)))
820 (dolist (new-list others
)
821 (dolist (arg-pair new-list
)
822 (let ((header (car arg-pair
)))
824 (cons arg-pair
(org-remove-if
825 (lambda (pair) (equal header
(car pair
)))
830 (defun org-babel-check-src-block ()
831 "Check for misspelled header arguments in the current code block."
833 ;; TODO: report malformed code block
834 ;; TODO: report incompatible combinations of header arguments
835 ;; TODO: report uninitialized variables
836 (let ((too-close 2) ;; <- control closeness to report potential match
837 (names (mapcar #'symbol-name org-babel-header-arg-names
)))
838 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg
)) 1))
839 (and (org-babel-where-is-src-block-head)
840 (org-babel-parse-header-arguments
842 (match-string 4))))))
844 (when (and (not (string= header name
))
845 (<= (org-babel-edit-distance header name
) too-close
)
846 (not (member header names
)))
847 (error "Supplied header \"%S\" is suspiciously close to \"%S\""
849 (message "No suspicious header arguments found.")))
852 (defun org-babel-insert-header-arg (&optional header-arg value
)
853 "Insert a header argument selecting from lists of common args and values."
855 (let* ((info (org-babel-get-src-block-info 'light
))
858 (lang-headers (intern (concat "org-babel-header-args:" lang
)))
859 (headers (org-babel-combine-header-arg-lists
860 org-babel-common-header-args-w-values
861 (when (boundp lang-headers
) (eval lang-headers
))))
862 (header-arg (or header-arg
863 (org-icompleting-read
866 (lambda (header-spec) (symbol-name (car header-spec
)))
868 (vals (cdr (assoc (intern header-arg
) headers
)))
872 (read-from-minibuffer "value: "))
876 (let ((arg (org-icompleting-read
879 (mapcar #'symbol-name group
)))))
880 (if (and arg
(not (string= "default" arg
)))
886 (goto-char (point-at-eol))
887 (unless (= (char-before (point)) ?\
) (insert " "))
888 (insert ":" header-arg
) (when value
(insert " " value
)))))
890 ;; Add support for completing-read insertion of header arguments after ":"
891 (defun org-babel-header-arg-expand ()
892 "Call `org-babel-enter-header-arg-w-completion' in appropriate contexts."
893 (when (and (equal (char-before) ?\
:) (org-babel-where-is-src-block-head))
894 (org-babel-enter-header-arg-w-completion (match-string 2))))
896 (defun org-babel-enter-header-arg-w-completion (&optional lang
)
897 "Insert header argument appropriate for LANG with completion."
898 (let* ((lang-headers-var (intern (concat "org-babel-header-args:" lang
)))
899 (lang-headers (when (boundp lang-headers-var
) (eval lang-headers-var
)))
900 (headers-w-values (org-babel-combine-header-arg-lists
901 org-babel-common-header-args-w-values lang-headers
))
902 (headers (mapcar #'symbol-name
(mapcar #'car headers-w-values
)))
903 (header (org-completing-read "Header Arg: " headers
))
904 (args (cdr (assoc (intern header
) headers-w-values
)))
905 (arg (when (and args
(listp args
))
907 (format "%s: " header
)
908 (mapcar #'symbol-name
(apply #'append args
))))))
909 (insert (concat header
" " (or arg
"")))
912 (add-hook 'org-tab-first-hook
'org-babel-header-arg-expand
)
915 (defun org-babel-load-in-session (&optional _arg info
)
916 "Load the body of the current source-code block.
917 Evaluate the header arguments for the source block before
918 entering the session. After loading the body this pops open the
921 (let* ((info (or info
(org-babel-get-src-block-info)))
923 (params (nth 2 info
))
925 (user-error "No src code block at point")
927 (if (org-babel-noweb-p params
:eval
)
928 (org-babel-expand-noweb-references info
)
930 (session (cdr (assoc :session params
)))
931 (dir (cdr (assoc :dir params
)))
933 (or (and dir
(file-name-as-directory dir
)) default-directory
))
934 (cmd (intern (concat "org-babel-load-session:" lang
))))
935 (unless (fboundp cmd
)
936 (error "No org-babel-load-session function for %s!" lang
))
937 (pop-to-buffer (funcall cmd session body params
))
941 (defun org-babel-initiate-session (&optional arg info
)
942 "Initiate session for current code block.
943 If called with a prefix argument then resolve any variable
944 references in the header arguments and assign these variables in
945 the session. Copy the body of the code block to the kill ring."
947 (let* ((info (or info
(org-babel-get-src-block-info (not arg
))))
950 (params (nth 2 info
))
951 (session (cdr (assoc :session params
)))
952 (dir (cdr (assoc :dir params
)))
954 (or (and dir
(file-name-as-directory dir
)) default-directory
))
955 (init-cmd (intern (format "org-babel-%s-initiate-session" lang
)))
956 (prep-cmd (intern (concat "org-babel-prep-session:" lang
))))
957 (if (and (stringp session
) (string= session
"none"))
958 (error "This block is not using a session!"))
959 (unless (fboundp init-cmd
)
960 (error "No org-babel-initiate-session function for %s!" lang
))
961 (with-temp-buffer (insert (org-babel-trim body
))
962 (copy-region-as-kill (point-min) (point-max)))
964 (unless (fboundp prep-cmd
)
965 (error "No org-babel-prep-session function for %s!" lang
))
966 (funcall prep-cmd session params
))
967 (funcall init-cmd session params
)))
970 (defun org-babel-switch-to-session (&optional arg info
)
971 "Switch to the session of the current code block.
972 Uses `org-babel-initiate-session' to start the session. If called
973 with a prefix argument then this is passed on to
974 `org-babel-initiate-session'."
976 (pop-to-buffer (org-babel-initiate-session arg info
))
979 (defalias 'org-babel-pop-to-session
'org-babel-switch-to-session
)
981 (defvar org-src-window-setup
)
984 (defun org-babel-switch-to-session-with-code (&optional arg _info
)
985 "Switch to code buffer and display session."
989 (let ((other-window-buffer (window-buffer (next-window))))
990 (set-window-buffer (next-window) (current-buffer))
991 (set-window-buffer (selected-window) other-window-buffer
))
993 (info (org-babel-get-src-block-info))
994 (org-src-window-setup 'reorganize-frame
))
996 (org-babel-switch-to-session arg info
))
998 (funcall swap-windows
)))
1001 (defmacro org-babel-do-in-edit-buffer
(&rest body
)
1002 "Evaluate BODY in edit buffer if there is a code block at point.
1003 Return t if a code block was found at point, nil otherwise."
1004 `(let ((org-src-window-setup 'switch-invisibly
))
1005 (when (and (org-babel-where-is-src-block-head)
1006 (org-edit-src-code))
1007 (unwind-protect (progn ,@body
)
1008 (org-edit-src-exit))
1010 (def-edebug-spec org-babel-do-in-edit-buffer
(body))
1012 (defun org-babel-do-key-sequence-in-edit-buffer (key)
1013 "Read key sequence and execute the command in edit buffer.
1014 Enter a key sequence to be executed in the language major-mode
1015 edit buffer. For example, TAB will alter the contents of the
1016 Org-mode code block according to the effect of TAB in the
1017 language major-mode buffer. For languages that support
1018 interactive sessions, this can be used to send code from the Org
1019 buffer to the session for evaluation using the native major-mode
1020 evaluation mechanisms."
1021 (interactive "kEnter key-sequence to execute in edit buffer: ")
1022 (org-babel-do-in-edit-buffer
1024 (key-binding (or key
(read-key-sequence nil
))))))
1026 (defvar org-bracket-link-regexp
)
1028 (defun org-babel-active-location-p ()
1029 (memq (org-element-type (save-match-data (org-element-context)))
1030 '(babel-call inline-babel-call inline-src-block src-block
)))
1033 (defun org-babel-open-src-block-result (&optional re-run
)
1034 "If `point' is on a src block then open the results of the
1035 source code block, otherwise return nil. With optional prefix
1036 argument RE-RUN the source-code block is evaluated even if
1037 results already exist."
1039 (let ((info (org-babel-get-src-block-info 'light
)))
1042 ;; go to the results, if there aren't any then run the block
1043 (goto-char (or (and (not re-run
) (org-babel-where-is-src-block-result))
1044 (progn (org-babel-execute-src-block)
1045 (org-babel-where-is-src-block-result))))
1047 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
1049 (if (looking-at org-bracket-link-regexp
)
1052 (let ((r (org-babel-format-result
1053 (org-babel-read-result) (cdr (assoc :sep
(nth 2 info
))))))
1054 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
1055 (delete-region (point-min) (point-max))
1060 (defmacro org-babel-map-src-blocks
(file &rest body
)
1061 "Evaluate BODY forms on each source-block in FILE.
1062 If FILE is nil evaluate BODY forms on source blocks in current
1063 buffer. During evaluation of BODY the following local variables
1064 are set relative to the currently matched code block.
1066 full-block ------- string holding the entirety of the code block
1067 beg-block -------- point at the beginning of the code block
1068 end-block -------- point at the end of the matched code block
1069 lang ------------- string holding the language of the code block
1070 beg-lang --------- point at the beginning of the lang
1071 end-lang --------- point at the end of the lang
1072 switches --------- string holding the switches
1073 beg-switches ----- point at the beginning of the switches
1074 end-switches ----- point at the end of the switches
1075 header-args ------ string holding the header-args
1076 beg-header-args -- point at the beginning of the header-args
1077 end-header-args -- point at the end of the header-args
1078 body ------------- string holding the body of the code block
1079 beg-body --------- point at the beginning of the body
1080 end-body --------- point at the end of the body"
1081 (declare (indent 1))
1082 (let ((tempvar (make-symbol "file")))
1083 `(let* ((case-fold-search t
)
1085 (visited-p (or (null ,tempvar
)
1086 (get-file-buffer (expand-file-name ,tempvar
))))
1087 (point (point)) to-be-removed
)
1088 (save-window-excursion
1089 (when ,tempvar
(find-file ,tempvar
))
1090 (setq to-be-removed
(current-buffer))
1091 (goto-char (point-min))
1092 (while (re-search-forward org-babel-src-block-regexp nil t
)
1093 (when (org-babel-active-location-p)
1094 (goto-char (match-beginning 0))
1095 (let ((full-block (match-string 0))
1096 (beg-block (match-beginning 0))
1097 (end-block (match-end 0))
1098 (lang (match-string 2))
1099 (beg-lang (match-beginning 2))
1100 (end-lang (match-end 2))
1101 (switches (match-string 3))
1102 (beg-switches (match-beginning 3))
1103 (end-switches (match-end 3))
1104 (header-args (match-string 4))
1105 (beg-header-args (match-beginning 4))
1106 (end-header-args (match-end 4))
1107 (body (match-string 5))
1108 (beg-body (match-beginning 5))
1109 (end-body (match-end 5)))
1110 ;; Silence byte-compiler in case `body' doesn't use all
1112 (ignore full-block beg-block end-block lang
1113 beg-lang end-lang switches beg-switches
1114 end-switches header-args beg-header-args
1115 end-header-args body beg-body end-body
)
1117 (goto-char end-block
)))))
1118 (unless visited-p
(kill-buffer to-be-removed
))
1119 (goto-char point
))))
1120 (def-edebug-spec org-babel-map-src-blocks
(form body
))
1123 (defmacro org-babel-map-inline-src-blocks
(file &rest body
)
1124 "Evaluate BODY forms on each inline source-block in FILE.
1125 If FILE is nil evaluate BODY forms on source blocks in current
1127 (declare (indent 1))
1128 (let ((tempvar (make-symbol "file")))
1129 `(let* ((case-fold-search t
)
1131 (visited-p (or (null ,tempvar
)
1132 (get-file-buffer (expand-file-name ,tempvar
))))
1133 (point (point)) to-be-removed
)
1134 (save-window-excursion
1135 (when ,tempvar
(find-file ,tempvar
))
1136 (setq to-be-removed
(current-buffer))
1137 (goto-char (point-min))
1138 (while (re-search-forward org-babel-inline-src-block-regexp nil t
)
1139 (when (org-babel-active-location-p)
1140 (goto-char (match-beginning 1))
1141 (save-match-data ,@body
))
1142 (goto-char (match-end 0))))
1143 (unless visited-p
(kill-buffer to-be-removed
))
1144 (goto-char point
))))
1145 (def-edebug-spec org-babel-map-inline-src-blocks
(form body
))
1147 (defvar org-babel-lob-one-liner-regexp
)
1150 (defmacro org-babel-map-call-lines
(file &rest body
)
1151 "Evaluate BODY forms on each call line in FILE.
1152 If FILE is nil evaluate BODY forms on source blocks in current
1154 (declare (indent 1))
1155 (let ((tempvar (make-symbol "file")))
1156 `(let* ((,tempvar
,file
)
1157 (visited-p (or (null ,tempvar
)
1158 (get-file-buffer (expand-file-name ,tempvar
))))
1159 (point (point)) to-be-removed
)
1160 (save-window-excursion
1161 (when ,tempvar
(find-file ,tempvar
))
1162 (setq to-be-removed
(current-buffer))
1163 (goto-char (point-min))
1164 (while (re-search-forward org-babel-lob-one-liner-regexp nil t
)
1165 (when (org-babel-active-location-p)
1166 (goto-char (match-beginning 1))
1167 (save-match-data ,@body
))
1168 (goto-char (match-end 0))))
1169 (unless visited-p
(kill-buffer to-be-removed
))
1170 (goto-char point
))))
1171 (def-edebug-spec org-babel-map-call-lines
(form body
))
1174 (defmacro org-babel-map-executables
(file &rest body
)
1175 (declare (indent 1))
1176 (let ((tempvar (make-symbol "file"))
1177 (rx (make-symbol "rx")))
1178 `(let* ((,tempvar
,file
)
1179 (,rx
(concat "\\(" org-babel-src-block-regexp
1180 "\\|" org-babel-inline-src-block-regexp
1181 "\\|" org-babel-lob-one-liner-regexp
"\\)"))
1182 (visited-p (or (null ,tempvar
)
1183 (get-file-buffer (expand-file-name ,tempvar
))))
1184 (point (point)) to-be-removed
)
1185 (save-window-excursion
1186 (when ,tempvar
(find-file ,tempvar
))
1187 (setq to-be-removed
(current-buffer))
1188 (goto-char (point-min))
1189 (while (re-search-forward ,rx nil t
)
1190 (when (org-babel-active-location-p)
1191 (goto-char (match-beginning 1))
1192 (when (looking-at org-babel-inline-src-block-regexp
)
1194 (save-match-data ,@body
))
1195 (goto-char (match-end 0))))
1196 (unless visited-p
(kill-buffer to-be-removed
))
1197 (goto-char point
))))
1198 (def-edebug-spec org-babel-map-executables
(form body
))
1201 (defun org-babel-execute-buffer (&optional arg
)
1202 "Execute source code blocks in a buffer.
1203 Call `org-babel-execute-src-block' on every source block in
1204 the current buffer."
1206 (org-babel-eval-wipe-error-buffer)
1207 (org-save-outline-visibility t
1208 (org-babel-map-executables nil
1209 (if (looking-at org-babel-lob-one-liner-regexp
)
1210 (org-babel-lob-execute-maybe)
1211 (org-babel-execute-src-block arg
)))))
1214 (defun org-babel-execute-subtree (&optional arg
)
1215 "Execute source code blocks in a subtree.
1216 Call `org-babel-execute-src-block' on every source block in
1217 the current subtree."
1221 (org-narrow-to-subtree)
1222 (org-babel-execute-buffer arg
)
1226 (defun org-babel-sha1-hash (&optional info
)
1227 "Generate an sha1 hash based on the value of info."
1229 (let ((print-level nil
)
1230 (info (or info
(org-babel-get-src-block-info))))
1232 (sort (copy-sequence (nth 2 info
))
1233 (lambda (a b
) (string< (car a
) (car b
)))))
1234 (let* ((rm (lambda (lst)
1235 (dolist (p '("replace" "silent" "none"
1236 "append" "prepend"))
1237 (setq lst
(remove p lst
)))
1240 (let ((v (if (and (listp (cdr arg
)) (null (cddr arg
)))
1241 (copy-sequence (cdr arg
))
1243 (when (and v
(not (and (sequencep v
)
1247 ((and (listp v
) ; lists are sorted
1248 (member (car arg
) '(:result-params
)))
1249 (sort (funcall rm v
) #'string
<))
1250 ((and (stringp v
) ; strings are sorted
1251 (member (car arg
) '(:results
:exports
)))
1252 (mapconcat #'identity
(sort (funcall rm
(split-string v
))
1257 (params (nth 2 info
))
1258 (body (if (org-babel-noweb-p params
:eval
)
1259 (org-babel-expand-noweb-references info
) (nth 1 info
)))
1260 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
1261 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
1264 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
1265 (org-babel-expand-body:generic
1266 body params
(and (fboundp assignments-cmd
)
1267 (funcall assignments-cmd params
))))))
1268 (let* ((it (format "%s-%s"
1271 (delq nil
(mapcar (lambda (arg)
1272 (let ((normalized (funcall norm arg
)))
1274 (format "%S" normalized
))))
1278 (when (org-called-interactively-p 'interactive
) (message hash
))
1281 (defun org-babel-current-result-hash (&optional info
)
1282 "Return the current in-buffer hash."
1283 (org-babel-where-is-src-block-result nil info
)
1284 (org-no-properties (match-string 5)))
1286 (defun org-babel-set-current-result-hash (hash info
)
1287 "Set the current in-buffer hash to HASH."
1288 (org-babel-where-is-src-block-result nil info
)
1289 (save-excursion (goto-char (match-beginning 5))
1290 (mapc #'delete-overlay
(overlays-at (point)))
1291 (forward-char org-babel-hash-show
)
1292 (mapc #'delete-overlay
(overlays-at (point)))
1293 (replace-match hash nil nil nil
5)
1294 (goto-char (point-at-bol))
1295 (org-babel-hide-hash)))
1297 (defun org-babel-hide-hash ()
1298 "Hide the hash in the current results line.
1299 Only the initial `org-babel-hash-show' characters of the hash
1300 will remain visible."
1301 (add-to-invisibility-spec '(org-babel-hide-hash . t
))
1303 (when (and (re-search-forward org-babel-result-regexp nil t
)
1305 (let* ((start (match-beginning 5))
1306 (hide-start (+ org-babel-hash-show start
))
1308 (hash (match-string 5))
1310 (setq ov1
(make-overlay start hide-start
))
1311 (setq ov2
(make-overlay hide-start end
))
1312 (overlay-put ov2
'invisible
'org-babel-hide-hash
)
1313 (overlay-put ov1
'babel-hash hash
)))))
1315 (defun org-babel-hide-all-hashes ()
1316 "Hide the hash in the current buffer.
1317 Only the initial `org-babel-hash-show' characters of each hash
1318 will remain visible. This function should be called as part of
1319 the `org-mode-hook'."
1321 (while (and (not org-babel-hash-show-time
)
1322 (re-search-forward org-babel-result-regexp nil t
))
1323 (goto-char (match-beginning 0))
1324 (org-babel-hide-hash)
1325 (goto-char (match-end 0)))))
1326 (add-hook 'org-mode-hook
'org-babel-hide-all-hashes
)
1328 (defun org-babel-hash-at-point (&optional point
)
1329 "Return the value of the hash at POINT.
1331 The hash is also added as the last element of the kill ring.
1332 This can be called with \\[org-ctrl-c-ctrl-c]."
1334 (let ((hash (car (delq nil
(mapcar
1335 (lambda (ol) (overlay-get ol
'babel-hash
))
1336 (overlays-at (or point
(point))))))))
1337 (when hash
(kill-new hash
) (message hash
))))
1338 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-hash-at-point
)
1340 (defun org-babel-result-hide-spec ()
1341 "Hide portions of results lines.
1342 Add `org-babel-hide-result' as an invisibility spec for hiding
1343 portions of results lines."
1344 (add-to-invisibility-spec '(org-babel-hide-result . t
)))
1345 (add-hook 'org-mode-hook
'org-babel-result-hide-spec
)
1347 (defvar org-babel-hide-result-overlays nil
1348 "Overlays hiding results.")
1350 (defun org-babel-result-hide-all ()
1351 "Fold all results in the current buffer."
1353 (org-babel-show-result-all)
1355 (while (re-search-forward org-babel-result-regexp nil t
)
1356 (save-excursion (goto-char (match-beginning 0))
1357 (org-babel-hide-result-toggle-maybe)))))
1359 (defun org-babel-show-result-all ()
1360 "Unfold all results in the current buffer."
1361 (mapc 'delete-overlay org-babel-hide-result-overlays
)
1362 (setq org-babel-hide-result-overlays nil
))
1365 (defun org-babel-hide-result-toggle-maybe ()
1366 "Toggle visibility of result at point."
1368 (let ((case-fold-search t
))
1370 (beginning-of-line 1)
1371 (looking-at org-babel-result-regexp
))
1372 (progn (org-babel-hide-result-toggle)
1373 t
) ;; to signal that we took action
1374 nil
))) ;; to signal that we did not
1376 (defun org-babel-hide-result-toggle (&optional force
)
1377 "Toggle the visibility of the current result."
1381 (if (re-search-forward org-babel-result-regexp nil t
)
1382 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
1384 (while (looking-at org-babel-multi-line-header-regexp
)
1386 (goto-char (- (org-babel-result-end) 1)) (point)))
1388 (if (memq t
(mapcar (lambda (overlay)
1389 (eq (overlay-get overlay
'invisible
)
1390 'org-babel-hide-result
))
1391 (overlays-at start
)))
1392 (if (or (not force
) (eq force
'off
))
1394 (when (member ov org-babel-hide-result-overlays
)
1395 (setq org-babel-hide-result-overlays
1396 (delq ov org-babel-hide-result-overlays
)))
1397 (when (eq (overlay-get ov
'invisible
)
1398 'org-babel-hide-result
)
1399 (delete-overlay ov
)))
1400 (overlays-at start
)))
1401 (setq ov
(make-overlay start end
))
1402 (overlay-put ov
'invisible
'org-babel-hide-result
)
1403 ;; make the block accessible to isearch
1405 ov
'isearch-open-invisible
1407 (when (member ov org-babel-hide-result-overlays
)
1408 (setq org-babel-hide-result-overlays
1409 (delq ov org-babel-hide-result-overlays
)))
1410 (when (eq (overlay-get ov
'invisible
)
1411 'org-babel-hide-result
)
1412 (delete-overlay ov
))))
1413 (push ov org-babel-hide-result-overlays
)))
1414 (error "Not looking at a result line"))))
1416 ;; org-tab-after-check-for-cycling-hook
1417 (add-hook 'org-tab-first-hook
'org-babel-hide-result-toggle-maybe
)
1418 ;; Remove overlays when changing major mode
1419 (add-hook 'org-mode-hook
1420 (lambda () (org-add-hook 'change-major-mode-hook
1421 'org-babel-show-result-all
'append
'local
)))
1423 (defvar org-file-properties
)
1424 (defun org-babel-params-from-properties (&optional lang
)
1425 "Retrieve parameters specified as properties.
1426 Return a list of association lists of source block params
1427 specified in the properties of the current outline entry."
1430 ;; DEPRECATED header arguments specified as separate property at
1431 ;; point of definition.
1432 (org-babel-parse-multiple-vars
1436 (let* ((arg (symbol-name (car header
)))
1437 (val (org-entry-get (point) arg t
)))
1439 (cons (intern (concat ":" arg
))
1440 (org-babel-read val
)))))
1441 (org-babel-combine-header-arg-lists
1442 org-babel-common-header-args-w-values
1443 (let ((sym (intern (concat "org-babel-header-args:" lang
))))
1444 (and (boundp sym
) (symbol-value sym
)))))))
1445 ;; header arguments specified with the header-args property at
1447 (org-babel-parse-header-arguments
1448 (org-entry-get org-babel-current-src-block-location
1451 (and lang
; language-specific header arguments at point of call
1452 (org-babel-parse-header-arguments
1453 (org-entry-get org-babel-current-src-block-location
1454 (concat "header-args:" lang
)
1457 (defvar org-src-preserve-indentation
) ;; declare defcustom from org-src
1458 (defun org-babel-parse-src-block-match ()
1459 "Parse the results from a match of the `org-babel-src-block-regexp'."
1460 (let* ((block-indentation (string-width (match-string 1)))
1461 (lang (org-match-string-no-properties 2))
1462 (lang-headers (intern (concat "org-babel-default-header-args:" lang
)))
1463 (switches (match-string 3))
1464 (body (let* ((body (org-match-string-no-properties 5))
1465 (sub-length (- (length body
) 1)))
1466 (if (and (> sub-length
0)
1467 (string= "\n" (substring body sub-length
)))
1468 (substring body
0 sub-length
)
1470 (preserve-indentation (or org-src-preserve-indentation
1472 (string-match "-i\\>" switches
)))))
1474 ;; get block body less properties, protective commas, and indentation
1477 (insert (org-unescape-code-in-string body
))
1478 (unless preserve-indentation
(org-do-remove-indentation))
1480 (apply #'org-babel-merge-params
1481 org-babel-default-header-args
1482 (when (boundp lang-headers
) (eval lang-headers
))
1484 (org-babel-params-from-properties lang
)
1485 (list (org-babel-parse-header-arguments
1486 (org-no-properties (or (match-string 4) ""))))))
1488 block-indentation
)))
1490 (defun org-babel-parse-inline-src-block-match ()
1491 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
1492 (let* ((lang (org-no-properties (match-string 2)))
1493 (lang-headers (intern (concat "org-babel-default-header-args:" lang
))))
1495 (org-unescape-code-in-string (org-no-properties (match-string 5)))
1496 (apply #'org-babel-merge-params
1497 org-babel-default-inline-header-args
1498 (if (boundp lang-headers
) (eval lang-headers
) nil
)
1500 (org-babel-params-from-properties lang
)
1501 (list (org-babel-parse-header-arguments
1502 (org-no-properties (or (match-string 4) ""))))))
1505 (defun org-babel-balanced-split (string alts
)
1506 "Split STRING on instances of ALTS.
1507 ALTS is a cons of two character options where each option may be
1508 either the numeric code of a single character or a list of
1509 character alternatives. For example to split on balanced
1510 instances of \"[ \t]:\" set ALTS to ((32 9) . 58)."
1511 (let* ((matches (lambda (ch spec
) (if (listp spec
) (member ch spec
) (equal spec ch
))))
1512 (matched (lambda (ch last
)
1514 (and (funcall matches ch
(cdr alts
))
1515 (funcall matches last
(car alts
)))
1516 (funcall matches ch alts
))))
1517 (balance 0) (last 0)
1519 (mapc (lambda (ch) ; split on [], (), "" balanced instances of [ \t]:
1520 (setq balance
(+ balance
1521 (cond ((or (equal 91 ch
) (equal 40 ch
)) 1)
1522 ((or (equal 93 ch
) (equal 41 ch
)) -
1)
1524 (when (and (equal 34 ch
) (not (equal 92 last
)))
1525 (setq quote
(not quote
)))
1526 (setq partial
(cons ch partial
))
1527 (when (and (= balance
0) (not quote
) (funcall matched ch last
))
1528 (setq lst
(cons (apply #'string
(nreverse
1535 (string-to-list string
))
1536 (nreverse (cons (apply #'string
(nreverse partial
)) lst
))))
1538 (defun org-babel-join-splits-near-ch (ch list
)
1539 "Join splits where \"=\" is on either end of the split."
1540 (let ((last= (lambda (str) (= ch
(aref str
(1- (length str
))))))
1541 (first= (lambda (str) (= ch
(aref str
0)))))
1543 (org-reduce (lambda (acc el
)
1544 (let ((head (car acc
)))
1545 (if (and head
(or (funcall last
= head
) (funcall first
= el
)))
1546 (cons (concat head el
) (cdr acc
))
1548 list
:initial-value nil
))))
1550 (defun org-babel-parse-header-arguments (arg-string)
1551 "Parse a string of header arguments returning an alist."
1552 (when (> (length arg-string
) 0)
1553 (org-babel-parse-multiple-vars
1558 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1560 (cons (intern (match-string 1 arg
))
1561 (org-babel-read (org-babel-chomp (match-string 2 arg
))))
1562 (cons (intern (org-babel-chomp arg
)) nil
)))
1563 (let ((raw (org-babel-balanced-split arg-string
'((32 9) .
58))))
1564 (cons (car raw
) (mapcar (lambda (r) (concat ":" r
)) (cdr raw
)))))))))
1566 (defun org-babel-parse-multiple-vars (header-arguments)
1567 "Expand multiple variable assignments behind a single :var keyword.
1569 This allows expression of multiple variables with one :var as
1572 #+PROPERTY: var foo=1, bar=2"
1574 (mapc (lambda (pair)
1575 (if (eq (car pair
) :var
)
1576 (mapcar (lambda (v) (push (cons :var
(org-babel-trim v
)) results
))
1577 (org-babel-join-splits-near-ch
1578 61 (org-babel-balanced-split (cdr pair
) 32)))
1579 (push pair results
)))
1581 (nreverse results
)))
1583 (defun org-babel-process-params (params)
1584 "Expand variables in PARAMS and add summary parameters."
1585 (let* ((processed-vars (mapcar (lambda (el)
1586 (if (consp (cdr el
))
1588 (org-babel-ref-parse (cdr el
))))
1589 (org-babel-get-header params
:var
)))
1590 (vars-and-names (if (and (assoc :colname-names params
)
1591 (assoc :rowname-names params
))
1592 (list processed-vars
)
1593 (org-babel-disassemble-tables
1595 (cdr (assoc :hlines params
))
1596 (cdr (assoc :colnames params
))
1597 (cdr (assoc :rownames params
)))))
1598 (raw-result (or (cdr (assoc :results params
)) ""))
1599 (result-params (append
1600 (split-string (if (stringp raw-result
)
1603 (cdr (assoc :result-params params
)))))
1605 (mapcar (lambda (var) (cons :var var
)) (car vars-and-names
))
1607 (cons :colname-names
(or (cdr (assoc :colname-names params
))
1608 (cadr vars-and-names
)))
1609 (cons :rowname-names
(or (cdr (assoc :rowname-names params
))
1610 (caddr vars-and-names
)))
1611 (cons :result-params result-params
)
1612 (cons :result-type
(cond ((member "output" result-params
) 'output
)
1613 ((member "value" result-params
) 'value
)
1616 (lambda (x) (memq (car x
) '(:colname-names
:rowname-names
:result-params
1617 :result-type
:var
)))
1620 ;; row and column names
1621 (defun org-babel-del-hlines (table)
1622 "Remove all `hline's from TABLE."
1623 (remq 'hline table
))
1625 (defun org-babel-get-colnames (table)
1626 "Return the column names of TABLE.
1627 Return a cons cell, the `car' of which contains the TABLE less
1628 colnames, and the `cdr' of which contains a list of the column
1630 (if (equal 'hline
(nth 1 table
))
1631 (cons (cddr table
) (car table
))
1632 (cons (cdr table
) (car table
))))
1634 (defun org-babel-get-rownames (table)
1635 "Return the row names of TABLE.
1636 Return a cons cell, the `car' of which contains the TABLE less
1637 rownames, and the `cdr' of which contains a list of the rownames.
1638 Note: this function removes any hlines in TABLE."
1639 (let* ((table (org-babel-del-hlines table
))
1640 (rownames (funcall (lambda ()
1646 (setq tp
(cdr tp
))))
1648 (cons table rownames
)))
1650 (defun org-babel-put-colnames (table colnames
)
1651 "Add COLNAMES to TABLE if they exist."
1652 (if colnames
(apply 'list colnames
'hline table
) table
))
1654 (defun org-babel-put-rownames (table rownames
)
1655 "Add ROWNAMES to TABLE if they exist."
1657 (mapcar (lambda (row)
1659 (cons (or (pop rownames
) "") row
)
1663 (defun org-babel-pick-name (names selector
)
1664 "Select one out of an alist of row or column names.
1665 SELECTOR can be either a list of names in which case those names
1666 will be returned directly, or an index into the list NAMES in
1667 which case the indexed names will be return."
1668 (if (listp selector
)
1671 (if (and selector
(symbolp selector
) (not (equal t selector
)))
1672 (cdr (assoc selector names
))
1673 (if (integerp selector
)
1674 (nth (- selector
1) names
)
1675 (cdr (car (last names
))))))))
1677 (defun org-babel-disassemble-tables (vars hlines colnames rownames
)
1678 "Parse tables for further processing.
1679 Process the variables in VARS according to the HLINES,
1680 ROWNAMES and COLNAMES header arguments. Return a list consisting
1681 of the vars, cnames and rnames."
1682 (let (cnames rnames
)
1686 (when (listp (cdr var
))
1687 (when (and (not (equal colnames
"no"))
1688 (or colnames
(and (equal (nth 1 (cdr var
)) 'hline
)
1689 (not (member 'hline
(cddr (cdr var
)))))))
1690 (let ((both (org-babel-get-colnames (cdr var
))))
1691 (setq cnames
(cons (cons (car var
) (cdr both
))
1693 (setq var
(cons (car var
) (car both
)))))
1694 (when (and rownames
(not (equal rownames
"no")))
1695 (let ((both (org-babel-get-rownames (cdr var
))))
1696 (setq rnames
(cons (cons (car var
) (cdr both
))
1698 (setq var
(cons (car var
) (car both
)))))
1699 (when (and hlines
(not (equal hlines
"yes")))
1700 (setq var
(cons (car var
) (org-babel-del-hlines (cdr var
))))))
1703 (reverse cnames
) (reverse rnames
))))
1705 (defun org-babel-reassemble-table (table colnames rownames
)
1706 "Add column and row names to a table.
1707 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1708 to the table for reinsertion to org-mode."
1710 (let ((table (if (and rownames
(= (length table
) (length rownames
)))
1711 (org-babel-put-rownames table rownames
) table
)))
1712 (if (and colnames
(listp (car table
)) (= (length (car table
))
1714 (org-babel-put-colnames table colnames
) table
))
1717 (defun org-babel-where-is-src-block-head (&optional src-block
)
1718 "Find where the current source block begins.
1720 If optional argument SRC-BLOCK is `src-block' type element, find
1721 its current beginning instead.
1723 Return the point at the beginning of the current source block.
1724 Specifically at the beginning of the #+BEGIN_SRC line. Also set
1725 match-data relatively to `org-babel-src-block-regexp', which see.
1726 If the point is not on a source block then return nil."
1727 (let ((element (or src-block
(org-element-at-point))))
1728 (when (eq (org-element-type element
) 'src-block
)
1729 (let ((end (org-element-property :end element
)))
1730 (org-with-wide-buffer
1731 ;; Ensure point is not on a blank line after the block.
1733 (skip-chars-forward " \r\t\n" end
)
1734 (when (< (point) end
)
1735 (prog1 (goto-char (org-element-property :post-affiliated element
))
1736 (looking-at org-babel-src-block-regexp
))))))))
1739 (defun org-babel-goto-src-block-head ()
1740 "Go to the beginning of the current code block."
1742 (let ((head (org-babel-where-is-src-block-head)))
1743 (if head
(goto-char head
) (error "Not currently in a code block"))))
1746 (defun org-babel-goto-named-src-block (name)
1747 "Go to a named source-code block."
1749 (let ((completion-ignore-case t
)
1750 (case-fold-search t
)
1751 (under-point (thing-at-point 'line
)))
1752 (list (org-icompleting-read
1753 "source-block name: " (org-babel-src-block-names) nil t
1756 ((string-match (org-babel-noweb-wrap) under-point
)
1757 (let ((block-name (match-string 1 under-point
)))
1758 (string-match "[^(]*" block-name
)
1759 (match-string 0 block-name
)))
1761 ((string-match org-babel-lob-one-liner-regexp under-point
)
1762 (let ((source-info (car (org-babel-lob-get-info))))
1763 (if (string-match "^\\([^\\[]+?\\)\\(\\[.*\\]\\)?(" source-info
)
1764 (let ((source-name (match-string 1 source-info
)))
1767 ((string-match (concat "#\\+" org-babel-results-keyword
1768 "\\:\s+\\([^\\(]*\\)") under-point
)
1769 (match-string 1 under-point
))
1771 ((and (thing-at-point 'symbol
))
1772 (org-babel-find-named-block (thing-at-point 'symbol
))
1773 (thing-at-point 'symbol
))
1775 (let ((point (org-babel-find-named-block name
)))
1777 ;; taken from `org-open-at-point'
1778 (progn (org-mark-ring-push) (goto-char point
) (org-show-context))
1779 (message "source-code block `%s' not found in this buffer" name
))))
1781 (defun org-babel-find-named-block (name)
1782 "Find a named source-code block.
1783 Return the location of the source block identified by source
1784 NAME, or nil if no such block exists. Set match data according
1785 to `org-babel-named-src-block-regexp'."
1787 (goto-char (point-min))
1789 (org-next-block 1 nil
(org-babel-named-src-block-regexp-for-name name
)))))
1791 (defun org-babel-src-block-names (&optional file
)
1792 "Returns the names of source blocks in FILE or the current buffer."
1793 (when file
(find-file file
))
1795 (goto-char (point-min))
1796 (let ((re (org-babel-named-src-block-regexp-for-name))
1798 (while (ignore-errors (org-next-block 1 nil re
))
1799 (push (org-match-string-no-properties 9) names
))
1803 (defun org-babel-goto-named-result (name)
1804 "Go to a named result."
1806 (let ((completion-ignore-case t
))
1807 (list (org-icompleting-read "source-block name: "
1808 (org-babel-result-names) nil t
))))
1809 (let ((point (org-babel-find-named-result name
)))
1811 ;; taken from `org-open-at-point'
1812 (progn (goto-char point
) (org-show-context))
1813 (message "result `%s' not found in this buffer" name
))))
1815 (defun org-babel-find-named-result (name &optional point
)
1816 "Find a named result.
1817 Return the location of the result named NAME in the current
1818 buffer or nil if no such result exists."
1820 (let ((case-fold-search t
))
1821 (goto-char (or point
(point-min)))
1822 (catch 'is-a-code-block
1823 (when (re-search-forward
1824 (concat org-babel-result-regexp
1825 "[ \t]" (regexp-quote name
) "[ \t]*[\n\f\v\r]")
1827 (when (and (string= "name" (downcase (match-string 1)))
1828 (or (beginning-of-line 1)
1829 (looking-at org-babel-src-block-regexp
)
1830 (looking-at org-babel-multi-line-header-regexp
)
1831 (looking-at org-babel-lob-one-liner-regexp
)))
1832 (throw 'is-a-code-block
(org-babel-find-named-result name
(point))))
1833 (beginning-of-line 0) (point))))))
1835 (defun org-babel-result-names (&optional file
)
1836 "Returns the names of results in FILE or the current buffer."
1838 (when file
(find-file file
)) (goto-char (point-min))
1839 (let ((case-fold-search t
) names
)
1840 (while (re-search-forward org-babel-result-w-name-regexp nil t
)
1841 (setq names
(cons (match-string 4) names
)))
1845 (defun org-babel-next-src-block (&optional arg
)
1846 "Jump to the next source block.
1847 With optional prefix argument ARG, jump forward ARG many source blocks."
1849 (org-next-block arg nil org-babel-src-block-regexp
))
1852 (defun org-babel-previous-src-block (&optional arg
)
1853 "Jump to the previous source block.
1854 With optional prefix argument ARG, jump backward ARG many source blocks."
1856 (org-previous-block arg org-babel-src-block-regexp
))
1858 (defvar org-babel-load-languages
)
1861 (defun org-babel-mark-block ()
1862 "Mark current src block."
1864 (let ((head (org-babel-where-is-src-block-head)))
1868 (looking-at org-babel-src-block-regexp
))
1869 (push-mark (match-end 5) nil t
)
1870 (goto-char (match-beginning 5)))))
1872 (defun org-babel-demarcate-block (&optional arg
)
1873 "Wrap or split the code in the region or on the point.
1874 When called from inside of a code block the current block is
1875 split. When called from outside of a code block a new code block
1876 is created. In both cases if the region is demarcated and if the
1877 region is not active then the point is demarcated."
1879 (let* ((info (org-babel-get-src-block-info 'light
))
1880 (start (org-babel-where-is-src-block-head))
1881 (block (and start
(match-string 0)))
1882 (headers (and start
(match-string 4)))
1883 (stars (concat (make-string (or (org-current-level) 1) ?
*) " "))
1884 (lower-case-p (and block
1885 (let (case-fold-search)
1886 (org-string-match-p "#\\+begin_src" block
)))))
1892 (let ((lang (nth 0 info
))
1893 (indent (make-string (nth 5 info
) ?
)))
1894 (when (string-match "^[[:space:]]*$"
1895 (buffer-substring (point-at-bol)
1897 (delete-region (point-at-bol) (point-at-eol)))
1899 (if (looking-at "^") "" "\n")
1900 indent
(funcall (if lower-case-p
'downcase
'upcase
) "#+end_src\n")
1901 (if arg stars indent
) "\n"
1902 indent
(funcall (if lower-case-p
'downcase
'upcase
) "#+begin_src ")
1904 (if (> (length headers
) 1)
1905 (concat " " headers
) headers
)
1906 (if (looking-at "[\n\r]")
1908 (concat "\n" (make-string (current-column) ?
)))))))
1909 (move-end-of-line 2))
1910 (sort (if (org-region-active-p) (list (mark) (point)) (list (point))) #'>))
1911 (let ((start (point))
1912 (lang (org-icompleting-read
1914 (mapcar #'symbol-name
1916 (append (mapcar #'car org-babel-load-languages
)
1917 (mapcar (lambda (el) (intern (car el
)))
1918 org-src-lang-modes
))))))
1919 (body (delete-and-extract-region
1920 (if (org-region-active-p) (mark) (point)) (point))))
1921 (insert (concat (if (looking-at "^") "" "\n")
1922 (if arg
(concat stars
"\n") "")
1923 (funcall (if lower-case-p
'downcase
'upcase
) "#+begin_src ")
1926 (if (or (= (length body
) 0)
1927 (string-match "[\r\n]$" body
)) "" "\n")
1928 (funcall (if lower-case-p
'downcase
'upcase
) "#+end_src\n")))
1929 (goto-char start
) (move-end-of-line 1)))))
1931 (defvar org-babel-lob-one-liner-regexp
)
1932 (defun org-babel-where-is-src-block-result (&optional insert info hash indent
)
1933 "Find where the current source block results begin.
1934 Return the point at the beginning of the result of the current
1935 source block. Specifically at the beginning of the results line.
1936 If no result exists for this block then create a results line
1937 following the source block."
1939 (let* ((case-fold-search t
)
1940 (on-lob-line (save-excursion
1941 (beginning-of-line 1)
1942 (looking-at org-babel-lob-one-liner-regexp
)))
1943 (inlinep (when (org-babel-get-inline-src-block-matches)
1945 (name (nth 4 (or info
(org-babel-get-src-block-info 'light
))))
1946 (head (unless on-lob-line
(org-babel-where-is-src-block-head)))
1948 (when head
(goto-char head
))
1949 (org-with-wide-buffer
1951 found
;; was there a result (before we potentially insert one)
1956 ;; - return t if it is found, else return nil
1957 ;; - if it does not need to be rebuilt, then don't set end
1958 ;; - if it does need to be rebuilt then do set end
1959 name
(setq beg
(org-babel-find-named-result name
))
1961 (when (and hash
(not (string= hash
(match-string 5))))
1962 (goto-char beg
) (setq end beg
) ;; beginning of result
1964 (delete-region end
(org-babel-result-end)) nil
)))
1967 ;; - return t if it is found, else return nil
1968 ;; - if it is found, and the hash doesn't match, delete and set end
1969 (or on-lob-line
(re-search-forward "^[ \t]*#\\+end_src" nil t
))
1970 (progn (end-of-line 1)
1971 (if (eobp) (insert "\n") (forward-char 1))
1975 (progn ;; unnamed results line already exists
1977 (while (re-search-forward "[^ \f\t\n\r\v]" nil t
)
1978 (beginning-of-line 1)
1980 ((looking-at (concat org-babel-result-regexp
"\n"))
1981 (throw 'non-comment t
))
1982 ((and (looking-at "^[ \t]*#")
1984 org-babel-lob-one-liner-regexp
)))
1986 (t (throw 'non-comment nil
))))))
1987 (let ((this-hash (match-string 5)))
1989 ;; must remove and rebuild if hash!=old-hash
1990 (if (and hash
(not (string= hash this-hash
)))
1992 (setq end
(point-at-bol))
1994 (delete-region end
(org-babel-result-end))
1996 (setq end nil
))))))))))
1997 (if (not (and insert end
)) found
2000 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
2001 (when (wholenump indent
) (indent-to indent
))
2003 "#+" org-babel-results-keyword
2005 (if org-babel-hash-show-time
2007 "["(format-time-string "<%Y-%m-%d %H:%M:%S>")" "hash
"]")
2008 (concat "["hash
"]")))
2010 (when name
(concat " " name
)) "\n"))
2011 (unless beg
(insert "\n") (backward-char))
2012 (beginning-of-line 0)
2013 (when hash
(org-babel-hide-hash))
2016 (defvar org-block-regexp
)
2017 (defun org-babel-read-result ()
2018 "Read the result at `point' into emacs-lisp."
2019 (let ((case-fold-search t
) result-string
)
2021 ((org-at-table-p) (org-babel-read-table))
2022 ((org-at-item-p) (org-babel-read-list))
2023 ((looking-at org-bracket-link-regexp
) (org-babel-read-link))
2024 ((looking-at org-block-regexp
) (org-remove-indentation (match-string 4)))
2025 ((or (looking-at "^[ \t]*: ") (looking-at "^[ \t]*:$"))
2028 (mapconcat (lambda (line)
2029 (or (and (> (length line
) 1)
2030 (string-match "^[ \t]*: ?\\(.+\\)" line
)
2031 (match-string 1 line
))
2035 (point) (org-babel-result-end)) "[\r\n]+")
2037 (or (org-babel-number-p result-string
) result-string
))
2038 ((looking-at org-babel-result-regexp
)
2039 (save-excursion (forward-line 1) (org-babel-read-result))))))
2041 (defun org-babel-read-table ()
2042 "Read the table at `point' into emacs-lisp."
2043 (mapcar (lambda (row)
2044 (if (and (symbolp row
) (equal row
'hline
)) row
2045 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
)) row
)))
2046 (org-table-to-lisp)))
2048 (defun org-babel-read-list ()
2049 "Read the list at `point' into emacs-lisp."
2050 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
))
2051 (mapcar #'cadr
(cdr (org-list-parse-list)))))
2053 (defvar org-link-types-re
)
2054 (defun org-babel-read-link ()
2055 "Read the link at `point' into emacs-lisp.
2056 If the path of the link is a file path it is expanded using
2057 `expand-file-name'."
2058 (let* ((case-fold-search t
)
2059 (raw (and (looking-at org-bracket-link-regexp
)
2060 (org-no-properties (match-string 1))))
2061 (type (and (string-match org-link-types-re raw
)
2062 (match-string 1 raw
))))
2064 ((not type
) (expand-file-name raw
))
2065 ((string= type
"file")
2066 (and (string-match "file\\(.*\\):\\(.+\\)" raw
)
2067 (expand-file-name (match-string 2 raw
))))
2070 (defun org-babel-format-result (result &optional sep
)
2071 "Format RESULT for writing to file."
2072 (let ((echo-res (lambda (r) (if (stringp r
) r
(format "%S" r
)))))
2076 result
(list :sep
(or sep
"\t") :fmt echo-res
))
2078 (funcall echo-res result
))))
2080 (defun org-babel-insert-result
2081 (result &optional result-params info hash indent lang
)
2082 "Insert RESULT into the current buffer.
2084 By default RESULT is inserted after the end of the current source
2085 block. The RESULT of an inline source block usually will be
2086 wrapped inside a `results' macro and placed on the same line as
2087 the inline source block. The macro is stripped upon export.
2088 Multiline and non-scalar RESULTS from inline source blocks are
2089 not allowed. With optional argument RESULT-PARAMS controls
2090 insertion of results in the Org mode file. RESULT-PARAMS can
2091 take the following values:
2093 replace - (default option) insert results after the source block
2094 or inline source block replacing any previously
2097 silent -- no results are inserted into the Org-mode buffer but
2098 the results are echoed to the minibuffer and are
2099 ingested by Emacs (a potentially time consuming
2102 file ---- the results are interpreted as a file path, and are
2103 inserted into the buffer using the Org-mode file syntax.
2105 list ---- the results are interpreted as an Org-mode list.
2107 raw ----- results are added directly to the Org-mode file. This
2108 is a good option if you code block will output org-mode
2111 drawer -- results are added directly to the Org-mode file as with
2112 \"raw\", but are wrapped in a RESULTS drawer or results
2113 macro, allowing them to later be replaced or removed
2116 org ----- results are added inside of a \"src_org{}\" or \"#+BEGIN_SRC
2117 org\" block depending on whether the current source block is
2118 inline or not. They are not comma-escaped when inserted,
2119 but Org syntax here will be discarded when exporting the
2122 html ---- results are added inside of a #+BEGIN_HTML block or
2123 html export snippet depending on whether the current
2124 source block is inline or not. This is a good option
2125 if your code block will output html formatted text.
2127 latex --- results are added inside of a #+BEGIN_LATEX block or
2128 latex export snippet depending on whether the current
2129 source block is inline or not. This is a good option
2130 if your code block will output latex formatted text.
2132 code ---- the results are extracted in the syntax of the source
2133 code of the language being evaluated and are added
2134 inside of a source block with the source-code language
2135 set appropriately. Also, source block inlining is
2136 preserved in this case. Note this relies on the
2137 optional LANG argument.
2139 list ---- the results are rendered as a list. This option not
2140 allowed for inline src blocks.
2142 table --- the results are rendered as a table. This option not
2143 allowed for inline src blocks.
2145 INFO may provide the values of these header arguments (in the
2146 `header-arguments-alist' see the docstring for
2147 `org-babel-get-src-block-info'):
2149 :file --- the name of the file to which output should be written.
2151 :wrap --- the effect is similar to `latex' in RESULT-PARAMS but
2152 using the argument supplied to specify the export block
2155 (if (stringp result
)
2157 (setq result
(org-no-properties result
))
2158 (when (member "file" result-params
)
2159 (setq result
(org-babel-result-to-file
2160 result
(when (assoc :file-desc
(nth 2 info
))
2161 (or (cdr (assoc :file-desc
(nth 2 info
)))
2163 (unless (listp result
) (setq result
(format "%S" result
))))
2164 (if (and result-params
(member "silent" result-params
))
2166 (message (replace-regexp-in-string "%" "%%" (format "%S" result
)))
2171 (when (or (org-babel-get-inline-src-block-matches)
2172 (org-babel-get-lob-one-liner-matches))
2173 (goto-char (match-end 0))
2174 (org-babel-remove-inline-result)
2179 (org-babel-where-is-src-block-result t info hash indent
)))
2183 (and (member "table" result-params
) "`:results table'")
2184 (and (listp result
) "list result")
2185 (and (org-string-match-p "\n." result
) "multiline result")
2186 (and (member "list" result-params
) "`:results list'"))))
2188 (cdr (assoc :results_switches
(nth 2 info
))))
2189 (visible-beg (point-min-marker))
2190 (visible-end (point-max-marker))
2191 ;; When results exist outside of the current visible
2192 ;; region of the buffer, be sure to widen buffer to
2194 (outside-scope-p (and existing-result
2195 (or (> visible-beg existing-result
)
2196 (<= visible-end existing-result
))))
2198 (when (and (stringp result
) ; ensure results end in a newline
2200 (> (length result
) 0)
2201 (not (or (string-equal (substring result -
1) "\n")
2202 (string-equal (substring result -
1) "\r"))))
2203 (setq result
(concat result
"\n")))
2206 (when outside-scope-p
(widen))
2207 (if (not existing-result
)
2208 (setq beg
(or inlinep
(point)))
2209 (goto-char existing-result
)
2211 (re-search-forward "#" nil t
)
2212 (setq indent
(- (current-column) 1)))
2216 ((member "replace" result-params
)
2217 (delete-region (point) (org-babel-result-end)))
2218 ((member "append" result-params
)
2219 (goto-char (org-babel-result-end)) (setq beg
(point-marker)))
2220 ((member "prepend" result-params
)))) ; already there
2221 (setq results-switches
2222 (if results-switches
(concat " " results-switches
) ""))
2223 (let ((wrap (lambda (start finish
&optional no-escape no-newlines
2224 inline-start inline-finish
)
2226 (setq start inline-start
)
2227 (setq finish inline-finish
)
2228 (setq no-newlines t
))
2230 (insert (concat finish
(unless no-newlines
"\n")))
2232 (insert (concat start
(unless no-newlines
"\n")))
2234 (org-escape-code-in-region (min (point) end
) end
))
2236 (unless no-newlines
(goto-char (point-at-eol)))
2237 (setq end
(point-marker))))
2240 ;; Non-nil when result R can be turned into
2243 (null (cdr (last r
)))
2245 (lambda (e) (or (atom e
) (null (cdr (last e
)))))
2247 ;; insert results based on type
2249 ;; Do nothing for an empty result.
2251 ;; Illegal inline result or params.
2253 (error "Inline error: %s cannot be used" bad-inline-p
))
2254 ;; insert a list if preferred
2255 ((member "list" result-params
)
2258 (org-list-to-generic
2261 (lambda (el) (list nil
(if (stringp el
) el
(format "%S" el
))))
2262 (if (listp result
) result
(split-string result
"\n" t
))))
2263 '(:splicep nil
:istart
"- " :iend
"\n")))
2265 ;; Try hard to print RESULT as a table. Give up if
2266 ;; it contains an improper list.
2267 ((funcall tabulablep result
)
2269 (insert (concat (orgtbl-to-orgtbl
2272 (or (eq e
'hline
) (listp e
)))
2279 (when (org-at-table-p) (org-table-align))
2280 (goto-char (org-table-end)))
2281 ;; Print verbatim a list that cannot be turned into
2283 ((listp result
) (insert (format "%s\n" result
)))
2284 ((member "file" result-params
)
2287 (setq result
(org-macro-escape-arguments result
)))
2290 (not (member "raw" result-params
)))
2292 (insert (org-macro-escape-arguments
2293 (org-babel-chomp result
"\n"))))
2294 (t (goto-char beg
) (insert result
)))
2295 (setq end
(point-marker))
2296 ;; possibly wrap result
2298 (bad-inline-p) ; Do nothing.
2299 ((assoc :wrap
(nth 2 info
))
2300 (let ((name (or (cdr (assoc :wrap
(nth 2 info
))) "RESULTS")))
2301 (funcall wrap
(concat "#+BEGIN_" name
)
2302 (concat "#+END_" (car (org-split-string name
)))
2303 nil nil
(concat "{{{results(@@" name
":") "@@)}}}")))
2304 ((member "html" result-params
)
2305 (funcall wrap
"#+BEGIN_HTML" "#+END_HTML" nil nil
2306 "{{{results(@@html:" "@@)}}}"))
2307 ((member "latex" result-params
)
2308 (funcall wrap
"#+BEGIN_LaTeX" "#+END_LaTeX" nil nil
2309 "{{{results(@@latex:" "@@)}}}"))
2310 ((member "org" result-params
)
2311 (goto-char beg
) (if (org-at-table-p) (org-cycle))
2312 (funcall wrap
"#+BEGIN_SRC org" "#+END_SRC" nil nil
2313 "{{{results(src_org{" "})}}}"))
2314 ((member "code" result-params
)
2315 (let ((lang (or lang
"none")))
2316 (funcall wrap
(format "#+BEGIN_SRC %s%s" lang results-switches
)
2318 (format "{{{results(src_%s[%s]{" lang results-switches
)
2320 ((member "raw" result-params
)
2321 (goto-char beg
) (if (org-at-table-p) (org-cycle)))
2322 ((or (member "drawer" result-params
)
2323 ;; Stay backward compatible with <7.9.2
2324 (member "wrap" result-params
))
2325 (goto-char beg
) (if (org-at-table-p) (org-cycle))
2326 (funcall wrap
":RESULTS:" ":END:" 'no-escape nil
2327 "{{{results(" ")}}}"))
2328 ((and inlinep
(member "file" result-params
))
2329 (funcall wrap nil nil nil nil
"{{{results(" ")}}}"))
2330 ((and (not (funcall tabulablep result
))
2331 (not (member "file" result-params
)))
2332 (let ((org-babel-inline-result-wrap
2333 ;; Hard code {{{results(...)}}} on top of customization.
2334 (format "{{{results(%s)}}}" org-babel-inline-result-wrap
)))
2335 (org-babel-examplify-region beg end results-switches
)
2336 (setq end
(point))))))
2337 ;; possibly indent the results to match the #+results line
2338 (when (and (not inlinep
) (numberp indent
) indent
(> indent
0)
2339 ;; in this case `table-align' does the work for us
2340 (not (and (listp result
)
2341 (member "append" result-params
))))
2342 (indent-rigidly beg end indent
))
2344 (if (member "value" result-params
)
2345 (message "Code block returned no value.")
2346 (message "Code block produced no output."))
2347 (message "Code block evaluation complete.")))
2348 (when outside-scope-p
(narrow-to-region visible-beg visible-end
))
2349 (set-marker visible-beg nil
)
2350 (set-marker visible-end nil
))))))
2352 (defun org-babel-remove-result (&optional info keep-keyword
)
2353 "Remove the result of the current source block."
2355 (let ((location (org-babel-where-is-src-block-result nil info
)))
2358 (goto-char location
)
2359 (when (looking-at (concat org-babel-result-regexp
".*$"))
2361 (if keep-keyword
(1+ (match-end 0)) (1- (match-beginning 0)))
2362 (progn (forward-line 1) (org-babel-result-end))))))))
2364 (defun org-babel-remove-inline-result ()
2365 "Remove the result of the current inline-src-block or babel call.
2366 The result must be wrapped in a `results' macro to be removed.
2367 Leading whitespace is trimmed."
2369 (let* ((el (org-element-context))
2370 (post-blank (org-element-property :post-blank el
)))
2371 (when (memq (org-element-type el
) '(inline-src-block inline-babel-call
))
2372 (org-with-wide-buffer
2373 (goto-char (org-element-property :end el
))
2374 (let ((el (org-element-context)))
2375 (when (and (eq (org-element-type el
) 'macro
)
2376 (string= (org-element-property :key el
) "results"))
2377 (delete-region ; And leading whitespace.
2378 (- (org-element-property :begin el
) post-blank
)
2379 (- (org-element-property :end el
)
2380 (org-element-property :post-blank el
)))))))))
2382 (defun org-babel-remove-result-one-or-many (x)
2383 "Remove the result of the current source block.
2384 If called with a prefix argument, remove all result blocks
2388 (org-babel-map-src-blocks nil
(org-babel-remove-result))
2389 (org-babel-remove-result)))
2391 (defun org-babel-result-end ()
2392 "Return the point at the end of the current set of results."
2395 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
2396 ((org-at-item-p) (let* ((struct (org-list-struct))
2397 (prvs (org-list-prevs-alist struct
)))
2398 (org-list-get-list-end (point-at-bol) struct prvs
)))
2399 ((let ((case-fold-search t
)) (looking-at "^\\([ \t]*\\):results:"))
2400 (progn (re-search-forward (concat "^" (match-string 1) ":END:"))
2401 (forward-char 1) (point)))
2403 (let ((case-fold-search t
))
2404 (if (looking-at (concat "[ \t]*#\\+begin_\\([^ \t\n\r]+\\)"))
2405 (progn (re-search-forward (concat "[ \t]*#\\+end_" (match-string 1))
2408 (while (looking-at "[ \t]*\\(: \\|:$\\|\\[\\[\\)")
2412 (defun org-babel-result-to-file (result &optional description
)
2413 "Convert RESULT into an `org-mode' link with optional DESCRIPTION.
2414 If the `default-directory' is different from the containing
2415 file's directory then expand relative links."
2416 (when (stringp result
)
2417 (format "[[file:%s]%s]"
2418 (if (and default-directory
2420 (not (string= (expand-file-name default-directory
)
2422 (file-name-directory buffer-file-name
)))))
2423 (expand-file-name result default-directory
)
2425 (if description
(concat "[" description
"]") ""))))
2427 (defvar org-babel-capitalize-example-region-markers nil
2428 "Make true to capitalize begin/end example markers inserted by code blocks.")
2430 (define-obsolete-function-alias
2431 'org-babel-examplize-region
2432 'org-babel-examplify-region
"25.1")
2434 (defun org-babel-examplify-region (beg end
&optional results-switches
)
2435 "Comment out region using the inline `==' or `: ' org example quote."
2437 (let ((chars-between (lambda (b e
)
2438 (not (string-match "^[\\s]*$"
2439 (buffer-substring b e
)))))
2440 (maybe-cap (lambda (str) (if org-babel-capitalize-example-region-markers
2442 (beg-bol (save-excursion (goto-char beg
) (point-at-bol)))
2443 (end-bol (save-excursion (goto-char end
) (point-at-bol)))
2444 (end-eol (save-excursion (goto-char end
) (point-at-eol))))
2445 (if (and (not (= end end-bol
))
2446 (or (funcall chars-between beg-bol beg
)
2447 (funcall chars-between end end-eol
)))
2450 (insert (format org-babel-inline-result-wrap
2451 (prog1 (buffer-substring beg end
)
2452 (delete-region beg end
)))))
2453 (let ((size (count-lines beg end
)))
2455 (cond ((= size
0)) ; do nothing for an empty result
2456 ((< size org-babel-min-lines-for-block-output
)
2459 (beginning-of-line 1) (insert ": ") (forward-line 1)))
2462 (insert (if results-switches
2464 (funcall maybe-cap
"#+begin_example")
2466 (funcall maybe-cap
"#+begin_example\n")))
2467 (if (markerp end
) (goto-char end
) (forward-char (- end beg
)))
2468 (insert (funcall maybe-cap
"#+end_example\n")))))))))
2470 (defun org-babel-update-block-body (new-body)
2471 "Update the body of the current code block to NEW-BODY."
2472 (let ((element (org-element-at-point)))
2473 (unless (eq (org-element-type element
) 'src-block
)
2474 (error "Not in a source block"))
2475 (goto-char (org-babel-where-is-src-block-head element
))
2476 (let* ((ind (org-get-indentation))
2477 (body-start (line-beginning-position 2))
2478 (body (org-element-normalize-string
2479 (if (or org-src-preserve-indentation
2480 (org-element-property :preserve-indent element
))
2483 (insert (org-remove-indentation new-body
))
2487 (+ ind org-edit-src-content-indentation
))
2488 (buffer-string))))))
2489 (delete-region body-start
2490 (org-with-wide-buffer
2491 (goto-char (org-element-property :end element
))
2492 (skip-chars-backward " \t\n")
2493 (line-beginning-position)))
2494 (goto-char body-start
)
2497 (defun org-babel-merge-params (&rest plists
)
2498 "Combine all parameter association lists in PLISTS.
2499 Later elements of PLISTS override the values of previous elements.
2500 This takes into account some special considerations for certain
2501 parameters when merging lists."
2502 (let* ((results-exclusive-groups
2503 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2504 (cdr (assoc 'results org-babel-common-header-args-w-values
))))
2505 (exports-exclusive-groups
2506 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2507 (cdr (assoc 'exports org-babel-common-header-args-w-values
))))
2509 (e-merge (lambda (exclusive-groups &rest result-params
)
2510 ;; maintain exclusivity of mutually exclusive parameters
2512 (mapc (lambda (new-params)
2513 (mapc (lambda (new-param)
2514 (mapc (lambda (exclusive-group)
2515 (when (member new-param exclusive-group
)
2516 (mapcar (lambda (excluded-param)
2523 (setq output
(org-uniquify
2524 (cons new-param output
))))
2528 params results exports tangle noweb cache vars shebang comments padline
2537 (let ((name (if (listp (cdr pair
))
2539 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
2541 (intern (match-string 1 (cdr pair
)))))))
2545 (if (member name
(mapcar #'car vars
))
2547 (push name clearnames
)
2551 (unless (equal (car p
) name
) p
))
2554 (list (cons name pair
))))
2555 ;; if no name is given and we already have named variables
2556 ;; then assign to named variables in order
2557 (if (and vars
(nth variable-index vars
))
2558 (let ((name (car (nth variable-index vars
))))
2559 (push name clearnames
) ; clear out colnames
2562 (prog1 (setf (cddr (nth variable-index vars
))
2563 (concat (symbol-name name
) "=" (cdr pair
)))
2564 (incf variable-index
)))
2565 (error "Variable \"%s\" must be assigned a default value"
2568 (setq results
(funcall e-merge results-exclusive-groups
2571 (let ((r (cdr pair
)))
2572 (if (stringp r
) r
(eval r
)))))))
2575 (setq results
(funcall e-merge results-exclusive-groups
2577 (unless (or (member "both" exports
)
2578 (member "none" exports
)
2579 (member "code" exports
))
2580 (setq exports
(funcall e-merge exports-exclusive-groups
2581 exports
'("results"))))
2582 (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))
2585 (setq results
(funcall e-merge results-exclusive-groups
2587 (unless (or (member "both" exports
)
2588 (member "none" exports
)
2589 (member "code" exports
))
2590 (setq exports
(funcall e-merge exports-exclusive-groups
2591 exports
'("results"))))
2592 (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))
2594 (setq exports
(funcall e-merge exports-exclusive-groups
2596 (split-string (or (cdr pair
) "")))))
2597 (:tangle
;; take the latest -- always overwrite
2598 (setq tangle
(or (list (cdr pair
)) tangle
)))
2600 (setq noweb
(funcall e-merge
2601 '(("yes" "no" "tangle" "no-export"
2602 "strip-export" "eval"))
2604 (split-string (or (cdr pair
) "")))))
2606 (setq cache
(funcall e-merge
'(("yes" "no")) cache
2607 (split-string (or (cdr pair
) "")))))
2609 (setq padline
(funcall e-merge
'(("yes" "no")) padline
2610 (split-string (or (cdr pair
) "")))))
2611 (:shebang
;; take the latest -- always overwrite
2612 (setq shebang
(or (list (cdr pair
)) shebang
)))
2614 (setq comments
(funcall e-merge
'(("yes" "no")) comments
2615 (split-string (or (cdr pair
) "")))))
2616 (t ;; replace: this covers e.g. :session
2617 (setq params
(cons pair
(assq-delete-all (car pair
) params
))))))
2620 (setq vars
(reverse vars
))
2621 (while vars
(setq params
(cons (cons :var
(cddr (pop vars
))) params
)))
2622 ;; clear out col-names and row-names for replaced variables
2627 (when (assoc param params
)
2628 (setf (cdr (assoc param params
))
2629 (org-remove-if (lambda (pair) (equal (car pair
) name
))
2630 (cdr (assoc param params
))))
2631 (setf params
(org-remove-if (lambda (pair) (and (equal (car pair
) param
)
2634 (list :colname-names
:rowname-names
)))
2638 (let ((key (intern (concat ":" (symbol-name hd
))))
2640 (setf params
(cons (cons key
(mapconcat 'identity val
" ")) params
))))
2641 '(results exports tangle noweb padline cache shebang comments
))
2644 (defvar org-babel-use-quick-and-dirty-noweb-expansion nil
2645 "Set to true to use regular expressions to expand noweb references.
2646 This results in much faster noweb reference expansion but does
2647 not properly allow code blocks to inherit the \":noweb-ref\"
2648 header argument from buffer or subtree wide properties.")
2650 (defun org-babel-noweb-p (params context
)
2651 "Check if PARAMS require expansion in CONTEXT.
2652 CONTEXT may be one of :tangle, :export or :eval."
2654 (intersect (lambda (as bs
)
2656 (if (member (car as
) bs
)
2658 (funcall intersect
(cdr as
) bs
))))))
2659 (funcall intersect
(case context
2660 (:tangle
'("yes" "tangle" "no-export" "strip-export"))
2661 (:eval
'("yes" "no-export" "strip-export" "eval"))
2663 (split-string (or (cdr (assoc :noweb params
)) "")))))
2665 (defun org-babel-expand-noweb-references (&optional info parent-buffer
)
2666 "Expand Noweb references in the body of the current source code block.
2668 For example the following reference would be replaced with the
2669 body of the source-code block named `example-block'.
2673 Note that any text preceding the <<foo>> construct on a line will
2674 be interposed between the lines of the replacement text. So for
2675 example if <<foo>> is placed behind a comment, then the entire
2676 replacement text will also be commented.
2678 This function must be called from inside of the buffer containing
2679 the source-code block which holds BODY.
2681 In addition the following syntax can be used to insert the
2682 results of evaluating the source-code block named `example-block'.
2686 Any optional arguments can be passed to example-block by placing
2687 the arguments inside the parenthesis following the convention
2688 defined by `org-babel-lob'. For example
2690 <<example-block(a=9)>>
2692 would set the value of argument \"a\" equal to \"9\". Note that
2693 these arguments are not evaluated in the current source-code
2694 block but are passed literally to the \"example-block\"."
2695 (let* ((parent-buffer (or parent-buffer
(current-buffer)))
2696 (info (or info
(org-babel-get-src-block-info 'light
)))
2699 (ob-nww-start org-babel-noweb-wrap-start
)
2700 (ob-nww-end org-babel-noweb-wrap-end
)
2701 (comment (string= "noweb" (cdr (assoc :comments
(nth 2 info
)))))
2702 (rx-prefix (concat "\\(" org-babel-src-name-regexp
"\\|"
2703 ":noweb-ref[ \t]+" "\\)"))
2705 (nb-add (lambda (text) (setq new-body
(concat new-body text
))))
2706 (c-wrap (lambda (text)
2708 (funcall (intern (concat lang
"-mode")))
2709 (comment-region (point) (progn (insert text
) (point)))
2710 (org-babel-trim (buffer-string)))))
2711 index source-name evaluate prefix
)
2713 (org-set-local 'org-babel-noweb-wrap-start ob-nww-start
)
2714 (org-set-local 'org-babel-noweb-wrap-end ob-nww-end
)
2715 (insert body
) (goto-char (point-min))
2716 (setq index
(point))
2717 (while (and (re-search-forward (org-babel-noweb-wrap) nil t
))
2718 (save-match-data (setf source-name
(match-string 1)))
2719 (save-match-data (setq evaluate
(string-match "(.*)" source-name
)))
2722 (buffer-substring (match-beginning 0)
2724 (beginning-of-line 1) (point)))))
2725 ;; add interval to new-body (removing noweb reference)
2726 (goto-char (match-beginning 0))
2727 (funcall nb-add
(buffer-substring index
(point)))
2728 (goto-char (match-end 0))
2729 (setq index
(point))
2732 (with-current-buffer parent-buffer
2735 (mapconcat ;; Interpose PREFIX between every line.
2739 (let ((raw (org-babel-ref-resolve source-name
)))
2740 (if (stringp raw
) raw
(format "%S" raw
)))
2742 ;; Retrieve from the library of babel.
2743 (nth 2 (assoc (intern source-name
)
2744 org-babel-library-of-babel
))
2745 ;; Return the contents of headlines literally.
2747 (when (org-babel-ref-goto-headline-id source-name
)
2748 (org-babel-ref-headline-body)))
2749 ;; Find the expansion of reference in this buffer.
2750 (let ((rx (concat rx-prefix source-name
"[ \t\n]"))
2753 (goto-char (point-min))
2754 (if org-babel-use-quick-and-dirty-noweb-expansion
2755 (while (re-search-forward rx nil t
)
2756 (let* ((i (org-babel-get-src-block-info 'light
))
2757 (body (org-babel-expand-noweb-references i
))
2758 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2761 (let ((cs (org-babel-tangle-comment-links i
)))
2762 (concat (funcall c-wrap
(car cs
)) "\n"
2764 (funcall c-wrap
(cadr cs
))))
2766 (setq expansion
(cons sep
(cons full expansion
)))))
2767 (org-babel-map-src-blocks nil
2768 (let ((i (org-babel-get-src-block-info 'light
)))
2769 (when (equal (or (cdr (assoc :noweb-ref
(nth 2 i
)))
2772 (let* ((body (org-babel-expand-noweb-references i
))
2773 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2776 (let ((cs (org-babel-tangle-comment-links i
)))
2777 (concat (funcall c-wrap
(car cs
)) "\n"
2779 (funcall c-wrap
(cadr cs
))))
2782 (cons sep
(cons full expansion
)))))))))
2784 (mapconcat #'identity
(nreverse (cdr expansion
)) "")))
2785 ;; Possibly raise an error if named block doesn't exist.
2786 (if (or org-babel-noweb-error-all-langs
2787 (member lang org-babel-noweb-error-langs
))
2789 (org-babel-noweb-wrap source-name
)
2790 "could not be resolved (see "
2791 "`org-babel-noweb-error-langs')"))
2793 "[\n\r]") (concat "\n" prefix
))))))
2794 (funcall nb-add
(buffer-substring index
(point-max))))
2797 (defun org-babel--script-escape-inner (str)
2798 (let (in-single in-double backslash out
)
2805 (setq backslash nil
)
2807 ((and in-single
(eq ch ?
'))
2808 ;; Escaped single quote inside single quoted string:
2809 ;; emit just a single quote, since we've changed the
2810 ;; outer quotes to double.
2813 ;; Escaped double quote
2815 ;; This should be interpreted as backslash+quote,
2816 ;; not an escape. Emit a three backslashes
2817 ;; followed by a quote (because one layer of
2818 ;; quoting will be stripped by `org-babel-read').
2819 (append (list ch ?
\\ ?
\\ ?
\\) out
)
2820 ;; Otherwise we are in a double-quoted string. Emit
2821 ;; a single escaped quote
2822 (append (list ch ?
\\) out
)))
2824 ;; Escaped backslash: emit a single escaped backslash
2825 (append (list ?
\\ ?
\\) out
))
2826 ;; Other: emit a quoted backslash followed by whatever
2827 ;; the character was (because one layer of quoting will
2828 ;; be stripped by `org-babel-read').
2829 (t (append (list ch ?
\\ ?
\\) out
))))
2831 (?\
[ (if (or in-double in-single
)
2834 (?\
] (if (or in-double in-single
)
2837 (?\
{ (if (or in-double in-single
)
2840 (?\
} (if (or in-double in-single
)
2843 (?
, (if (or in-double in-single
)
2844 (cons ?
, out
) (cons ?\s out
)))
2847 (setq in-single
(not in-single
)) (cons ?
\" out
)))
2849 (append (list ?
\" ?
\\) out
)
2850 (setq in-double
(not in-double
)) (cons ?
\" out
)))
2851 (?
\\ (unless (or in-single in-double
)
2852 (error "Can't handle backslash outside string in `org-babel-script-escape'"))
2855 (t (cons ch out
))))))
2856 (string-to-list str
))
2857 (when (or in-single in-double
)
2858 (error "Unterminated string in `org-babel-script-escape'"))
2859 (apply #'string
(reverse out
))))
2861 (defun org-babel-script-escape (str &optional force
)
2862 "Safely convert tables into elisp lists."
2863 (unless (stringp str
)
2864 (error "`org-babel-script-escape' expects a string"))
2867 ((and (> (length str
) 2)
2868 (or (and (string-equal "[" (substring str
0 1))
2869 (string-equal "]" (substring str -
1)))
2870 (and (string-equal "{" (substring str
0 1))
2871 (string-equal "}" (substring str -
1)))
2872 (and (string-equal "(" (substring str
0 1))
2873 (string-equal ")" (substring str -
1)))))
2875 (concat "'" (org-babel--script-escape-inner str
)))
2877 (and (> (length str
) 2)
2878 (or (and (string-equal "'" (substring str
0 1))
2879 (string-equal "'" (substring str -
1)))
2880 ;; We need to pass double-quoted strings
2881 ;; through the backslash-twiddling bits, even
2882 ;; though we don't need to change their
2884 (and (string-equal "\"" (substring str
0 1))
2885 (string-equal "\"" (substring str -
1))))))
2886 (org-babel--script-escape-inner str
))
2888 (condition-case nil
(org-babel-read escaped
) (error escaped
))))
2890 (defun org-babel-read (cell &optional inhibit-lisp-eval
)
2891 "Convert the string value of CELL to a number if appropriate.
2892 Otherwise if CELL looks like lisp (meaning it starts with a
2893 \"(\", \"\\='\", \"\\=`\" or a \"[\") then read and evaluate it as
2894 lisp, otherwise return it unmodified as a string. Optional
2895 argument INHIBIT-LISP-EVAL inhibits lisp evaluation for
2896 situations in which is it not appropriate."
2897 (if (and (stringp cell
) (not (equal cell
"")))
2898 (or (org-babel-number-p cell
)
2899 (if (and (not inhibit-lisp-eval
)
2900 (or (member (substring cell
0 1) '("(" "'" "`" "["))
2901 (string= cell
"*this*")))
2903 (if (string= (substring cell
0 1) "\"")
2905 (progn (set-text-properties 0 (length cell
) nil cell
) cell
))))
2908 (defun org-babel-number-p (string)
2909 "If STRING represents a number return its value."
2910 (if (and (string-match "[0-9]+" string
)
2911 (string-match "^-?[0-9]*\\.?[0-9]*$" string
)
2912 (= (length (substring string
(match-beginning 0)
2915 (string-to-number string
)))
2917 (defun org-babel-import-elisp-from-file (file-name &optional separator
)
2918 "Read the results located at FILE-NAME into an elisp table.
2919 If the table is trivial, then return it as a scalar."
2921 (save-window-excursion
2925 (org-table-import file-name separator
)
2926 (delete-file file-name
)
2927 (setq result
(mapcar (lambda (row)
2928 (mapcar #'org-babel-string-read row
))
2929 (org-table-to-lisp))))
2930 (error (message "Error reading results: %s" err
) nil
)))
2931 (if (null (cdr result
)) ;; if result is trivial vector, then scalarize it
2932 (if (consp (car result
))
2933 (if (null (cdr (car result
)))
2939 (defun org-babel-string-read (cell)
2940 "Strip nested \"s from around strings."
2941 (org-babel-read (or (and (stringp cell
)
2942 (string-match "\\\"\\(.+\\)\\\"" cell
)
2943 (match-string 1 cell
))
2946 (defun org-babel-chomp (string &optional regexp
)
2947 "Strip a trailing space or carriage return from STRING.
2948 The default regexp used is \"[ \\f\\t\\n\\r\\v]\" but another one
2949 can be specified as the REGEXP argument."
2950 (let ((regexp (or regexp
"[ \f\t\n\r\v]")))
2951 (while (and (> (length string
) 0)
2952 (string-match regexp
(substring string -
1)))
2953 (setq string
(substring string
0 -
1)))
2956 (defun org-babel-trim (string &optional regexp
)
2957 "Strip a leading and trailing space or carriage return from STRING.
2958 Like `org-babel-chomp', but run on both the first and last
2959 character of the string."
2962 (org-babel-chomp (org-reverse-string string
) regexp
)) regexp
))
2964 (defun org-babel-tramp-handle-call-process-region
2965 (start end program
&optional delete buffer display
&rest args
)
2966 "Use Tramp to handle `call-process-region'.
2967 Fixes a bug in `tramp-handle-call-process-region'."
2968 (if (and (featurep 'tramp
) (file-remote-p default-directory
))
2969 (let ((tmpfile (tramp-compat-make-temp-file "")))
2970 (write-region start end tmpfile
)
2971 (when delete
(delete-region start end
))
2973 ;; (apply 'call-process program tmpfile buffer display args)
2975 (apply 'process-file program tmpfile buffer display args
)
2976 (delete-file tmpfile
)))
2977 ;; org-babel-call-process-region-original is the original emacs
2978 ;; definition. It is in scope from the let binding in
2979 ;; org-babel-execute-src-block
2980 (apply org-babel-call-process-region-original
2981 start end program delete buffer display args
)))
2983 (defun org-babel-local-file-name (file)
2984 "Return the local name component of FILE."
2985 (or (file-remote-p file
'localname
) file
))
2987 (defun org-babel-process-file-name (name &optional no-quote-p
)
2988 "Prepare NAME to be used in an external process.
2989 If NAME specifies a remote location, the remote portion of the
2990 name is removed, since in that case the process will be executing
2991 remotely. The file name is then processed by `expand-file-name'.
2992 Unless second argument NO-QUOTE-P is non-nil, the file name is
2993 additionally processed by `shell-quote-argument'"
2994 (let ((f (org-babel-local-file-name (expand-file-name name
))))
2995 (if no-quote-p f
(shell-quote-argument f
))))
2997 (defvar org-babel-temporary-directory
)
2998 (unless (or noninteractive
(boundp 'org-babel-temporary-directory
))
2999 (defvar org-babel-temporary-directory
3000 (or (and (boundp 'org-babel-temporary-directory
)
3001 (file-exists-p org-babel-temporary-directory
)
3002 org-babel-temporary-directory
)
3003 (make-temp-file "babel-" t
))
3004 "Directory to hold temporary files created to execute code blocks.
3005 Used by `org-babel-temp-file'. This directory will be removed on
3008 (defcustom org-babel-remote-temporary-directory
"/tmp/"
3009 "Directory to hold temporary files on remote hosts."
3013 (defmacro org-babel-result-cond
(result-params scalar-form
&rest table-forms
)
3014 "Call the code to parse raw string results according to RESULT-PARAMS."
3016 (debug (form form
&rest form
)))
3017 (org-with-gensyms (params)
3018 `(let ((,params
,result-params
))
3019 (unless (member "none" ,params
)
3020 (if (or (member "scalar" ,params
)
3021 (member "verbatim" ,params
)
3022 (member "html" ,params
)
3023 (member "code" ,params
)
3024 (member "pp" ,params
)
3025 (member "file" ,params
)
3026 (and (or (member "output" ,params
)
3027 (member "raw" ,params
)
3028 (member "org" ,params
)
3029 (member "drawer" ,params
))
3030 (not (member "table" ,params
))))
3033 (def-edebug-spec org-babel-result-cond
(form form body
))
3035 (defun org-babel-temp-file (prefix &optional suffix
)
3036 "Create a temporary file in the `org-babel-temporary-directory'.
3037 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
3038 value of `temporary-file-directory' temporarily set to the value
3039 of `org-babel-temporary-directory'."
3040 (if (file-remote-p default-directory
)
3042 (concat (file-remote-p default-directory
)
3044 prefix org-babel-remote-temporary-directory
))))
3045 (make-temp-file prefix nil suffix
))
3046 (let ((temporary-file-directory
3047 (or (and (boundp 'org-babel-temporary-directory
)
3048 (file-exists-p org-babel-temporary-directory
)
3049 org-babel-temporary-directory
)
3050 temporary-file-directory
)))
3051 (make-temp-file prefix nil suffix
))))
3053 (defun org-babel-remove-temporary-directory ()
3054 "Remove `org-babel-temporary-directory' on Emacs shutdown."
3055 (when (and (boundp 'org-babel-temporary-directory
)
3056 (file-exists-p org-babel-temporary-directory
))
3057 ;; taken from `delete-directory' in files.el
3060 (mapc (lambda (file)
3061 ;; This test is equivalent to
3062 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
3063 ;; but more efficient
3064 (if (eq t
(car (file-attributes file
)))
3065 (delete-directory file
)
3066 (delete-file file
)))
3067 ;; We do not want to delete "." and "..".
3068 (directory-files org-babel-temporary-directory
'full
3069 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
3070 (delete-directory org-babel-temporary-directory
))
3072 (message "Failed to remove temporary Org-babel directory %s"
3073 (if (boundp 'org-babel-temporary-directory
)
3074 org-babel-temporary-directory
3075 "[directory not defined]"))))))
3077 (add-hook 'kill-emacs-hook
'org-babel-remove-temporary-directory
)
3079 (defun org-babel-one-header-arg-safe-p (pair safe-list
)
3080 "Determine if the PAIR is a safe babel header arg according to SAFE-LIST.
3082 For the format of SAFE-LIST, see `org-babel-safe-header-args'."
3084 (keywordp (car pair
))
3085 (stringp (cdr pair
))
3087 (memq (car pair
) safe-list
)
3088 (let ((entry (assq (car pair
) safe-list
)))
3091 (cond ((functionp (cdr entry
))
3092 (funcall (cdr entry
) (cdr pair
)))
3093 ((listp (cdr entry
))
3094 (member (cdr pair
) (cdr entry
)))
3097 (defun org-babel-generate-file-param (src-name params
)
3098 "Calculate the filename for source block results.
3100 The directory is calculated from the :output-dir property of the
3101 source block; if not specified, use the current directory.
3103 If the source block has a #+NAME and the :file parameter does not
3104 contain any period characters, then the :file parameter is
3105 treated as an extension, and the output file name is the
3106 concatenation of the directory (as calculated above), the block
3107 name, a period, and the parameter value as a file extension.
3108 Otherwise, the :file parameter is treated as a full file name,
3109 and the output file name is the directory (as calculated above)
3110 plus the parameter value."
3111 (let* ((file-cons (assq :file params
))
3112 (file-ext-cons (assq :file-ext params
))
3113 (file-ext (cdr-safe file-ext-cons
))
3114 (dir (cdr-safe (assq :output-dir params
)))
3116 ;; create the output-dir if it does not exist
3118 (make-directory dir t
))
3120 ;; :file given; add :output-dir if given
3122 (setcdr file-cons
(concat (file-name-as-directory dir
) (cdr file-cons
))))
3123 ;; :file not given; compute from name and :file-ext if possible
3124 (when (and src-name file-ext
)
3126 (setq fname
(concat (file-name-as-directory (or dir
""))
3127 src-name
"." file-ext
))
3128 (setq fname
(concat src-name
"." file-ext
)))
3129 (setq params
(cons (cons :file fname
) params
))))
3132 ;;; Used by backends: R, Maxima, Octave.
3133 (defun org-babel-graphical-output-file (params)
3134 "File where a babel block should send graphical output, per PARAMS."
3135 (unless (assq :file params
)
3136 (if (assq :file-ext params
)
3137 (user-error ":file-ext given but no :file generated; did you forget to give a block a #+NAME?")
3138 (user-error "No :file header argument given; cannot create graphical result.")))
3139 (and (member "graphics" (cdr (assq :result-params params
)))
3140 (cdr (assq :file params
))))
3145 ;; generated-autoload-file: "org-loaddefs.el"
3148 ;;; ob-core.el ends here