1 ;;; ob-core.el --- working with code blocks in org-mode
3 ;; Copyright (C) 2009-2014 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
))
36 ;; dynamically scoped for tramp
37 (defvar org-babel-call-process-region-original nil
)
38 (defvar org-src-lang-modes
)
39 (defvar org-babel-library-of-babel
)
40 (declare-function show-all
"outline" ())
41 (declare-function org-every
"org" (pred seq
))
42 (declare-function org-remove-indentation
"org" (code &optional n
))
43 (declare-function org-reduce
"org" (CL-FUNC CL-SEQ
&rest CL-KEYS
))
44 (declare-function org-mark-ring-push
"org" (&optional pos buffer
))
45 (declare-function tramp-compat-make-temp-file
"tramp-compat"
46 (filename &optional dir-flag
))
47 (declare-function tramp-dissect-file-name
"tramp" (name &optional nodefault
))
48 (declare-function tramp-file-name-user
"tramp" (vec))
49 (declare-function tramp-file-name-host
"tramp" (vec))
50 (declare-function with-parsed-tramp-file-name
"tramp" (filename var
&rest body
))
51 (declare-function org-icompleting-read
"org" (&rest args
))
52 (declare-function org-edit-src-code
"org-src" (&optional code edit-buffer-name
))
53 (declare-function org-edit-src-exit
"org-src" ())
54 (declare-function org-open-at-point
"org" (&optional in-emacs reference-buffer
))
55 (declare-function org-save-outline-visibility
"org-macs" (use-markers &rest body
))
56 (declare-function org-outline-overlay-data
"org" (&optional use-markers
))
57 (declare-function org-set-outline-overlay-data
"org" (data))
58 (declare-function org-narrow-to-subtree
"org" ())
59 (declare-function org-split-string
"org" (string &optional separators
))
60 (declare-function org-entry-get
"org"
61 (pom property
&optional inherit literal-nil
))
62 (declare-function org-make-options-regexp
"org" (kwds &optional extra
))
63 (declare-function org-do-remove-indentation
"org" (&optional n
))
64 (declare-function org-next-block
"org" (arg &optional backward block-regexp
))
65 (declare-function org-previous-block
"org" (arg &optional block-regexp
))
66 (declare-function org-show-context
"org" (&optional key
))
67 (declare-function org-at-table-p
"org" (&optional table-type
))
68 (declare-function org-cycle
"org" (&optional arg
))
69 (declare-function org-uniquify
"org" (list))
70 (declare-function org-current-level
"org" ())
71 (declare-function org-table-import
"org-table" (file arg
))
72 (declare-function org-add-hook
"org-compat"
73 (hook function
&optional append local
))
74 (declare-function org-table-align
"org-table" ())
75 (declare-function org-table-end
"org-table" (&optional table-type
))
76 (declare-function orgtbl-to-generic
"org-table" (table params
))
77 (declare-function orgtbl-to-orgtbl
"org-table" (table params
))
78 (declare-function org-babel-tangle-comment-links
"ob-tangle" (&optional info
))
79 (declare-function org-babel-lob-get-info
"ob-lob" nil
)
80 (declare-function org-babel-ref-split-args
"ob-ref" (arg-string))
81 (declare-function org-babel-ref-parse
"ob-ref" (assignment))
82 (declare-function org-babel-ref-resolve
"ob-ref" (ref))
83 (declare-function org-babel-ref-goto-headline-id
"ob-ref" (id))
84 (declare-function org-babel-ref-headline-body
"ob-ref" ())
85 (declare-function org-babel-lob-execute-maybe
"ob-lob" ())
86 (declare-function org-number-sequence
"org-compat" (from &optional to inc
))
87 (declare-function org-at-item-p
"org-list" ())
88 (declare-function org-list-parse-list
"org-list" (&optional delete
))
89 (declare-function org-list-to-generic
"org-list" (LIST PARAMS
))
90 (declare-function org-list-struct
"org-list" ())
91 (declare-function org-list-prevs-alist
"org-list" (struct))
92 (declare-function org-list-get-list-end
"org-list" (item struct prevs
))
93 (declare-function org-remove-if
"org" (predicate seq
))
94 (declare-function org-completing-read
"org" (&rest args
))
95 (declare-function org-escape-code-in-region
"org-src" (beg end
))
96 (declare-function org-unescape-code-in-string
"org-src" (s))
97 (declare-function org-table-to-lisp
"org-table" (&optional txt
))
98 (declare-function org-reverse-string
"org" (string))
99 (declare-function org-element-context
"org-element" (&optional ELEMENT
))
100 (declare-function org-every
"org" (pred seq
))
102 (defgroup org-babel nil
103 "Code block evaluation and management in `org-mode' documents."
107 (defcustom org-confirm-babel-evaluate t
108 "Confirm before evaluation.
109 Require confirmation before interactively evaluating code
110 blocks in Org-mode buffers. The default value of this variable
111 is t, meaning confirmation is required for any code block
112 evaluation. This variable can be set to nil to inhibit any
113 future confirmation requests. This variable can also be set to a
114 function which takes two arguments the language of the code block
115 and the body of the code block. Such a function should then
116 return a non-nil value if the user should be prompted for
117 execution or nil if no prompt is required.
119 Warning: Disabling confirmation may result in accidental
120 evaluation of potentially harmful code. It may be advisable
121 remove code block execution from C-c C-c as further protection
122 against accidental code block evaluation. The
123 `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
124 remove code block execution from the C-c C-c keybinding."
127 :type
'(choice boolean function
))
128 ;; don't allow this variable to be changed through file settings
129 (put 'org-confirm-babel-evaluate
'safe-local-variable
(lambda (x) (eq x t
)))
131 (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
132 "Remove code block evaluation from the C-c C-c key binding."
137 (defcustom org-babel-results-keyword
"RESULTS"
138 "Keyword used to name results generated by code blocks.
139 Should be either RESULTS or NAME however any capitalization may
143 :package-version
'(Org .
"8.0")
146 (defcustom org-babel-noweb-wrap-start
"<<"
147 "String used to begin a noweb reference in a code block.
148 See also `org-babel-noweb-wrap-end'."
152 (defcustom org-babel-noweb-wrap-end
">>"
153 "String used to end a noweb reference in a code block.
154 See also `org-babel-noweb-wrap-start'."
158 (defcustom org-babel-inline-result-wrap
"=%s="
159 "Format string used to wrap inline results.
160 This string must include a \"%s\" which will be replaced by the results."
163 (put 'org-babel-inline-result-wrap
167 (string-match-p "%s" value
))))
169 (defun org-babel-noweb-wrap (&optional regexp
)
170 (concat org-babel-noweb-wrap-start
171 (or regexp
"\\([^ \t\n].+?[^ \t]\\|[^ \t\n]\\)")
172 org-babel-noweb-wrap-end
))
174 (defvar org-babel-src-name-regexp
175 "^[ \t]*#\\+name:[ \t]*"
176 "Regular expression used to match a source name line.")
178 (defvar org-babel-multi-line-header-regexp
179 "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
180 "Regular expression used to match multi-line header arguments.")
182 (defvar org-babel-src-name-w-name-regexp
183 (concat org-babel-src-name-regexp
185 org-babel-multi-line-header-regexp
187 "\\([^ ()\f\t\n\r\v]+\\)")
188 "Regular expression matching source name lines with a name.")
190 (defvar org-babel-src-block-regexp
192 ;; (1) indentation (2) lang
193 "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
195 "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
196 ;; (4) header arguments
199 "\\([^\000]*?\n\\)??[ \t]*#\\+end_src")
200 "Regexp used to identify code blocks.")
202 (defvar org-babel-inline-src-block-regexp
204 ;; (1) replacement target (2) lang
205 "\\(?:^\\|[^-[:alnum:]]\\)\\(src_\\([^ \f\t\n\r\v[]+\\)"
206 ;; (3,4) (unused, headers)
207 "\\(\\|\\[[ \t]*\\(.*?\\)\\]\\)"
209 "{\\([^\f\n\r\v]+?\\)}\\)")
210 "Regexp used to identify inline src-blocks.")
212 (defun org-babel-get-header (params key
&optional others
)
213 "Select only header argument of type KEY from a list.
214 Optional argument OTHERS indicates that only the header that do
215 not match KEY should be returned."
218 (lambda (p) (when (funcall (if others
#'not
#'identity
) (eq (car p
) key
)) p
))
221 (defun org-babel-get-inline-src-block-matches ()
222 "Set match data if within body of an inline source block.
223 Returns non-nil if match-data set"
224 (let ((src-at-0-p (save-excursion
225 (beginning-of-line 1)
226 (string= "src" (thing-at-point 'word
))))
227 (first-line-p (= (line-beginning-position) (point-min)))
229 (let ((search-for (cond ((and src-at-0-p first-line-p
"src_"))
230 (first-line-p "[[:punct:] \t]src_")
231 (t "[[:punct:] \f\t\n\r\v]src_")))
232 (lower-limit (if first-line-p
234 (- (point-at-bol) 1))))
236 (when (or (and src-at-0-p
(bobp))
237 (and (re-search-forward "}" (point-at-eol) t
)
238 (re-search-backward search-for lower-limit t
)
240 (when (looking-at org-babel-inline-src-block-regexp
)
243 (defvar org-babel-inline-lob-one-liner-regexp
)
244 (defun org-babel-get-lob-one-liner-matches ()
245 "Set match data if on line of an lob one liner.
246 Returns non-nil if match-data set"
248 (unless (= (point) (point-at-bol)) ;; move before inline block
249 (re-search-backward "[ \f\t\n\r\v]" nil t
))
250 (if (looking-at org-babel-inline-lob-one-liner-regexp
)
254 (defun org-babel-get-src-block-info (&optional light
)
255 "Get information on the current source block.
257 Optional argument LIGHT does not resolve remote variable
258 references; a process which could likely result in the execution
259 of other code blocks.
262 (language body header-arguments-alist switches name indent block-head)."
263 (let ((case-fold-search t
) head info name indent
)
265 (if (setq head
(org-babel-where-is-src-block-head))
268 (setq info
(org-babel-parse-src-block-match))
269 (setq indent
(car (last info
)))
270 (setq info
(butlast info
))
271 (while (and (forward-line -
1)
272 (looking-at org-babel-multi-line-header-regexp
))
274 (org-babel-merge-params
276 (org-babel-parse-header-arguments (match-string 1)))))
277 (when (looking-at org-babel-src-name-w-name-regexp
)
278 (setq name
(org-no-properties (match-string 3)))))
279 ;; inline source block
280 (when (org-babel-get-inline-src-block-matches)
281 (setq head
(match-beginning 0))
282 (setq info
(org-babel-parse-inline-src-block-match))))
283 ;; resolve variable references and add summary parameters
284 (when (and info
(not light
))
285 (setf (nth 2 info
) (org-babel-process-params (nth 2 info
))))
287 (setf (nth 2 info
) (org-babel-generate-file-param name
(nth 2 info
))))
288 (when info
(append info
(list name indent head
)))))
290 (defvar org-babel-exp-reference-buffer nil
291 "Buffer containing original contents of the exported buffer.
292 This is used by Babel to resolve references in source blocks.
293 Its value is dynamically bound during export.")
295 (defmacro org-babel-check-confirm-evaluate
(info &rest body
)
296 "Evaluate BODY with special execution confirmation variables set.
298 Specifically; NOEVAL will indicate if evaluation is allowed,
299 QUERY will indicate if a user query is required, CODE-BLOCK will
300 hold the language of the code block, and BLOCK-NAME will hold the
301 name of the code block."
302 (declare (indent defun
))
304 (lang block-body headers name head eval eval-no export eval-no-export
)
305 `(let* ((,lang
(nth 0 ,info
))
306 (,block-body
(nth 1 ,info
))
307 (,headers
(nth 2 ,info
))
308 (,name
(nth 4 ,info
))
309 (,head
(nth 6 ,info
))
310 (,eval
(or (cdr (assoc :eval
,headers
))
311 (when (assoc :noeval
,headers
) "no")))
312 (,eval-no
(or (equal ,eval
"no")
313 (equal ,eval
"never")))
314 (,export org-babel-exp-reference-buffer
)
315 (,eval-no-export
(and ,export
(or (equal ,eval
"no-export")
316 (equal ,eval
"never-export"))))
317 (noeval (or ,eval-no
,eval-no-export
))
318 (query (or (equal ,eval
"query")
319 (and ,export
(equal ,eval
"query-export"))
320 (if (functionp org-confirm-babel-evaluate
)
323 (funcall org-confirm-babel-evaluate
325 org-confirm-babel-evaluate
)))
326 (code-block (if ,info
(format " %s " ,lang
) " "))
327 (block-name (if ,name
(format " (%s) " ,name
) " ")))
330 (defsubst org-babel-check-evaluate
(info)
331 "Check if code block INFO should be evaluated.
332 Do not query the user."
333 (org-babel-check-confirm-evaluate info
335 (message (format "Evaluation of this%scode-block%sis disabled."
336 code-block block-name
))))))
338 ;; dynamically scoped for asynchronous export
339 (defvar org-babel-confirm-evaluate-answer-no
)
341 (defsubst org-babel-confirm-evaluate
(info)
342 "Confirm evaluation of the code block INFO.
344 If the variable `org-babel-confirm-evaluate-answer-no' is bound
345 to a non-nil value, auto-answer with \"no\".
347 This query can also be suppressed by setting the value of
348 `org-confirm-babel-evaluate' to nil, in which case all future
349 interactive code block evaluations will proceed without any
350 confirmation from the user.
352 Note disabling confirmation may result in accidental evaluation
353 of potentially harmful code."
354 (org-babel-check-confirm-evaluate info
357 (and (not (org-bound-and-true-p
358 org-babel-confirm-evaluate-answer-no
))
360 (format "Evaluate this%scode block%son your system? "
361 code-block block-name
)))
362 (message (format "Evaluation of this%scode-block%sis aborted."
363 code-block block-name
)))))))
366 (defun org-babel-execute-safely-maybe ()
367 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
368 (org-babel-execute-maybe)))
370 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-execute-safely-maybe
)
373 (defun org-babel-execute-maybe ()
375 (or (org-babel-execute-src-block-maybe)
376 (org-babel-lob-execute-maybe)))
378 (defmacro org-babel-when-in-src-block
(&rest body
)
379 "Execute BODY if point is in a source block and return t.
381 Otherwise do nothing and return nil."
382 `(if (or (org-babel-where-is-src-block-head)
383 (org-babel-get-inline-src-block-matches))
389 (defun org-babel-execute-src-block-maybe ()
390 "Conditionally execute a source block.
391 Detect if this is context for a Babel src-block and if so
392 then run `org-babel-execute-src-block'."
394 (org-babel-when-in-src-block
395 (org-babel-eval-wipe-error-buffer)
396 (org-babel-execute-src-block current-prefix-arg
)))
399 (defun org-babel-view-src-block-info ()
400 "Display information on the current source block.
401 This includes header arguments, language and name, and is largely
402 a window into the `org-babel-get-src-block-info' function."
404 (let ((info (org-babel-get-src-block-info 'light
))
405 (full (lambda (it) (> (length it
) 0)))
406 (printf (lambda (fmt &rest args
) (princ (apply #'format fmt args
)))))
408 (with-help-window (help-buffer)
409 (let ((name (nth 4 info
))
411 (switches (nth 3 info
))
412 (header-args (nth 2 info
)))
413 (when name
(funcall printf
"Name: %s\n" name
))
414 (when lang
(funcall printf
"Lang: %s\n" lang
))
415 (when (funcall full switches
) (funcall printf
"Switches: %s\n" switches
))
416 (funcall printf
"Header Arguments:\n")
417 (dolist (pair (sort header-args
418 (lambda (a b
) (string< (symbol-name (car a
))
419 (symbol-name (car b
))))))
420 (when (funcall full
(cdr pair
))
421 (funcall printf
"\t%S%s\t%s\n"
423 (if (> (length (format "%S" (car pair
))) 7) "" "\t")
427 (defun org-babel-expand-src-block-maybe ()
428 "Conditionally expand a source block.
429 Detect if this is context for a org-babel src-block and if so
430 then run `org-babel-expand-src-block'."
432 (org-babel-when-in-src-block
433 (org-babel-expand-src-block current-prefix-arg
)))
436 (defun org-babel-load-in-session-maybe ()
437 "Conditionally load a source block in a session.
438 Detect if this is context for a org-babel src-block and if so
439 then run `org-babel-load-in-session'."
441 (org-babel-when-in-src-block
442 (org-babel-load-in-session current-prefix-arg
)))
444 (add-hook 'org-metaup-hook
'org-babel-load-in-session-maybe
)
447 (defun org-babel-pop-to-session-maybe ()
448 "Conditionally pop to a session.
449 Detect if this is context for a org-babel src-block and if so
450 then run `org-babel-switch-to-session'."
452 (org-babel-when-in-src-block
453 (org-babel-switch-to-session current-prefix-arg
)))
455 (add-hook 'org-metadown-hook
'org-babel-pop-to-session-maybe
)
457 (defconst org-babel-common-header-args-w-values
458 '((cache .
((no yes
)))
460 (colnames .
((nil no yes
)))
461 (comments .
((no link yes org both noweb
)))
463 (eval .
((never query
)))
464 (exports .
((code results both none
)))
468 (hlines .
((no yes
)))
469 (mkdirp .
((yes no
)))
472 (noweb .
((yes no tangle no-export strip-export
)))
476 (padline .
((yes no
)))
479 (results .
((file list vector table scalar verbatim
)
480 (raw html latex org code pp drawer
)
481 (replace silent none append prepend
)
483 (rownames .
((no yes
)))
487 (tangle .
((tangle yes no
:any
)))
488 (tangle-mode .
((#o755
#o555
#o444
:any
)))
492 (defconst org-babel-header-arg-names
493 (mapcar #'car org-babel-common-header-args-w-values
)
494 "Common header arguments used by org-babel.
495 Note that individual languages may define their own language
496 specific header arguments as well.")
498 (defconst org-babel-safe-header-args
499 '(:cache
:colnames
:comments
:exports
:epilogue
:hlines
:noeval
500 :noweb
:noweb-ref
:noweb-sep
:padline
:prologue
:rownames
501 :sep
:session
:tangle
:wrap
502 (:eval .
("never" "query"))
503 (:results .
(lambda (str) (not (string-match "file" str
)))))
504 "A list of safe header arguments for babel source blocks.
506 The list can have entries of the following forms:
507 - :ARG -> :ARG is always a safe header arg
508 - (:ARG . (VAL1 VAL2 ...)) -> :ARG is safe as a header arg if it is
509 `equal' to one of the VALs.
510 - (:ARG . FN) -> :ARG is safe as a header arg if the function FN
511 returns non-nil. FN is passed one
512 argument, the value of the header arg
515 (defmacro org-babel-header-args-safe-fn
(safe-list)
516 "Return a function that determines whether a list of header args are safe.
519 \(put 'org-babel-default-header-args 'safe-local-variable
520 (org-babel-header-args-safe-p org-babel-safe-header-args)
522 This allows org-babel languages to extend the list of safe values for
523 their `org-babel-default-header-args:foo' variable.
525 For the format of SAFE-LIST, see `org-babel-safe-header-args'."
531 (org-babel-one-header-arg-safe-p pair
,safe-list
)))
534 (defvar org-babel-default-header-args
535 '((:session .
"none") (:results .
"replace") (:exports .
"code")
536 (:cache .
"no") (:noweb .
"no") (:hlines .
"no") (:tangle .
"no"))
537 "Default arguments to use when evaluating a source block.")
538 (put 'org-babel-default-header-args
'safe-local-variable
539 (org-babel-header-args-safe-fn org-babel-safe-header-args
))
541 (defvar org-babel-default-inline-header-args
542 '((:session .
"none") (:results .
"replace")
543 (:exports .
"results") (:hlines .
"yes"))
544 "Default arguments to use when evaluating an inline source block.")
545 (put 'org-babel-default-inline-header-args
'safe-local-variable
546 (org-babel-header-args-safe-fn org-babel-safe-header-args
))
548 (defvar org-babel-data-names
'("tblname" "results" "name"))
550 (defvar org-babel-result-regexp
551 (concat "^[ \t]*#\\+"
552 (regexp-opt org-babel-data-names t
)
554 ;; FIXME The string below is `org-ts-regexp'
555 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
556 " \\)?\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*")
557 "Regular expression used to match result lines.
558 If the results are associated with a hash key then the hash will
559 be saved in the second match data.")
561 (defvar org-babel-result-w-name-regexp
562 (concat org-babel-result-regexp
563 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
565 (defvar org-babel-min-lines-for-block-output
10
566 "The minimum number of lines for block output.
567 If number of lines of output is equal to or exceeds this
568 value, the output is placed in a #+begin_example...#+end_example
569 block. Otherwise the output is marked as literal by inserting
570 colons at the starts of the lines. This variable only takes
571 effect if the :results output option is in effect.")
573 (defvar org-babel-noweb-error-all-langs nil
574 "Raise errors when noweb references don't resolve.
575 Also see `org-babel-noweb-error-langs' to control noweb errors on
576 a language by language bases.")
578 (defvar org-babel-noweb-error-langs nil
579 "Languages for which Babel will raise literate programming errors.
580 List of languages for which errors should be raised when the
581 source code block satisfying a noweb reference in this language
582 can not be resolved. Also see `org-babel-noweb-error-all-langs'
583 to raise errors for all languages.")
585 (defvar org-babel-hash-show
4
586 "Number of initial characters to show of a hidden results hash.")
588 (defvar org-babel-hash-show-time nil
589 "Non-nil means show the time the code block was evaluated in the result hash.")
591 (defvar org-babel-after-execute-hook nil
592 "Hook for functions to be called after `org-babel-execute-src-block'")
594 (defun org-babel-named-src-block-regexp-for-name (name)
595 "This generates a regexp used to match a src block named NAME."
596 (concat org-babel-src-name-regexp
(regexp-quote name
)
597 "[ \t(]*[\r\n]\\(?:^[[:space:]]*#.*[\r\n]\\)*"
598 (substring org-babel-src-block-regexp
1)))
600 (defun org-babel-named-data-regexp-for-name (name)
601 "This generates a regexp used to match data named NAME."
602 (concat org-babel-result-regexp
(regexp-quote name
) "\\([ \t]\\|$\\)"))
605 (defvar call-process-region
)
606 (defvar org-babel-current-src-block-location nil
607 "Marker pointing to the src block currently being executed.
608 This may also point to a call line or an inline code block. If
609 multiple blocks are being executed (e.g., in chained execution
610 through use of the :var header argument) this marker points to
611 the outer-most code block.")
614 (defun org-babel-execute-src-block (&optional arg info params
)
615 "Execute the current source code block.
616 Insert the results of execution into the buffer. Source code
617 execution and the collection and formatting of results can be
618 controlled through a variety of header arguments.
620 With prefix argument ARG, force re-execution even if an existing
621 result cached in the buffer would otherwise have been returned.
623 Optionally supply a value for INFO in the form returned by
624 `org-babel-get-src-block-info'.
626 Optionally supply a value for PARAMS which will be merged with
627 the header arguments specified at the front of the source code
630 (let* ((org-babel-current-src-block-location
631 (or org-babel-current-src-block-location
633 (org-babel-where-is-src-block-head)
635 (and (org-babel-get-inline-src-block-matches)
636 (match-beginning 0))))
639 (org-babel-get-src-block-info)))
640 (merged-params (org-babel-merge-params (nth 2 info
) params
)))
641 (when (org-babel-check-evaluate
642 (let ((i info
)) (setf (nth 2 i
) merged-params
) i
))
643 (let* ((params (if params
644 (org-babel-process-params merged-params
)
646 (cachep (and (not arg
) (cdr (assoc :cache params
))
647 (string= "yes" (cdr (assoc :cache params
)))))
648 (new-hash (when cachep
(org-babel-sha1-hash info
)))
649 (old-hash (when cachep
(org-babel-current-result-hash)))
650 (cache-current-p (and (not arg
) new-hash
651 (equal new-hash old-hash
))))
654 (save-excursion ;; return cached result
655 (goto-char (org-babel-where-is-src-block-result nil info
))
656 (end-of-line 1) (forward-char 1)
657 (let ((result (org-babel-read-result)))
658 (message (replace-regexp-in-string
659 "%" "%%" (format "%S" result
))) result
)))
660 ((org-babel-confirm-evaluate
661 (let ((i info
)) (setf (nth 2 i
) merged-params
) i
))
662 (let* ((lang (nth 0 info
))
663 (result-params (cdr (assoc :result-params params
)))
664 (body (setf (nth 1 info
)
665 (if (org-babel-noweb-p params
:eval
)
666 (org-babel-expand-noweb-references info
)
668 (dir (cdr (assoc :dir params
)))
670 (or (and dir
(file-name-as-directory (expand-file-name dir
)))
672 (org-babel-call-process-region-original ;; for tramp handler
673 (or (org-bound-and-true-p
674 org-babel-call-process-region-original
)
675 (symbol-function 'call-process-region
)))
676 (indent (nth 5 info
))
679 (let ((call-process-region
681 (apply 'org-babel-tramp-handle-call-process-region
685 (let ((f (intern (concat "org-babel-execute:" f
))))
686 (when (fboundp f
) f
)))))
688 (or (funcall lang-check lang
)
691 (cdr (assoc lang org-src-lang-modes
))))
692 (error "No org-babel-execute function for %s!"
694 (message "executing %s code block%s..."
696 (if (nth 4 info
) (format " (%s)" (nth 4 info
)) ""))
697 (if (member "none" result-params
)
699 (funcall cmd body params
)
700 (message "result silenced")
703 (let ((result (funcall cmd body params
)))
704 (if (and (eq (cdr (assoc :result-type params
))
706 (or (member "vector" result-params
)
707 (member "table" result-params
))
708 (not (listp result
)))
709 (list (list result
)) result
)))
710 ;; If non-empty result and :file then write to :file.
711 (when (cdr (assoc :file params
))
713 (with-temp-file (cdr (assoc :file params
))
715 (org-babel-format-result
716 result
(cdr (assoc :sep
(nth 2 info
)))))))
717 (setq result
(cdr (assoc :file params
))))
718 ;; Possibly perform post process provided its appropriate.
719 (when (cdr (assoc :post params
))
720 (let ((*this
* (if (cdr (assoc :file params
))
721 (org-babel-result-to-file
722 (cdr (assoc :file params
))
723 (when (assoc :file-desc params
)
724 (or (cdr (assoc :file-desc params
))
727 (setq result
(org-babel-ref-resolve
728 (cdr (assoc :post params
))))
729 (when (cdr (assoc :file params
))
731 (remove "file" result-params
)))))
732 (org-babel-insert-result
733 result result-params info new-hash indent lang
))
734 (run-hooks 'org-babel-after-execute-hook
)
736 (setq call-process-region
737 'org-babel-call-process-region-original
)))))))))
739 (defun org-babel-expand-body:generic
(body params
&optional var-lines
)
740 "Expand BODY with PARAMS.
741 Expand a block of code with org-babel according to its header
742 arguments. This generic implementation of body expansion is
743 called for languages which have not defined their own specific
744 org-babel-expand-body:lang function."
745 (let ((pro (cdr (assoc :prologue params
)))
746 (epi (cdr (assoc :epilogue params
))))
747 (mapconcat #'identity
748 (append (when pro
(list pro
))
751 (when epi
(list epi
)))
755 (defun org-babel-expand-src-block (&optional arg info params
)
756 "Expand the current source code block.
757 Expand according to the source code block's header
758 arguments and pop open the results in a preview buffer."
760 (let* ((info (or info
(org-babel-get-src-block-info)))
762 (params (setf (nth 2 info
)
763 (sort (org-babel-merge-params (nth 2 info
) params
)
764 (lambda (el1 el2
) (string< (symbol-name (car el1
))
765 (symbol-name (car el2
)))))))
766 (body (setf (nth 1 info
)
767 (if (org-babel-noweb-p params
:eval
)
768 (org-babel-expand-noweb-references info
) (nth 1 info
))))
769 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
770 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
773 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
774 (org-babel-expand-body:generic
775 body params
(and (fboundp assignments-cmd
)
776 (funcall assignments-cmd params
))))))
777 (if (org-called-interactively-p 'any
)
779 expanded
(concat "*Org-Babel Preview " (buffer-name) "[ " lang
" ]*"))
782 (defun org-babel-edit-distance (s1 s2
)
783 "Return the edit (levenshtein) distance between strings S1 S2."
784 (let* ((l1 (length s1
))
786 (dist (vconcat (mapcar (lambda (_) (make-vector (1+ l2
) nil
))
787 (number-sequence 1 (1+ l1
)))))
788 (in (lambda (i j
) (aref (aref dist i
) j
))))
789 (setf (aref (aref dist
0) 0) 0)
790 (dolist (j (number-sequence 1 l2
))
791 (setf (aref (aref dist
0) j
) j
))
792 (dolist (i (number-sequence 1 l1
))
793 (setf (aref (aref dist i
) 0) i
)
794 (dolist (j (number-sequence 1 l2
))
795 (setf (aref (aref dist i
) j
)
797 (1+ (funcall in
(1- i
) j
))
798 (1+ (funcall in i
(1- j
)))
799 (+ (if (equal (aref s1
(1- i
)) (aref s2
(1- j
))) 0 1)
800 (funcall in
(1- i
) (1- j
)))))))
803 (defun org-babel-combine-header-arg-lists (original &rest others
)
804 "Combine a number of lists of header argument names and arguments."
805 (let ((results (copy-sequence original
)))
806 (dolist (new-list others
)
807 (dolist (arg-pair new-list
)
808 (let ((header (car arg-pair
))
809 (args (cdr arg-pair
)))
811 (cons arg-pair
(org-remove-if
812 (lambda (pair) (equal header
(car pair
)))
817 (defun org-babel-check-src-block ()
818 "Check for misspelled header arguments in the current code block."
820 ;; TODO: report malformed code block
821 ;; TODO: report incompatible combinations of header arguments
822 ;; TODO: report uninitialized variables
823 (let ((too-close 2) ;; <- control closeness to report potential match
824 (names (mapcar #'symbol-name org-babel-header-arg-names
)))
825 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg
)) 1))
826 (and (org-babel-where-is-src-block-head)
827 (org-babel-parse-header-arguments
829 (match-string 4))))))
831 (when (and (not (string= header name
))
832 (<= (org-babel-edit-distance header name
) too-close
)
833 (not (member header names
)))
834 (error "Supplied header \"%S\" is suspiciously close to \"%S\""
836 (message "No suspicious header arguments found.")))
839 (defun org-babel-insert-header-arg (&optional header-arg value
)
840 "Insert a header argument selecting from lists of common args and values."
842 (let* ((info (org-babel-get-src-block-info 'light
))
845 (lang-headers (intern (concat "org-babel-header-args:" lang
)))
846 (headers (org-babel-combine-header-arg-lists
847 org-babel-common-header-args-w-values
848 (when (boundp lang-headers
) (eval lang-headers
))))
849 (header-arg (or header-arg
850 (org-icompleting-read
853 (lambda (header-spec) (symbol-name (car header-spec
)))
855 (vals (cdr (assoc (intern header-arg
) headers
)))
859 (read-from-minibuffer "value: "))
863 (let ((arg (org-icompleting-read
866 (mapcar #'symbol-name group
)))))
867 (if (and arg
(not (string= "default" arg
)))
873 (goto-char (point-at-eol))
874 (unless (= (char-before (point)) ?\
) (insert " "))
875 (insert ":" header-arg
) (when value
(insert " " value
)))))
877 ;; Add support for completing-read insertion of header arguments after ":"
878 (defun org-babel-header-arg-expand ()
879 "Call `org-babel-enter-header-arg-w-completion' in appropriate contexts."
880 (when (and (equal (char-before) ?\
:) (org-babel-where-is-src-block-head))
881 (org-babel-enter-header-arg-w-completion (match-string 2))))
883 (defun org-babel-enter-header-arg-w-completion (&optional lang
)
884 "Insert header argument appropriate for LANG with completion."
885 (let* ((lang-headers-var (intern (concat "org-babel-header-args:" lang
)))
886 (lang-headers (when (boundp lang-headers-var
) (eval lang-headers-var
)))
887 (headers-w-values (org-babel-combine-header-arg-lists
888 org-babel-common-header-args-w-values lang-headers
))
889 (headers (mapcar #'symbol-name
(mapcar #'car headers-w-values
)))
890 (header (org-completing-read "Header Arg: " headers
))
891 (args (cdr (assoc (intern header
) headers-w-values
)))
892 (arg (when (and args
(listp args
))
894 (format "%s: " header
)
895 (mapcar #'symbol-name
(apply #'append args
))))))
896 (insert (concat header
" " (or arg
"")))
899 (add-hook 'org-tab-first-hook
'org-babel-header-arg-expand
)
902 (defun org-babel-load-in-session (&optional arg info
)
903 "Load the body of the current source-code block.
904 Evaluate the header arguments for the source block before
905 entering the session. After loading the body this pops open the
908 (let* ((info (or info
(org-babel-get-src-block-info)))
910 (params (nth 2 info
))
912 (user-error "No src code block at point")
914 (if (org-babel-noweb-p params
:eval
)
915 (org-babel-expand-noweb-references info
)
917 (session (cdr (assoc :session params
)))
918 (dir (cdr (assoc :dir params
)))
920 (or (and dir
(file-name-as-directory dir
)) default-directory
))
921 (cmd (intern (concat "org-babel-load-session:" lang
))))
922 (unless (fboundp cmd
)
923 (error "No org-babel-load-session function for %s!" lang
))
924 (pop-to-buffer (funcall cmd session body params
))
928 (defun org-babel-initiate-session (&optional arg info
)
929 "Initiate session for current code block.
930 If called with a prefix argument then resolve any variable
931 references in the header arguments and assign these variables in
932 the session. Copy the body of the code block to the kill ring."
934 (let* ((info (or info
(org-babel-get-src-block-info (not arg
))))
937 (params (nth 2 info
))
938 (session (cdr (assoc :session params
)))
939 (dir (cdr (assoc :dir params
)))
941 (or (and dir
(file-name-as-directory dir
)) default-directory
))
942 (init-cmd (intern (format "org-babel-%s-initiate-session" lang
)))
943 (prep-cmd (intern (concat "org-babel-prep-session:" lang
))))
944 (if (and (stringp session
) (string= session
"none"))
945 (error "This block is not using a session!"))
946 (unless (fboundp init-cmd
)
947 (error "No org-babel-initiate-session function for %s!" lang
))
948 (with-temp-buffer (insert (org-babel-trim body
))
949 (copy-region-as-kill (point-min) (point-max)))
951 (unless (fboundp prep-cmd
)
952 (error "No org-babel-prep-session function for %s!" lang
))
953 (funcall prep-cmd session params
))
954 (funcall init-cmd session params
)))
957 (defun org-babel-switch-to-session (&optional arg info
)
958 "Switch to the session of the current code block.
959 Uses `org-babel-initiate-session' to start the session. If called
960 with a prefix argument then this is passed on to
961 `org-babel-initiate-session'."
963 (pop-to-buffer (org-babel-initiate-session arg info
))
966 (defalias 'org-babel-pop-to-session
'org-babel-switch-to-session
)
968 (defvar org-src-window-setup
)
971 (defun org-babel-switch-to-session-with-code (&optional arg info
)
972 "Switch to code buffer and display session."
976 (let ((other-window-buffer (window-buffer (next-window))))
977 (set-window-buffer (next-window) (current-buffer))
978 (set-window-buffer (selected-window) other-window-buffer
))
980 (info (org-babel-get-src-block-info))
981 (org-src-window-setup 'reorganize-frame
))
983 (org-babel-switch-to-session arg info
))
985 (funcall swap-windows
)))
988 (defmacro org-babel-do-in-edit-buffer
(&rest body
)
989 "Evaluate BODY in edit buffer if there is a code block at point.
990 Return t if a code block was found at point, nil otherwise."
991 `(let ((org-src-window-setup 'switch-invisibly
))
992 (when (and (org-babel-where-is-src-block-head)
994 (unwind-protect (progn ,@body
)
997 (def-edebug-spec org-babel-do-in-edit-buffer
(body))
999 (defun org-babel-do-key-sequence-in-edit-buffer (key)
1000 "Read key sequence and execute the command in edit buffer.
1001 Enter a key sequence to be executed in the language major-mode
1002 edit buffer. For example, TAB will alter the contents of the
1003 Org-mode code block according to the effect of TAB in the
1004 language major-mode buffer. For languages that support
1005 interactive sessions, this can be used to send code from the Org
1006 buffer to the session for evaluation using the native major-mode
1007 evaluation mechanisms."
1008 (interactive "kEnter key-sequence to execute in edit buffer: ")
1009 (org-babel-do-in-edit-buffer
1011 (key-binding (or key
(read-key-sequence nil
))))))
1013 (defvar org-bracket-link-regexp
)
1015 (defun org-babel-active-location-p ()
1016 (memq (car (save-match-data (org-element-context)))
1017 '(babel-call inline-babel-call inline-src-block src-block
)))
1020 (defun org-babel-open-src-block-result (&optional re-run
)
1021 "If `point' is on a src block then open the results of the
1022 source code block, otherwise return nil. With optional prefix
1023 argument RE-RUN the source-code block is evaluated even if
1024 results already exist."
1026 (let ((info (org-babel-get-src-block-info 'light
)))
1029 ;; go to the results, if there aren't any then run the block
1030 (goto-char (or (and (not re-run
) (org-babel-where-is-src-block-result))
1031 (progn (org-babel-execute-src-block)
1032 (org-babel-where-is-src-block-result))))
1034 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
1036 (if (looking-at org-bracket-link-regexp
)
1039 (let ((r (org-babel-format-result
1040 (org-babel-read-result) (cdr (assoc :sep
(nth 2 info
))))))
1041 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
1042 (delete-region (point-min) (point-max))
1047 (defmacro org-babel-map-src-blocks
(file &rest body
)
1048 "Evaluate BODY forms on each source-block in FILE.
1049 If FILE is nil evaluate BODY forms on source blocks in current
1050 buffer. During evaluation of BODY the following local variables
1051 are set relative to the currently matched code block.
1053 full-block ------- string holding the entirety of the code block
1054 beg-block -------- point at the beginning of the code block
1055 end-block -------- point at the end of the matched code block
1056 lang ------------- string holding the language of the code block
1057 beg-lang --------- point at the beginning of the lang
1058 end-lang --------- point at the end of the lang
1059 switches --------- string holding the switches
1060 beg-switches ----- point at the beginning of the switches
1061 end-switches ----- point at the end of the switches
1062 header-args ------ string holding the header-args
1063 beg-header-args -- point at the beginning of the header-args
1064 end-header-args -- point at the end of the header-args
1065 body ------------- string holding the body of the code block
1066 beg-body --------- point at the beginning of the body
1067 end-body --------- point at the end of the body"
1068 (declare (indent 1))
1069 (let ((tempvar (make-symbol "file")))
1070 `(let* ((,tempvar
,file
)
1071 (visited-p (or (null ,tempvar
)
1072 (get-file-buffer (expand-file-name ,tempvar
))))
1073 (point (point)) to-be-removed
)
1074 (save-window-excursion
1075 (when ,tempvar
(find-file ,tempvar
))
1076 (setq to-be-removed
(current-buffer))
1077 (goto-char (point-min))
1078 (while (re-search-forward org-babel-src-block-regexp nil t
)
1079 (when (org-babel-active-location-p)
1080 (goto-char (match-beginning 0))
1081 (let ((full-block (match-string 0))
1082 (beg-block (match-beginning 0))
1083 (end-block (match-end 0))
1084 (lang (match-string 2))
1085 (beg-lang (match-beginning 2))
1086 (end-lang (match-end 2))
1087 (switches (match-string 3))
1088 (beg-switches (match-beginning 3))
1089 (end-switches (match-end 3))
1090 (header-args (match-string 4))
1091 (beg-header-args (match-beginning 4))
1092 (end-header-args (match-end 4))
1093 (body (match-string 5))
1094 (beg-body (match-beginning 5))
1095 (end-body (match-end 5)))
1097 (goto-char end-block
)))))
1098 (unless visited-p
(kill-buffer to-be-removed
))
1099 (goto-char point
))))
1100 (def-edebug-spec org-babel-map-src-blocks
(form body
))
1103 (defmacro org-babel-map-inline-src-blocks
(file &rest body
)
1104 "Evaluate BODY forms on each inline source-block in FILE.
1105 If FILE is nil evaluate BODY forms on source blocks in current
1107 (declare (indent 1))
1108 (let ((tempvar (make-symbol "file")))
1109 `(let* ((,tempvar
,file
)
1110 (visited-p (or (null ,tempvar
)
1111 (get-file-buffer (expand-file-name ,tempvar
))))
1112 (point (point)) to-be-removed
)
1113 (save-window-excursion
1114 (when ,tempvar
(find-file ,tempvar
))
1115 (setq to-be-removed
(current-buffer))
1116 (goto-char (point-min))
1117 (while (re-search-forward org-babel-inline-src-block-regexp nil t
)
1118 (when (org-babel-active-location-p)
1119 (goto-char (match-beginning 1))
1120 (save-match-data ,@body
))
1121 (goto-char (match-end 0))))
1122 (unless visited-p
(kill-buffer to-be-removed
))
1123 (goto-char point
))))
1124 (def-edebug-spec org-babel-map-inline-src-blocks
(form body
))
1126 (defvar org-babel-lob-one-liner-regexp
)
1129 (defmacro org-babel-map-call-lines
(file &rest body
)
1130 "Evaluate BODY forms on each call line in FILE.
1131 If FILE is nil evaluate BODY forms on source blocks in current
1133 (declare (indent 1))
1134 (let ((tempvar (make-symbol "file")))
1135 `(let* ((,tempvar
,file
)
1136 (visited-p (or (null ,tempvar
)
1137 (get-file-buffer (expand-file-name ,tempvar
))))
1138 (point (point)) to-be-removed
)
1139 (save-window-excursion
1140 (when ,tempvar
(find-file ,tempvar
))
1141 (setq to-be-removed
(current-buffer))
1142 (goto-char (point-min))
1143 (while (re-search-forward org-babel-lob-one-liner-regexp nil t
)
1144 (when (org-babel-active-location-p)
1145 (goto-char (match-beginning 1))
1146 (save-match-data ,@body
))
1147 (goto-char (match-end 0))))
1148 (unless visited-p
(kill-buffer to-be-removed
))
1149 (goto-char point
))))
1150 (def-edebug-spec org-babel-map-call-lines
(form body
))
1153 (defmacro org-babel-map-executables
(file &rest body
)
1154 (declare (indent 1))
1155 (let ((tempvar (make-symbol "file"))
1156 (rx (make-symbol "rx")))
1157 `(let* ((,tempvar
,file
)
1158 (,rx
(concat "\\(" org-babel-src-block-regexp
1159 "\\|" org-babel-inline-src-block-regexp
1160 "\\|" org-babel-lob-one-liner-regexp
"\\)"))
1161 (visited-p (or (null ,tempvar
)
1162 (get-file-buffer (expand-file-name ,tempvar
))))
1163 (point (point)) to-be-removed
)
1164 (save-window-excursion
1165 (when ,tempvar
(find-file ,tempvar
))
1166 (setq to-be-removed
(current-buffer))
1167 (goto-char (point-min))
1168 (while (re-search-forward ,rx nil t
)
1169 (when (org-babel-active-location-p)
1170 (goto-char (match-beginning 1))
1171 (when (looking-at org-babel-inline-src-block-regexp
)
1173 (save-match-data ,@body
))
1174 (goto-char (match-end 0))))
1175 (unless visited-p
(kill-buffer to-be-removed
))
1176 (goto-char point
))))
1177 (def-edebug-spec org-babel-map-executables
(form body
))
1180 (defun org-babel-execute-buffer (&optional arg
)
1181 "Execute source code blocks in a buffer.
1182 Call `org-babel-execute-src-block' on every source block in
1183 the current buffer."
1185 (org-babel-eval-wipe-error-buffer)
1186 (org-save-outline-visibility t
1187 (org-babel-map-executables nil
1188 (if (looking-at org-babel-lob-one-liner-regexp
)
1189 (org-babel-lob-execute-maybe)
1190 (org-babel-execute-src-block arg
)))))
1193 (defun org-babel-execute-subtree (&optional arg
)
1194 "Execute source code blocks in a subtree.
1195 Call `org-babel-execute-src-block' on every source block in
1196 the current subtree."
1200 (org-narrow-to-subtree)
1201 (org-babel-execute-buffer arg
)
1205 (defun org-babel-sha1-hash (&optional info
)
1206 "Generate an sha1 hash based on the value of info."
1208 (let ((print-level nil
)
1209 (info (or info
(org-babel-get-src-block-info))))
1211 (sort (copy-sequence (nth 2 info
))
1212 (lambda (a b
) (string< (car a
) (car b
)))))
1213 (let* ((rm (lambda (lst)
1214 (dolist (p '("replace" "silent" "none"
1215 "append" "prepend"))
1216 (setq lst
(remove p lst
)))
1219 (let ((v (if (and (listp (cdr arg
)) (null (cddr arg
)))
1220 (copy-sequence (cdr arg
))
1222 (when (and v
(not (and (sequencep v
)
1226 ((and (listp v
) ; lists are sorted
1227 (member (car arg
) '(:result-params
)))
1228 (sort (funcall rm v
) #'string
<))
1229 ((and (stringp v
) ; strings are sorted
1230 (member (car arg
) '(:results
:exports
)))
1231 (mapconcat #'identity
(sort (funcall rm
(split-string v
))
1236 (params (nth 2 info
))
1237 (body (if (org-babel-noweb-p params
:eval
)
1238 (org-babel-expand-noweb-references info
) (nth 1 info
)))
1239 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
1240 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
1243 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
1244 (org-babel-expand-body:generic
1245 body params
(and (fboundp assignments-cmd
)
1246 (funcall assignments-cmd params
))))))
1247 (let* ((it (format "%s-%s"
1250 (delq nil
(mapcar (lambda (arg)
1251 (let ((normalized (funcall norm arg
)))
1253 (format "%S" normalized
))))
1257 (when (org-called-interactively-p 'interactive
) (message hash
))
1260 (defun org-babel-current-result-hash (&optional info
)
1261 "Return the current in-buffer hash."
1262 (org-babel-where-is-src-block-result nil info
)
1263 (org-no-properties (match-string 5)))
1265 (defun org-babel-set-current-result-hash (hash info
)
1266 "Set the current in-buffer hash to HASH."
1267 (org-babel-where-is-src-block-result nil info
)
1268 (save-excursion (goto-char (match-beginning 5))
1269 (mapc #'delete-overlay
(overlays-at (point)))
1270 (forward-char org-babel-hash-show
)
1271 (mapc #'delete-overlay
(overlays-at (point)))
1272 (replace-match hash nil nil nil
5)
1273 (goto-char (point-at-bol))
1274 (org-babel-hide-hash)))
1276 (defun org-babel-hide-hash ()
1277 "Hide the hash in the current results line.
1278 Only the initial `org-babel-hash-show' characters of the hash
1279 will remain visible."
1280 (add-to-invisibility-spec '(org-babel-hide-hash . t
))
1282 (when (and (re-search-forward org-babel-result-regexp nil t
)
1284 (let* ((start (match-beginning 5))
1285 (hide-start (+ org-babel-hash-show start
))
1287 (hash (match-string 5))
1289 (setq ov1
(make-overlay start hide-start
))
1290 (setq ov2
(make-overlay hide-start end
))
1291 (overlay-put ov2
'invisible
'org-babel-hide-hash
)
1292 (overlay-put ov1
'babel-hash hash
)))))
1294 (defun org-babel-hide-all-hashes ()
1295 "Hide the hash in the current buffer.
1296 Only the initial `org-babel-hash-show' characters of each hash
1297 will remain visible. This function should be called as part of
1298 the `org-mode-hook'."
1300 (while (and (not org-babel-hash-show-time
)
1301 (re-search-forward org-babel-result-regexp nil t
))
1302 (goto-char (match-beginning 0))
1303 (org-babel-hide-hash)
1304 (goto-char (match-end 0)))))
1305 (add-hook 'org-mode-hook
'org-babel-hide-all-hashes
)
1307 (defun org-babel-hash-at-point (&optional point
)
1308 "Return the value of the hash at POINT.
1309 The hash is also added as the last element of the kill ring.
1310 This can be called with C-c C-c."
1312 (let ((hash (car (delq nil
(mapcar
1313 (lambda (ol) (overlay-get ol
'babel-hash
))
1314 (overlays-at (or point
(point))))))))
1315 (when hash
(kill-new hash
) (message hash
))))
1316 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-hash-at-point
)
1318 (defun org-babel-result-hide-spec ()
1319 "Hide portions of results lines.
1320 Add `org-babel-hide-result' as an invisibility spec for hiding
1321 portions of results lines."
1322 (add-to-invisibility-spec '(org-babel-hide-result . t
)))
1323 (add-hook 'org-mode-hook
'org-babel-result-hide-spec
)
1325 (defvar org-babel-hide-result-overlays nil
1326 "Overlays hiding results.")
1328 (defun org-babel-result-hide-all ()
1329 "Fold all results in the current buffer."
1331 (org-babel-show-result-all)
1333 (while (re-search-forward org-babel-result-regexp nil t
)
1334 (save-excursion (goto-char (match-beginning 0))
1335 (org-babel-hide-result-toggle-maybe)))))
1337 (defun org-babel-show-result-all ()
1338 "Unfold all results in the current buffer."
1339 (mapc 'delete-overlay org-babel-hide-result-overlays
)
1340 (setq org-babel-hide-result-overlays nil
))
1343 (defun org-babel-hide-result-toggle-maybe ()
1344 "Toggle visibility of result at point."
1346 (let ((case-fold-search t
))
1348 (beginning-of-line 1)
1349 (looking-at org-babel-result-regexp
))
1350 (progn (org-babel-hide-result-toggle)
1351 t
) ;; to signal that we took action
1352 nil
))) ;; to signal that we did not
1354 (defun org-babel-hide-result-toggle (&optional force
)
1355 "Toggle the visibility of the current result."
1359 (if (re-search-forward org-babel-result-regexp nil t
)
1360 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
1362 (while (looking-at org-babel-multi-line-header-regexp
)
1364 (goto-char (- (org-babel-result-end) 1)) (point)))
1366 (if (memq t
(mapcar (lambda (overlay)
1367 (eq (overlay-get overlay
'invisible
)
1368 'org-babel-hide-result
))
1369 (overlays-at start
)))
1370 (if (or (not force
) (eq force
'off
))
1372 (when (member ov org-babel-hide-result-overlays
)
1373 (setq org-babel-hide-result-overlays
1374 (delq ov org-babel-hide-result-overlays
)))
1375 (when (eq (overlay-get ov
'invisible
)
1376 'org-babel-hide-result
)
1377 (delete-overlay ov
)))
1378 (overlays-at start
)))
1379 (setq ov
(make-overlay start end
))
1380 (overlay-put ov
'invisible
'org-babel-hide-result
)
1381 ;; make the block accessible to isearch
1383 ov
'isearch-open-invisible
1385 (when (member ov org-babel-hide-result-overlays
)
1386 (setq org-babel-hide-result-overlays
1387 (delq ov org-babel-hide-result-overlays
)))
1388 (when (eq (overlay-get ov
'invisible
)
1389 'org-babel-hide-result
)
1390 (delete-overlay ov
))))
1391 (push ov org-babel-hide-result-overlays
)))
1392 (error "Not looking at a result line"))))
1394 ;; org-tab-after-check-for-cycling-hook
1395 (add-hook 'org-tab-first-hook
'org-babel-hide-result-toggle-maybe
)
1396 ;; Remove overlays when changing major mode
1397 (add-hook 'org-mode-hook
1398 (lambda () (org-add-hook 'change-major-mode-hook
1399 'org-babel-show-result-all
'append
'local
)))
1401 (defvar org-file-properties
)
1402 (defun org-babel-params-from-properties (&optional lang
)
1403 "Retrieve parameters specified as properties.
1404 Return a list of association lists of source block params
1405 specified in the properties of the current outline entry."
1408 ;; DEPRECATED header arguments specified as separate property at
1409 ;; point of definition
1411 (org-babel-parse-multiple-vars
1414 (lambda (header-arg)
1415 (and (setq val
(org-entry-get (point) header-arg t
))
1416 (cons (intern (concat ":" header-arg
))
1417 (org-babel-read val
))))
1422 (org-babel-combine-header-arg-lists
1423 org-babel-common-header-args-w-values
1425 (setq sym
(intern (concat "org-babel-header-args:" lang
)))
1426 (and (boundp sym
) (eval sym
))))))))))
1427 ;; header arguments specified with the header-args property at
1429 (org-babel-parse-header-arguments
1430 (org-entry-get org-babel-current-src-block-location
1431 "header-args" 'inherit
))
1432 (when lang
;; language-specific header arguments at point of call
1433 (org-babel-parse-header-arguments
1434 (org-entry-get org-babel-current-src-block-location
1435 (concat "header-args:" lang
) 'inherit
))))))
1437 (defvar org-src-preserve-indentation
) ;; declare defcustom from org-src
1438 (defun org-babel-parse-src-block-match ()
1439 "Parse the results from a match of the `org-babel-src-block-regexp'."
1440 (let* ((block-indentation (length (match-string 1)))
1441 (lang (org-no-properties (match-string 2)))
1442 (lang-headers (intern (concat "org-babel-default-header-args:" lang
)))
1443 (switches (match-string 3))
1444 (body (org-no-properties
1445 (let* ((body (match-string 5))
1446 (sub-length (- (length body
) 1)))
1447 (if (and (> sub-length
0)
1448 (string= "\n" (substring body sub-length
)))
1449 (substring body
0 sub-length
)
1451 (preserve-indentation (or org-src-preserve-indentation
1453 (string-match "-i\\>" switches
)))))
1455 ;; get block body less properties, protective commas, and indentation
1458 (insert (org-unescape-code-in-string body
))
1459 (unless preserve-indentation
(org-do-remove-indentation))
1461 (apply #'org-babel-merge-params
1462 org-babel-default-header-args
1463 (when (boundp lang-headers
) (eval lang-headers
))
1465 (org-babel-params-from-properties lang
)
1466 (list (org-babel-parse-header-arguments
1467 (org-no-properties (or (match-string 4) ""))))))
1469 block-indentation
)))
1471 (defun org-babel-parse-inline-src-block-match ()
1472 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
1473 (let* ((lang (org-no-properties (match-string 2)))
1474 (lang-headers (intern (concat "org-babel-default-header-args:" lang
))))
1476 (org-unescape-code-in-string (org-no-properties (match-string 5)))
1477 (apply #'org-babel-merge-params
1478 org-babel-default-inline-header-args
1479 (if (boundp lang-headers
) (eval lang-headers
) nil
)
1481 (org-babel-params-from-properties lang
)
1482 (list (org-babel-parse-header-arguments
1483 (org-no-properties (or (match-string 4) ""))))))
1486 (defun org-babel-balanced-split (string alts
)
1487 "Split STRING on instances of ALTS.
1488 ALTS is a cons of two character options where each option may be
1489 either the numeric code of a single character or a list of
1490 character alternatives. For example to split on balanced
1491 instances of \"[ \t]:\" set ALTS to '((32 9) . 58)."
1492 (let* ((matches (lambda (ch spec
) (if (listp spec
) (member ch spec
) (equal spec ch
))))
1493 (matched (lambda (ch last
)
1495 (and (funcall matches ch
(cdr alts
))
1496 (funcall matches last
(car alts
)))
1497 (funcall matches ch alts
))))
1498 (balance 0) (last 0)
1500 (mapc (lambda (ch) ; split on [], (), "" balanced instances of [ \t]:
1501 (setq balance
(+ balance
1502 (cond ((or (equal 91 ch
) (equal 40 ch
)) 1)
1503 ((or (equal 93 ch
) (equal 41 ch
)) -
1)
1505 (when (and (equal 34 ch
) (not (equal 92 last
)))
1506 (setq quote
(not quote
)))
1507 (setq partial
(cons ch partial
))
1508 (when (and (= balance
0) (not quote
) (funcall matched ch last
))
1509 (setq lst
(cons (apply #'string
(nreverse
1516 (string-to-list string
))
1517 (nreverse (cons (apply #'string
(nreverse partial
)) lst
))))
1519 (defun org-babel-join-splits-near-ch (ch list
)
1520 "Join splits where \"=\" is on either end of the split."
1521 (let ((last= (lambda (str) (= ch
(aref str
(1- (length str
))))))
1522 (first= (lambda (str) (= ch
(aref str
0)))))
1524 (org-reduce (lambda (acc el
)
1525 (let ((head (car acc
)))
1526 (if (and head
(or (funcall last
= head
) (funcall first
= el
)))
1527 (cons (concat head el
) (cdr acc
))
1529 list
:initial-value nil
))))
1531 (defun org-babel-parse-header-arguments (arg-string)
1532 "Parse a string of header arguments returning an alist."
1533 (when (> (length arg-string
) 0)
1534 (org-babel-parse-multiple-vars
1539 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1541 (cons (intern (match-string 1 arg
))
1542 (org-babel-read (org-babel-chomp (match-string 2 arg
))))
1543 (cons (intern (org-babel-chomp arg
)) nil
)))
1544 (let ((raw (org-babel-balanced-split arg-string
'((32 9) .
58))))
1545 (cons (car raw
) (mapcar (lambda (r) (concat ":" r
)) (cdr raw
)))))))))
1547 (defun org-babel-parse-multiple-vars (header-arguments)
1548 "Expand multiple variable assignments behind a single :var keyword.
1550 This allows expression of multiple variables with one :var as
1553 #+PROPERTY: var foo=1, bar=2"
1555 (mapc (lambda (pair)
1556 (if (eq (car pair
) :var
)
1557 (mapcar (lambda (v) (push (cons :var
(org-babel-trim v
)) results
))
1558 (org-babel-join-splits-near-ch
1559 61 (org-babel-balanced-split (cdr pair
) 32)))
1560 (push pair results
)))
1562 (nreverse results
)))
1564 (defun org-babel-process-params (params)
1565 "Expand variables in PARAMS and add summary parameters."
1566 (let* ((processed-vars (mapcar (lambda (el)
1567 (if (consp (cdr el
))
1569 (org-babel-ref-parse (cdr el
))))
1570 (org-babel-get-header params
:var
)))
1571 (vars-and-names (if (and (assoc :colname-names params
)
1572 (assoc :rowname-names params
))
1573 (list processed-vars
)
1574 (org-babel-disassemble-tables
1576 (cdr (assoc :hlines params
))
1577 (cdr (assoc :colnames params
))
1578 (cdr (assoc :rownames params
)))))
1579 (raw-result (or (cdr (assoc :results params
)) ""))
1580 (result-params (append
1581 (split-string (if (stringp raw-result
)
1584 (cdr (assoc :result-params params
)))))
1586 (mapcar (lambda (var) (cons :var var
)) (car vars-and-names
))
1588 (cons :colname-names
(or (cdr (assoc :colname-names params
))
1589 (cadr vars-and-names
)))
1590 (cons :rowname-names
(or (cdr (assoc :rowname-names params
))
1591 (caddr vars-and-names
)))
1592 (cons :result-params result-params
)
1593 (cons :result-type
(cond ((member "output" result-params
) 'output
)
1594 ((member "value" result-params
) 'value
)
1596 (org-babel-get-header params
:var
'other
))))
1598 ;; row and column names
1599 (defun org-babel-del-hlines (table)
1600 "Remove all 'hlines from TABLE."
1601 (remq 'hline table
))
1603 (defun org-babel-get-colnames (table)
1604 "Return the column names of TABLE.
1605 Return a cons cell, the `car' of which contains the TABLE less
1606 colnames, and the `cdr' of which contains a list of the column
1608 (if (equal 'hline
(nth 1 table
))
1609 (cons (cddr table
) (car table
))
1610 (cons (cdr table
) (car table
))))
1612 (defun org-babel-get-rownames (table)
1613 "Return the row names of TABLE.
1614 Return a cons cell, the `car' of which contains the TABLE less
1615 rownames, and the `cdr' of which contains a list of the rownames.
1616 Note: this function removes any hlines in TABLE."
1617 (let* ((table (org-babel-del-hlines table
))
1618 (rownames (funcall (lambda ()
1624 (setq tp
(cdr tp
))))
1626 (cons table rownames
)))
1628 (defun org-babel-put-colnames (table colnames
)
1629 "Add COLNAMES to TABLE if they exist."
1630 (if colnames
(apply 'list colnames
'hline table
) table
))
1632 (defun org-babel-put-rownames (table rownames
)
1633 "Add ROWNAMES to TABLE if they exist."
1635 (mapcar (lambda (row)
1637 (cons (or (pop rownames
) "") row
)
1641 (defun org-babel-pick-name (names selector
)
1642 "Select one out of an alist of row or column names.
1643 SELECTOR can be either a list of names in which case those names
1644 will be returned directly, or an index into the list NAMES in
1645 which case the indexed names will be return."
1646 (if (listp selector
)
1649 (if (and selector
(symbolp selector
) (not (equal t selector
)))
1650 (cdr (assoc selector names
))
1651 (if (integerp selector
)
1652 (nth (- selector
1) names
)
1653 (cdr (car (last names
))))))))
1655 (defun org-babel-disassemble-tables (vars hlines colnames rownames
)
1656 "Parse tables for further processing.
1657 Process the variables in VARS according to the HLINES,
1658 ROWNAMES and COLNAMES header arguments. Return a list consisting
1659 of the vars, cnames and rnames."
1660 (let (cnames rnames
)
1664 (when (listp (cdr var
))
1665 (when (and (not (equal colnames
"no"))
1666 (or colnames
(and (equal (nth 1 (cdr var
)) 'hline
)
1667 (not (member 'hline
(cddr (cdr var
)))))))
1668 (let ((both (org-babel-get-colnames (cdr var
))))
1669 (setq cnames
(cons (cons (car var
) (cdr both
))
1671 (setq var
(cons (car var
) (car both
)))))
1672 (when (and rownames
(not (equal rownames
"no")))
1673 (let ((both (org-babel-get-rownames (cdr var
))))
1674 (setq rnames
(cons (cons (car var
) (cdr both
))
1676 (setq var
(cons (car var
) (car both
)))))
1677 (when (and hlines
(not (equal hlines
"yes")))
1678 (setq var
(cons (car var
) (org-babel-del-hlines (cdr var
))))))
1681 (reverse cnames
) (reverse rnames
))))
1683 (defun org-babel-reassemble-table (table colnames rownames
)
1684 "Add column and row names to a table.
1685 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1686 to the table for reinsertion to org-mode."
1688 (let ((table (if (and rownames
(= (length table
) (length rownames
)))
1689 (org-babel-put-rownames table rownames
) table
)))
1690 (if (and colnames
(listp (car table
)) (= (length (car table
))
1692 (org-babel-put-colnames table colnames
) table
))
1695 (defun org-babel-where-is-src-block-head ()
1696 "Find where the current source block begins.
1697 Return the point at the beginning of the current source
1698 block. Specifically at the beginning of the #+BEGIN_SRC line.
1699 If the point is not on a source block then return nil."
1700 (let ((initial (point)) (case-fold-search t
) top bottom
)
1702 (save-excursion ;; on a source name line or a #+header line
1703 (beginning-of-line 1)
1704 (and (or (looking-at org-babel-src-name-regexp
)
1705 (looking-at org-babel-multi-line-header-regexp
))
1707 (while (and (forward-line 1)
1708 (or (looking-at org-babel-src-name-regexp
)
1709 (looking-at org-babel-multi-line-header-regexp
))))
1710 (looking-at org-babel-src-block-regexp
))
1712 (save-excursion ;; on a #+begin_src line
1713 (beginning-of-line 1)
1714 (and (looking-at org-babel-src-block-regexp
)
1716 (save-excursion ;; inside a src block
1718 (re-search-backward "^[ \t]*#\\+begin_src" nil t
) (setq top
(point))
1719 (re-search-forward "^[ \t]*#\\+end_src" nil t
) (setq bottom
(point))
1720 (< top initial
) (< initial bottom
)
1721 (progn (goto-char top
) (beginning-of-line 1)
1722 (looking-at org-babel-src-block-regexp
))
1726 (defun org-babel-goto-src-block-head ()
1727 "Go to the beginning of the current code block."
1729 (let ((head (org-babel-where-is-src-block-head)))
1730 (if head
(goto-char head
) (error "Not currently in a code block"))))
1733 (defun org-babel-goto-named-src-block (name)
1734 "Go to a named source-code block."
1736 (let ((completion-ignore-case t
)
1737 (case-fold-search t
)
1738 (under-point (thing-at-point 'line
)))
1739 (list (org-icompleting-read
1740 "source-block name: " (org-babel-src-block-names) nil t
1743 ((string-match (org-babel-noweb-wrap) under-point
)
1744 (let ((block-name (match-string 1 under-point
)))
1745 (string-match "[^(]*" block-name
)
1746 (match-string 0 block-name
)))
1748 ((string-match org-babel-lob-one-liner-regexp under-point
)
1749 (let ((source-info (car (org-babel-lob-get-info))))
1750 (if (string-match "^\\([^\\[]+?\\)\\(\\[.*\\]\\)?(" source-info
)
1751 (let ((source-name (match-string 1 source-info
)))
1754 ((string-match (concat "#\\+" org-babel-results-keyword
1755 "\\:\s+\\([^\\(]*\\)") under-point
)
1756 (match-string 1 under-point
))
1758 ((and (thing-at-point 'symbol
))
1759 (org-babel-find-named-block (thing-at-point 'symbol
))
1760 (thing-at-point 'symbol
))
1762 (let ((point (org-babel-find-named-block name
)))
1764 ;; taken from `org-open-at-point'
1765 (progn (org-mark-ring-push) (goto-char point
) (org-show-context))
1766 (message "source-code block '%s' not found in this buffer" name
))))
1768 (defun org-babel-find-named-block (name)
1769 "Find a named source-code block.
1770 Return the location of the source block identified by source
1771 NAME, or nil if no such block exists. Set match data according to
1772 org-babel-named-src-block-regexp."
1774 (let ((case-fold-search t
)
1775 (regexp (org-babel-named-src-block-regexp-for-name name
)) msg
)
1776 (goto-char (point-min))
1777 (when (or (re-search-forward regexp nil t
)
1778 (re-search-backward regexp nil t
))
1779 (match-beginning 0)))))
1781 (defun org-babel-src-block-names (&optional file
)
1782 "Returns the names of source blocks in FILE or the current buffer."
1784 (when file
(find-file file
)) (goto-char (point-min))
1785 (let ((case-fold-search t
) names
)
1786 (while (re-search-forward org-babel-src-name-w-name-regexp nil t
)
1787 (setq names
(cons (match-string 3) names
)))
1791 (defun org-babel-goto-named-result (name)
1792 "Go to a named result."
1794 (let ((completion-ignore-case t
))
1795 (list (org-icompleting-read "source-block name: "
1796 (org-babel-result-names) nil t
))))
1797 (let ((point (org-babel-find-named-result name
)))
1799 ;; taken from `org-open-at-point'
1800 (progn (goto-char point
) (org-show-context))
1801 (message "result '%s' not found in this buffer" name
))))
1803 (defun org-babel-find-named-result (name &optional point
)
1804 "Find a named result.
1805 Return the location of the result named NAME in the current
1806 buffer or nil if no such result exists."
1808 (let ((case-fold-search t
))
1809 (goto-char (or point
(point-min)))
1810 (catch 'is-a-code-block
1811 (when (re-search-forward
1812 (concat org-babel-result-regexp
1813 "[ \t]" (regexp-quote name
) "[ \t]*[\n\f\v\r]") nil t
)
1814 (when (and (string= "name" (downcase (match-string 1)))
1815 (or (beginning-of-line 1)
1816 (looking-at org-babel-src-block-regexp
)
1817 (looking-at org-babel-multi-line-header-regexp
)
1818 (looking-at org-babel-lob-one-liner-regexp
)))
1819 (throw 'is-a-code-block
(org-babel-find-named-result name
(point))))
1820 (beginning-of-line 0) (point))))))
1822 (defun org-babel-result-names (&optional file
)
1823 "Returns the names of results in FILE or the current buffer."
1825 (when file
(find-file file
)) (goto-char (point-min))
1826 (let ((case-fold-search t
) names
)
1827 (while (re-search-forward org-babel-result-w-name-regexp nil t
)
1828 (setq names
(cons (match-string 4) names
)))
1832 (defun org-babel-next-src-block (&optional arg
)
1833 "Jump to the next source block.
1834 With optional prefix argument ARG, jump forward ARG many source blocks."
1836 (org-next-block arg nil org-babel-src-block-regexp
))
1839 (defun org-babel-previous-src-block (&optional arg
)
1840 "Jump to the previous source block.
1841 With optional prefix argument ARG, jump backward ARG many source blocks."
1843 (org-previous-block arg org-babel-src-block-regexp
))
1845 (defvar org-babel-load-languages
)
1848 (defun org-babel-mark-block ()
1849 "Mark current src block."
1851 (let ((head (org-babel-where-is-src-block-head)))
1855 (looking-at org-babel-src-block-regexp
))
1856 (push-mark (match-end 5) nil t
)
1857 (goto-char (match-beginning 5)))))
1859 (defun org-babel-demarcate-block (&optional arg
)
1860 "Wrap or split the code in the region or on the point.
1861 When called from inside of a code block the current block is
1862 split. When called from outside of a code block a new code block
1863 is created. In both cases if the region is demarcated and if the
1864 region is not active then the point is demarcated."
1866 (let* ((info (org-babel-get-src-block-info 'light
))
1867 (block (progn (org-babel-where-is-src-block-head) (match-string 0)))
1868 (headers (progn (org-babel-where-is-src-block-head) (match-string 4)))
1869 (stars (concat (make-string (or (org-current-level) 1) ?
*) " "))
1871 (if (let (case-fold-search) (string-match "#\\+begin_src" block
))
1872 (setq lower-case-p t
))
1878 (let ((lang (nth 0 info
))
1879 (indent (make-string (nth 5 info
) ?
)))
1880 (when (string-match "^[[:space:]]*$"
1881 (buffer-substring (point-at-bol)
1883 (delete-region (point-at-bol) (point-at-eol)))
1885 (if (looking-at "^") "" "\n")
1886 indent
(funcall (if lower-case-p
'downcase
'upcase
) "#+end_src\n")
1887 (if arg stars indent
) "\n"
1888 indent
(funcall (if lower-case-p
'downcase
'upcase
) "#+begin_src ")
1890 (if (> (length headers
) 1)
1891 (concat " " headers
) headers
)
1892 (if (looking-at "[\n\r]")
1894 (concat "\n" (make-string (current-column) ?
)))))))
1895 (move-end-of-line 2))
1896 (sort (if (org-region-active-p) (list (mark) (point)) (list (point))) #'>))
1897 (let ((start (point))
1898 (lang (org-icompleting-read
1900 (mapcar #'symbol-name
1902 (append (mapcar #'car org-babel-load-languages
)
1903 (mapcar (lambda (el) (intern (car el
)))
1904 org-src-lang-modes
))))))
1905 (body (delete-and-extract-region
1906 (if (org-region-active-p) (mark) (point)) (point))))
1907 (insert (concat (if (looking-at "^") "" "\n")
1908 (if arg
(concat stars
"\n") "")
1909 (funcall (if lower-case-p
'downcase
'upcase
) "#+begin_src ")
1912 (if (or (= (length body
) 0)
1913 (string-match "[\r\n]$" body
)) "" "\n")
1914 (funcall (if lower-case-p
'downcase
'upcase
) "#+end_src\n")))
1915 (goto-char start
) (move-end-of-line 1)))))
1917 (defvar org-babel-lob-one-liner-regexp
)
1918 (defun org-babel-where-is-src-block-result (&optional insert info hash indent
)
1919 "Find where the current source block results begin.
1920 Return the point at the beginning of the result of the current
1921 source block. Specifically at the beginning of the results line.
1922 If no result exists for this block then create a results line
1923 following the source block."
1925 (let* ((case-fold-search t
)
1926 (on-lob-line (save-excursion
1927 (beginning-of-line 1)
1928 (looking-at org-babel-lob-one-liner-regexp
)))
1929 (inlinep (when (org-babel-get-inline-src-block-matches)
1931 (name (nth 4 (or info
(org-babel-get-src-block-info 'light
))))
1932 (head (unless on-lob-line
(org-babel-where-is-src-block-head)))
1934 (when head
(goto-char head
))
1935 (org-with-wide-buffer
1937 found
;; was there a result (before we potentially insert one)
1942 ;; - return t if it is found, else return nil
1943 ;; - if it does not need to be rebuilt, then don't set end
1944 ;; - if it does need to be rebuilt then do set end
1945 name
(setq beg
(org-babel-find-named-result name
))
1947 (when (and hash
(not (string= hash
(match-string 5))))
1948 (goto-char beg
) (setq end beg
) ;; beginning of result
1950 (delete-region end
(org-babel-result-end)) nil
)))
1953 ;; - return t if it is found, else return nil
1954 ;; - if it is found, and the hash doesn't match, delete and set end
1955 (or on-lob-line
(re-search-forward "^[ \t]*#\\+end_src" nil t
))
1956 (progn (end-of-line 1)
1957 (if (eobp) (insert "\n") (forward-char 1))
1961 (progn ;; unnamed results line already exists
1963 (while (re-search-forward "[^ \f\t\n\r\v]" nil t
)
1964 (beginning-of-line 1)
1966 ((looking-at (concat org-babel-result-regexp
"\n"))
1967 (throw 'non-comment t
))
1968 ((and (looking-at "^[ \t]*#")
1970 org-babel-lob-one-liner-regexp
)))
1972 (t (throw 'non-comment nil
))))))
1973 (let ((this-hash (match-string 5)))
1975 ;; must remove and rebuild if hash!=old-hash
1976 (if (and hash
(not (string= hash this-hash
)))
1978 (setq end
(point-at-bol))
1980 (delete-region end
(org-babel-result-end))
1982 (setq end nil
))))))))))
1983 (if (not (and insert end
)) found
1986 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1988 (when (wholenump indent
) (make-string indent ?
))
1989 "#+" org-babel-results-keyword
1991 (if org-babel-hash-show-time
1993 "["(format-time-string "<%Y-%m-%d %H:%M:%S>")" "hash
"]")
1994 (concat "["hash
"]")))
1996 (when name
(concat " " name
)) "\n"))
1997 (unless beg
(insert "\n") (backward-char))
1998 (beginning-of-line 0)
1999 (if hash
(org-babel-hide-hash))
2002 (defvar org-block-regexp
)
2003 (defun org-babel-read-result ()
2004 "Read the result at `point' into emacs-lisp."
2005 (let ((case-fold-search t
) result-string
)
2007 ((org-at-table-p) (org-babel-read-table))
2008 ((org-at-item-p) (org-babel-read-list))
2009 ((looking-at org-bracket-link-regexp
) (org-babel-read-link))
2010 ((looking-at org-block-regexp
) (org-remove-indentation (match-string 4)))
2011 ((or (looking-at "^[ \t]*: ") (looking-at "^[ \t]*:$"))
2014 (mapconcat (lambda (line)
2015 (or (and (> (length line
) 1)
2016 (string-match "^[ \t]*: ?\\(.+\\)" line
)
2017 (match-string 1 line
))
2021 (point) (org-babel-result-end)) "[\r\n]+")
2023 (or (org-babel-number-p result-string
) result-string
))
2024 ((looking-at org-babel-result-regexp
)
2025 (save-excursion (forward-line 1) (org-babel-read-result))))))
2027 (defun org-babel-read-table ()
2028 "Read the table at `point' into emacs-lisp."
2029 (mapcar (lambda (row)
2030 (if (and (symbolp row
) (equal row
'hline
)) row
2031 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
)) row
)))
2032 (org-table-to-lisp)))
2034 (defun org-babel-read-list ()
2035 "Read the list at `point' into emacs-lisp."
2036 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
))
2037 (mapcar #'cadr
(cdr (org-list-parse-list)))))
2039 (defvar org-link-types-re
)
2040 (defun org-babel-read-link ()
2041 "Read the link at `point' into emacs-lisp.
2042 If the path of the link is a file path it is expanded using
2043 `expand-file-name'."
2044 (let* ((case-fold-search t
)
2045 (raw (and (looking-at org-bracket-link-regexp
)
2046 (org-no-properties (match-string 1))))
2047 (type (and (string-match org-link-types-re raw
)
2048 (match-string 1 raw
))))
2050 ((not type
) (expand-file-name raw
))
2051 ((string= type
"file")
2052 (and (string-match "file\\(.*\\):\\(.+\\)" raw
)
2053 (expand-file-name (match-string 2 raw
))))
2056 (defun org-babel-format-result (result &optional sep
)
2057 "Format RESULT for writing to file."
2058 (let ((echo-res (lambda (r) (if (stringp r
) r
(format "%S" r
)))))
2062 result
(list :sep
(or sep
"\t") :fmt echo-res
))
2064 (funcall echo-res result
))))
2066 (defun org-babel-insert-result
2067 (result &optional result-params info hash indent lang
)
2068 "Insert RESULT into the current buffer.
2069 By default RESULT is inserted after the end of the
2070 current source block. With optional argument RESULT-PARAMS
2071 controls insertion of results in the org-mode file.
2072 RESULT-PARAMS can take the following values:
2074 replace - (default option) insert results after the source block
2075 replacing any previously inserted results
2077 silent -- no results are inserted into the Org-mode buffer but
2078 the results are echoed to the minibuffer and are
2079 ingested by Emacs (a potentially time consuming
2082 file ---- the results are interpreted as a file path, and are
2083 inserted into the buffer using the Org-mode file syntax
2085 list ---- the results are interpreted as an Org-mode list.
2087 raw ----- results are added directly to the Org-mode file. This
2088 is a good option if you code block will output org-mode
2091 drawer -- results are added directly to the Org-mode file as with
2092 \"raw\", but are wrapped in a RESULTS drawer, allowing
2093 them to later be replaced or removed automatically.
2095 org ----- results are added inside of a \"src_org{}\" or \"#+BEGIN_SRC
2096 org\" block depending on whether the current source block is
2097 inline or not. They are not comma-escaped when inserted,
2098 but Org syntax here will be discarded when exporting the
2101 html ---- results are added inside of a #+BEGIN_HTML block. This
2102 is a good option if you code block will output html
2105 latex --- results are added inside of a #+BEGIN_LATEX block.
2106 This is a good option if you code block will output
2107 latex formatted text.
2109 code ---- the results are extracted in the syntax of the source
2110 code of the language being evaluated and are added
2111 inside of a source block with the source-code language
2112 set appropriately. Also, source block inlining is
2113 preserved in this case. Note this relies on the
2114 optional LANG argument."
2115 (if (stringp result
)
2117 (setq result
(org-no-properties result
))
2118 (when (member "file" result-params
)
2119 (setq result
(org-babel-result-to-file
2120 result
(when (assoc :file-desc
(nth 2 info
))
2121 (or (cdr (assoc :file-desc
(nth 2 info
)))
2123 (unless (listp result
) (setq result
(format "%S" result
))))
2124 (if (and result-params
(member "silent" result-params
))
2126 (message (replace-regexp-in-string "%" "%%" (format "%S" result
)))
2131 (when (or (org-babel-get-inline-src-block-matches)
2132 (org-babel-get-lob-one-liner-matches))
2133 (goto-char (match-end 0))
2134 (insert (if (listp result
) "\n" " "))
2136 (existing-result (unless inlinep
2137 (org-babel-where-is-src-block-result
2138 t info hash indent
)))
2140 (cdr (assoc :results_switches
(nth 2 info
))))
2141 (visible-beg (copy-marker (point-min)))
2142 (visible-end (copy-marker (point-max)))
2143 ;; When results exist outside of the current visible
2144 ;; region of the buffer, be sure to widen buffer to
2146 (outside-scope-p (and existing-result
2147 (or (> visible-beg existing-result
)
2148 (<= visible-end existing-result
))))
2150 (when (and (stringp result
) ; ensure results end in a newline
2152 (> (length result
) 0)
2153 (not (or (string-equal (substring result -
1) "\n")
2154 (string-equal (substring result -
1) "\r"))))
2155 (setq result
(concat result
"\n")))
2158 (when outside-scope-p
(widen))
2159 (if (not existing-result
)
2160 (setq beg
(or inlinep
(point)))
2161 (goto-char existing-result
)
2163 (re-search-forward "#" nil t
)
2164 (setq indent
(- (current-column) 1)))
2168 ((member "replace" result-params
)
2169 (delete-region (point) (org-babel-result-end)))
2170 ((member "append" result-params
)
2171 (goto-char (org-babel-result-end)) (setq beg
(point-marker)))
2172 ((member "prepend" result-params
)))) ; already there
2173 (setq results-switches
2174 (if results-switches
(concat " " results-switches
) ""))
2175 (let ((wrap (lambda (start finish
&optional no-escape no-newlines
)
2177 (insert (concat finish
(unless no-newlines
"\n")))
2179 (insert (concat start
(unless no-newlines
"\n")))
2181 (org-escape-code-in-region (min (point) end
) end
))
2183 (unless no-newlines
(goto-char (point-at-eol)))
2184 (setq end
(point-marker))))
2185 (proper-list-p (lambda (it) (and (listp it
) (null (cdr (last it
)))))))
2186 ;; insert results based on type
2188 ;; do nothing for an empty result
2190 ;; insert a list if preferred
2191 ((member "list" result-params
)
2194 (org-list-to-generic
2197 (lambda (el) (list nil
(if (stringp el
) el
(format "%S" el
))))
2198 (if (listp result
) result
(split-string result
"\n" t
))))
2199 '(:splicep nil
:istart
"- " :iend
"\n")))
2201 ;; assume the result is a table if it's not a string
2202 ((funcall proper-list-p result
)
2204 (insert (concat (orgtbl-to-orgtbl
2206 (lambda (el) (or (listp el
) (eq el
'hline
)))
2208 result
(list result
))
2209 '(:fmt
(lambda (cell) (format "%s" cell
)))) "\n"))
2210 (goto-char beg
) (when (org-at-table-p) (org-table-align)))
2211 ((and (listp result
) (not (funcall proper-list-p result
)))
2212 (insert (format "%s\n" result
)))
2213 ((member "file" result-params
)
2214 (when inlinep
(goto-char inlinep
))
2216 (t (goto-char beg
) (insert result
)))
2217 (when (funcall proper-list-p result
) (goto-char (org-table-end)))
2218 (setq end
(point-marker))
2219 ;; possibly wrap result
2221 ((assoc :wrap
(nth 2 info
))
2222 (let ((name (or (cdr (assoc :wrap
(nth 2 info
))) "RESULTS")))
2223 (funcall wrap
(concat "#+BEGIN_" name
)
2224 (concat "#+END_" (car (org-split-string name
))))))
2225 ((member "html" result-params
)
2226 (funcall wrap
"#+BEGIN_HTML" "#+END_HTML"))
2227 ((member "latex" result-params
)
2228 (funcall wrap
"#+BEGIN_LaTeX" "#+END_LaTeX"))
2229 ((member "org" result-params
)
2230 (goto-char beg
) (if (org-at-table-p) (org-cycle))
2232 (funcall wrap
"src_org{" "}" nil t
)
2233 (funcall wrap
"#+BEGIN_SRC org" "#+END_SRC")))
2234 ((member "code" result-params
)
2235 (let ((lang (or lang
"none")))
2237 (funcall wrap
(format "src_%s[%s]{" lang results-switches
)
2239 (funcall wrap
(format "#+BEGIN_SRC %s%s" lang results-switches
)
2241 ((member "raw" result-params
)
2242 (goto-char beg
) (if (org-at-table-p) (org-cycle)))
2243 ((or (member "drawer" result-params
)
2244 ;; Stay backward compatible with <7.9.2
2245 (member "wrap" result-params
))
2246 (goto-char beg
) (if (org-at-table-p) (org-cycle))
2247 (funcall wrap
":RESULTS:" ":END:" 'no-escape
))
2248 ((and (not (funcall proper-list-p result
))
2249 (not (member "file" result-params
)))
2250 (org-babel-examplify-region beg end results-switches
)
2251 (setq end
(point)))))
2252 ;; possibly indent the results to match the #+results line
2253 (when (and (not inlinep
) (numberp indent
) indent
(> indent
0)
2254 ;; in this case `table-align' does the work for us
2255 (not (and (listp result
)
2256 (member "append" result-params
))))
2257 (indent-rigidly beg end indent
))
2259 (if (member "value" result-params
)
2260 (message "Code block returned no value.")
2261 (message "Code block produced no output."))
2262 (message "Code block evaluation complete.")))
2263 (when outside-scope-p
(narrow-to-region visible-beg visible-end
))
2264 (set-marker visible-beg nil
)
2265 (set-marker visible-end nil
))))))
2267 (defun org-babel-remove-result (&optional info keep-keyword
)
2268 "Remove the result of the current source block."
2270 (let ((location (org-babel-where-is-src-block-result nil info
)))
2273 (goto-char location
)
2274 (when (looking-at (concat org-babel-result-regexp
".*$"))
2276 (if keep-keyword
(1+ (match-end 0)) (1- (match-beginning 0)))
2277 (progn (forward-line 1) (org-babel-result-end))))))))
2279 (defun org-babel-remove-result-one-or-many (x)
2280 "Remove the result of the current source block.
2281 If called with a prefix argument, remove all result blocks
2285 (org-babel-map-src-blocks nil
(org-babel-remove-result))
2286 (org-babel-remove-result)))
2288 (defun org-babel-result-end ()
2289 "Return the point at the end of the current set of results."
2292 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
2293 ((org-at-item-p) (let* ((struct (org-list-struct))
2294 (prvs (org-list-prevs-alist struct
)))
2295 (org-list-get-list-end (point-at-bol) struct prvs
)))
2296 ((let ((case-fold-search t
)) (looking-at "^\\([ \t]*\\):results:"))
2297 (progn (re-search-forward (concat "^" (match-string 1) ":END:"))
2298 (forward-char 1) (point)))
2300 (let ((case-fold-search t
))
2301 (if (looking-at (concat "[ \t]*#\\+begin_\\([^ \t\n\r]+\\)"))
2302 (progn (re-search-forward (concat "[ \t]*#\\+end_" (match-string 1))
2305 (while (looking-at "[ \t]*\\(: \\|:$\\|\\[\\[\\)")
2309 (defun org-babel-result-to-file (result &optional description
)
2310 "Convert RESULT into an `org-mode' link with optional DESCRIPTION.
2311 If the `default-directory' is different from the containing
2312 file's directory then expand relative links."
2313 (when (stringp result
)
2314 (format "[[file:%s]%s]"
2315 (if (and default-directory
2317 (not (string= (expand-file-name default-directory
)
2319 (file-name-directory buffer-file-name
)))))
2320 (expand-file-name result default-directory
)
2322 (if description
(concat "[" description
"]") ""))))
2324 (defvar org-babel-capitalize-example-region-markers nil
2325 "Make true to capitalize begin/end example markers inserted by code blocks.")
2327 (define-obsolete-function-alias
2328 'org-babel-examplize-region
2329 'org-babel-examplify-region
"25.1")
2331 (defun org-babel-examplify-region (beg end
&optional results-switches
)
2332 "Comment out region using the inline '==' or ': ' org example quote."
2334 (let ((chars-between (lambda (b e
)
2335 (not (string-match "^[\\s]*$"
2336 (buffer-substring b e
)))))
2337 (maybe-cap (lambda (str) (if org-babel-capitalize-example-region-markers
2339 (beg-bol (save-excursion (goto-char beg
) (point-at-bol)))
2340 (end-bol (save-excursion (goto-char end
) (point-at-bol)))
2341 (end-eol (save-excursion (goto-char end
) (point-at-eol))))
2342 (if (and (not (= end end-bol
))
2343 (or (funcall chars-between beg-bol beg
)
2344 (funcall chars-between end end-eol
)))
2347 (insert (format org-babel-inline-result-wrap
2348 (prog1 (buffer-substring beg end
)
2349 (delete-region beg end
)))))
2350 (let ((size (count-lines beg end
)))
2352 (cond ((= size
0)) ; do nothing for an empty result
2353 ((< size org-babel-min-lines-for-block-output
)
2356 (beginning-of-line 1) (insert ": ") (forward-line 1)))
2359 (insert (if results-switches
2361 (funcall maybe-cap
"#+begin_example")
2363 (funcall maybe-cap
"#+begin_example\n")))
2364 (if (markerp end
) (goto-char end
) (forward-char (- end beg
)))
2365 (insert (funcall maybe-cap
"#+end_example\n")))))))))
2367 (defun org-babel-update-block-body (new-body)
2368 "Update the body of the current code block to NEW-BODY."
2369 (if (not (org-babel-where-is-src-block-head))
2370 (error "Not in a source block")
2372 (replace-match (concat (org-babel-trim (org-remove-indentation new-body
))
2374 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
2376 (defun org-babel-merge-params (&rest plists
)
2377 "Combine all parameter association lists in PLISTS.
2378 Later elements of PLISTS override the values of previous elements.
2379 This takes into account some special considerations for certain
2380 parameters when merging lists."
2381 (let* ((results-exclusive-groups
2382 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2383 (cdr (assoc 'results org-babel-common-header-args-w-values
))))
2384 (exports-exclusive-groups
2385 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2386 (cdr (assoc 'exports org-babel-common-header-args-w-values
))))
2388 (e-merge (lambda (exclusive-groups &rest result-params
)
2389 ;; maintain exclusivity of mutually exclusive parameters
2391 (mapc (lambda (new-params)
2392 (mapc (lambda (new-param)
2393 (mapc (lambda (exclusive-group)
2394 (when (member new-param exclusive-group
)
2395 (mapcar (lambda (excluded-param)
2402 (setq output
(org-uniquify
2403 (cons new-param output
))))
2407 params results exports tangle noweb cache vars shebang comments padline
2416 (let ((name (if (listp (cdr pair
))
2418 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
2420 (intern (match-string 1 (cdr pair
)))))))
2424 (if (member name
(mapcar #'car vars
))
2426 (push name clearnames
)
2430 (unless (equal (car p
) name
) p
))
2433 (list (cons name pair
))))
2434 ;; if no name is given and we already have named variables
2435 ;; then assign to named variables in order
2436 (if (and vars
(nth variable-index vars
))
2437 (let ((name (car (nth variable-index vars
))))
2438 (push name clearnames
) ; clear out colnames
2441 (prog1 (setf (cddr (nth variable-index vars
))
2442 (concat (symbol-name name
) "=" (cdr pair
)))
2443 (incf variable-index
)))
2444 (error "Variable \"%s\" must be assigned a default value"
2447 (setq results
(funcall e-merge results-exclusive-groups
2450 (let ((r (cdr pair
)))
2451 (if (stringp r
) r
(eval r
)))))))
2454 (setq results
(funcall e-merge results-exclusive-groups
2456 (unless (or (member "both" exports
)
2457 (member "none" exports
)
2458 (member "code" exports
))
2459 (setq exports
(funcall e-merge exports-exclusive-groups
2460 exports
'("results"))))
2461 (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))
2464 (setq results
(funcall e-merge results-exclusive-groups
2466 (unless (or (member "both" exports
)
2467 (member "none" exports
)
2468 (member "code" exports
))
2469 (setq exports
(funcall e-merge exports-exclusive-groups
2470 exports
'("results"))))
2471 (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))
2473 (setq exports
(funcall e-merge exports-exclusive-groups
2474 exports
(split-string (cdr pair
)))))
2475 (:tangle
;; take the latest -- always overwrite
2476 (setq tangle
(or (list (cdr pair
)) tangle
)))
2478 (setq noweb
(funcall e-merge
2479 '(("yes" "no" "tangle" "no-export"
2480 "strip-export" "eval"))
2482 (split-string (or (cdr pair
) "")))))
2484 (setq cache
(funcall e-merge
'(("yes" "no")) cache
2485 (split-string (or (cdr pair
) "")))))
2487 (setq padline
(funcall e-merge
'(("yes" "no")) padline
2488 (split-string (or (cdr pair
) "")))))
2489 (:shebang
;; take the latest -- always overwrite
2490 (setq shebang
(or (list (cdr pair
)) shebang
)))
2492 (setq comments
(funcall e-merge
'(("yes" "no")) comments
2493 (split-string (or (cdr pair
) "")))))
2494 (t ;; replace: this covers e.g. :session
2495 (setq params
(cons pair
(assq-delete-all (car pair
) params
))))))
2498 (setq vars
(reverse vars
))
2499 (while vars
(setq params
(cons (cons :var
(cddr (pop vars
))) params
)))
2500 ;; clear out col-names and row-names for replaced variables
2505 (when (assoc param params
)
2506 (setf (cdr (assoc param params
))
2507 (org-remove-if (lambda (pair) (equal (car pair
) name
))
2508 (cdr (assoc param params
))))
2509 (setf params
(org-remove-if (lambda (pair) (and (equal (car pair
) param
)
2512 (list :colname-names
:rowname-names
)))
2516 (let ((key (intern (concat ":" (symbol-name hd
))))
2518 (setf params
(cons (cons key
(mapconcat 'identity val
" ")) params
))))
2519 '(results exports tangle noweb padline cache shebang comments
))
2522 (defvar org-babel-use-quick-and-dirty-noweb-expansion nil
2523 "Set to true to use regular expressions to expand noweb references.
2524 This results in much faster noweb reference expansion but does
2525 not properly allow code blocks to inherit the \":noweb-ref\"
2526 header argument from buffer or subtree wide properties.")
2528 (defun org-babel-noweb-p (params context
)
2529 "Check if PARAMS require expansion in CONTEXT.
2530 CONTEXT may be one of :tangle, :export or :eval."
2532 (intersect (lambda (as bs
)
2534 (if (member (car as
) bs
)
2536 (funcall intersect
(cdr as
) bs
))))))
2537 (funcall intersect
(case context
2538 (:tangle
'("yes" "tangle" "no-export" "strip-export"))
2539 (:eval
'("yes" "no-export" "strip-export" "eval"))
2541 (split-string (or (cdr (assoc :noweb params
)) "")))))
2543 (defun org-babel-expand-noweb-references (&optional info parent-buffer
)
2544 "Expand Noweb references in the body of the current source code block.
2546 For example the following reference would be replaced with the
2547 body of the source-code block named 'example-block'.
2551 Note that any text preceding the <<foo>> construct on a line will
2552 be interposed between the lines of the replacement text. So for
2553 example if <<foo>> is placed behind a comment, then the entire
2554 replacement text will also be commented.
2556 This function must be called from inside of the buffer containing
2557 the source-code block which holds BODY.
2559 In addition the following syntax can be used to insert the
2560 results of evaluating the source-code block named 'example-block'.
2564 Any optional arguments can be passed to example-block by placing
2565 the arguments inside the parenthesis following the convention
2566 defined by `org-babel-lob'. For example
2568 <<example-block(a=9)>>
2570 would set the value of argument \"a\" equal to \"9\". Note that
2571 these arguments are not evaluated in the current source-code
2572 block but are passed literally to the \"example-block\"."
2573 (let* ((parent-buffer (or parent-buffer
(current-buffer)))
2574 (info (or info
(org-babel-get-src-block-info 'light
)))
2577 (ob-nww-start org-babel-noweb-wrap-start
)
2578 (ob-nww-end org-babel-noweb-wrap-end
)
2579 (comment (string= "noweb" (cdr (assoc :comments
(nth 2 info
)))))
2580 (rx-prefix (concat "\\(" org-babel-src-name-regexp
"\\|"
2581 ":noweb-ref[ \t]+" "\\)"))
2583 (nb-add (lambda (text) (setq new-body
(concat new-body text
))))
2584 (c-wrap (lambda (text)
2586 (funcall (intern (concat lang
"-mode")))
2587 (comment-region (point) (progn (insert text
) (point)))
2588 (org-babel-trim (buffer-string)))))
2589 index source-name evaluate prefix
)
2591 (org-set-local 'org-babel-noweb-wrap-start ob-nww-start
)
2592 (org-set-local 'org-babel-noweb-wrap-end ob-nww-end
)
2593 (insert body
) (goto-char (point-min))
2594 (setq index
(point))
2595 (while (and (re-search-forward (org-babel-noweb-wrap) nil t
))
2596 (save-match-data (setf source-name
(match-string 1)))
2597 (save-match-data (setq evaluate
(string-match "\(.*\)" source-name
)))
2600 (buffer-substring (match-beginning 0)
2602 (beginning-of-line 1) (point)))))
2603 ;; add interval to new-body (removing noweb reference)
2604 (goto-char (match-beginning 0))
2605 (funcall nb-add
(buffer-substring index
(point)))
2606 (goto-char (match-end 0))
2607 (setq index
(point))
2610 (with-current-buffer parent-buffer
2613 (mapconcat ;; Interpose PREFIX between every line.
2617 (let ((raw (org-babel-ref-resolve source-name
)))
2618 (if (stringp raw
) raw
(format "%S" raw
)))
2620 ;; Retrieve from the library of babel.
2621 (nth 2 (assoc (intern source-name
)
2622 org-babel-library-of-babel
))
2623 ;; Return the contents of headlines literally.
2625 (when (org-babel-ref-goto-headline-id source-name
)
2626 (org-babel-ref-headline-body)))
2627 ;; Find the expansion of reference in this buffer.
2628 (let ((rx (concat rx-prefix source-name
"[ \t\n]"))
2631 (goto-char (point-min))
2632 (if org-babel-use-quick-and-dirty-noweb-expansion
2633 (while (re-search-forward rx nil t
)
2634 (let* ((i (org-babel-get-src-block-info 'light
))
2635 (body (org-babel-expand-noweb-references i
))
2636 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2639 (let ((cs (org-babel-tangle-comment-links i
)))
2640 (concat (funcall c-wrap
(car cs
)) "\n"
2642 (funcall c-wrap
(cadr cs
))))
2644 (setq expansion
(cons sep
(cons full expansion
)))))
2645 (org-babel-map-src-blocks nil
2646 (let ((i (org-babel-get-src-block-info 'light
)))
2647 (when (equal (or (cdr (assoc :noweb-ref
(nth 2 i
)))
2650 (let* ((body (org-babel-expand-noweb-references i
))
2651 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2654 (let ((cs (org-babel-tangle-comment-links i
)))
2655 (concat (funcall c-wrap
(car cs
)) "\n"
2657 (funcall c-wrap
(cadr cs
))))
2660 (cons sep
(cons full expansion
)))))))))
2662 (mapconcat #'identity
(nreverse (cdr expansion
)) "")))
2663 ;; Possibly raise an error if named block doesn't exist.
2664 (if (or org-babel-noweb-error-all-langs
2665 (member lang org-babel-noweb-error-langs
))
2667 (org-babel-noweb-wrap source-name
)
2668 "could not be resolved (see "
2669 "`org-babel-noweb-error-langs')"))
2671 "[\n\r]") (concat "\n" prefix
))))))
2672 (funcall nb-add
(buffer-substring index
(point-max))))
2675 (defun org-babel-script-escape (str &optional force
)
2676 "Safely convert tables into elisp lists."
2681 (or (and (string-equal "[" (substring str
0 1))
2682 (string-equal "]" (substring str -
1)))
2683 (and (string-equal "{" (substring str
0 1))
2684 (string-equal "}" (substring str -
1)))
2685 (and (string-equal "(" (substring str
0 1))
2686 (string-equal ")" (substring str -
1))))))
2690 (let (in-single in-double out
)
2696 (91 (if (or in-double in-single
) ; [
2699 (93 (if (or in-double in-single
) ; ]
2702 (123 (if (or in-double in-single
) ; {
2705 (125 (if (or in-double in-single
) ; }
2708 (44 (if (or in-double in-single
) ; ,
2709 (cons 44 out
) (cons 32 out
)))
2710 (39 (if in-double
; '
2712 (setq in-single
(not in-single
)) (cons 34 out
)))
2713 (34 (if in-single
; "
2714 (append (list 34 32) out
)
2715 (setq in-double
(not in-double
)) (cons 34 out
)))
2716 (t (cons ch out
)))))
2717 (string-to-list str
))
2718 (apply #'string
(reverse out
)))))
2720 (condition-case nil
(org-babel-read escaped
) (error escaped
))))
2722 (defun org-babel-read (cell &optional inhibit-lisp-eval
)
2723 "Convert the string value of CELL to a number if appropriate.
2724 Otherwise if cell looks like lisp (meaning it starts with a
2725 \"(\", \"'\", \"`\" or a \"[\") then read it as lisp,
2726 otherwise return it unmodified as a string. Optional argument
2727 NO-LISP-EVAL inhibits lisp evaluation for situations in which is
2728 it not appropriate."
2729 (if (and (stringp cell
) (not (equal cell
"")))
2730 (or (org-babel-number-p cell
)
2731 (if (and (not inhibit-lisp-eval
)
2732 (or (member (substring cell
0 1) '("(" "'" "`" "["))
2733 (string= cell
"*this*")))
2735 (if (string= (substring cell
0 1) "\"")
2737 (progn (set-text-properties 0 (length cell
) nil cell
) cell
))))
2740 (defun org-babel-number-p (string)
2741 "If STRING represents a number return its value."
2742 (if (and (string-match "[0-9]+" string
)
2743 (string-match "^-?[0-9]*\\.?[0-9]*$" string
)
2744 (= (length (substring string
(match-beginning 0)
2747 (string-to-number string
)))
2749 (defun org-babel-import-elisp-from-file (file-name &optional separator
)
2750 "Read the results located at FILE-NAME into an elisp table.
2751 If the table is trivial, then return it as a scalar."
2753 (save-window-excursion
2757 (org-table-import file-name separator
)
2758 (delete-file file-name
)
2759 (setq result
(mapcar (lambda (row)
2760 (mapcar #'org-babel-string-read row
))
2761 (org-table-to-lisp))))
2762 (error (message "Error reading results: %s" err
) nil
)))
2763 (if (null (cdr result
)) ;; if result is trivial vector, then scalarize it
2764 (if (consp (car result
))
2765 (if (null (cdr (car result
)))
2771 (defun org-babel-string-read (cell)
2772 "Strip nested \"s from around strings."
2773 (org-babel-read (or (and (stringp cell
)
2774 (string-match "\\\"\\(.+\\)\\\"" cell
)
2775 (match-string 1 cell
))
2778 (defun org-babel-chomp (string &optional regexp
)
2779 "Strip a trailing space or carriage return from STRING.
2780 The default regexp used is \"[ \\f\\t\\n\\r\\v]\" but another one
2781 can be specified as the REGEXP argument."
2782 (let ((regexp (or regexp
"[ \f\t\n\r\v]")))
2783 (while (and (> (length string
) 0)
2784 (string-match regexp
(substring string -
1)))
2785 (setq string
(substring string
0 -
1)))
2788 (defun org-babel-trim (string &optional regexp
)
2789 "Strip a leading and trailing space or carriage return from STRING.
2790 Like `org-babel-chomp', but run on both the first and last
2791 character of the string."
2794 (org-babel-chomp (org-reverse-string string
) regexp
)) regexp
))
2796 (defun org-babel-tramp-handle-call-process-region
2797 (start end program
&optional delete buffer display
&rest args
)
2798 "Use Tramp to handle `call-process-region'.
2799 Fixes a bug in `tramp-handle-call-process-region'."
2800 (if (and (featurep 'tramp
) (file-remote-p default-directory
))
2801 (let ((tmpfile (tramp-compat-make-temp-file "")))
2802 (write-region start end tmpfile
)
2803 (when delete
(delete-region start end
))
2805 ;; (apply 'call-process program tmpfile buffer display args)
2807 (apply 'process-file program tmpfile buffer display args
)
2808 (delete-file tmpfile
)))
2809 ;; org-babel-call-process-region-original is the original emacs
2810 ;; definition. It is in scope from the let binding in
2811 ;; org-babel-execute-src-block
2812 (apply org-babel-call-process-region-original
2813 start end program delete buffer display args
)))
2815 (defun org-babel-local-file-name (file)
2816 "Return the local name component of FILE."
2817 (or (file-remote-p file
'localname
) file
))
2819 (defun org-babel-process-file-name (name &optional no-quote-p
)
2820 "Prepare NAME to be used in an external process.
2821 If NAME specifies a remote location, the remote portion of the
2822 name is removed, since in that case the process will be executing
2823 remotely. The file name is then processed by `expand-file-name'.
2824 Unless second argument NO-QUOTE-P is non-nil, the file name is
2825 additionally processed by `shell-quote-argument'"
2826 (let ((f (org-babel-local-file-name (expand-file-name name
))))
2827 (if no-quote-p f
(shell-quote-argument f
))))
2829 (defvar org-babel-temporary-directory
)
2830 (unless (or noninteractive
(boundp 'org-babel-temporary-directory
))
2831 (defvar org-babel-temporary-directory
2832 (or (and (boundp 'org-babel-temporary-directory
)
2833 (file-exists-p org-babel-temporary-directory
)
2834 org-babel-temporary-directory
)
2835 (make-temp-file "babel-" t
))
2836 "Directory to hold temporary files created to execute code blocks.
2837 Used by `org-babel-temp-file'. This directory will be removed on
2840 (defcustom org-babel-remote-temporary-directory
"/tmp/"
2841 "Directory to hold temporary files on remote hosts."
2845 (defmacro org-babel-result-cond
(result-params scalar-form
&rest table-forms
)
2846 "Call the code to parse raw string results according to RESULT-PARAMS."
2848 (debug (form form
&rest form
)))
2849 (org-with-gensyms (params)
2850 `(let ((,params
,result-params
))
2851 (unless (member "none" ,params
)
2852 (if (or (member "scalar" ,params
)
2853 (member "verbatim" ,params
)
2854 (member "html" ,params
)
2855 (member "code" ,params
)
2856 (member "pp" ,params
)
2857 (and (or (member "output" ,params
)
2858 (member "raw" ,params
)
2859 (member "org" ,params
)
2860 (member "drawer" ,params
))
2861 (not (member "table" ,params
))))
2864 (def-edebug-spec org-babel-result-cond
(form form body
))
2866 (defun org-babel-temp-file (prefix &optional suffix
)
2867 "Create a temporary file in the `org-babel-temporary-directory'.
2868 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2869 value of `temporary-file-directory' temporarily set to the value
2870 of `org-babel-temporary-directory'."
2871 (if (file-remote-p default-directory
)
2873 (concat (file-remote-p default-directory
)
2875 prefix org-babel-remote-temporary-directory
))))
2876 (make-temp-file prefix nil suffix
))
2877 (let ((temporary-file-directory
2878 (or (and (boundp 'org-babel-temporary-directory
)
2879 (file-exists-p org-babel-temporary-directory
)
2880 org-babel-temporary-directory
)
2881 temporary-file-directory
)))
2882 (make-temp-file prefix nil suffix
))))
2884 (defun org-babel-remove-temporary-directory ()
2885 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2886 (when (and (boundp 'org-babel-temporary-directory
)
2887 (file-exists-p org-babel-temporary-directory
))
2888 ;; taken from `delete-directory' in files.el
2891 (mapc (lambda (file)
2892 ;; This test is equivalent to
2893 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2894 ;; but more efficient
2895 (if (eq t
(car (file-attributes file
)))
2896 (delete-directory file
)
2897 (delete-file file
)))
2898 ;; We do not want to delete "." and "..".
2899 (directory-files org-babel-temporary-directory
'full
2900 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2901 (delete-directory org-babel-temporary-directory
))
2903 (message "Failed to remove temporary Org-babel directory %s"
2904 (if (boundp 'org-babel-temporary-directory
)
2905 org-babel-temporary-directory
2906 "[directory not defined]"))))))
2908 (add-hook 'kill-emacs-hook
'org-babel-remove-temporary-directory
)
2910 (defun org-babel-one-header-arg-safe-p (pair safe-list
)
2911 "Determine if the PAIR is a safe babel header arg according to SAFE-LIST.
2913 For the format of SAFE-LIST, see `org-babel-safe-header-args'."
2915 (keywordp (car pair
))
2916 (stringp (cdr pair
))
2918 (memq (car pair
) safe-list
)
2919 (let ((entry (assq (car pair
) safe-list
)))
2922 (cond ((functionp (cdr entry
))
2923 (funcall (cdr entry
) (cdr pair
)))
2924 ((listp (cdr entry
))
2925 (member (cdr pair
) (cdr entry
)))
2928 (defun org-babel-generate-file-param (src-name params
)
2929 "Calculate the filename for source block results.
2931 The directory is calculated from the :output-dir property of the
2932 source block; if not specified, use the current directory.
2934 If the source block has a #+NAME and the :file parameter does not
2935 contain any period characters, then the :file parameter is
2936 treated as an extension, and the output file name is the
2937 concatenation of the directory (as calculated above), the block
2938 name, a period, and the parameter value as a file extension.
2939 Otherwise, the :file parameter is treated as a full file name,
2940 and the output file name is the directory (as calculated above)
2941 plus the parameter value."
2942 (let* ((file-cons (assq :file params
))
2943 (file-ext-cons (assq :file-ext params
))
2944 (file-ext (cdr-safe file-ext-cons
))
2945 (dir (cdr-safe (assq :output-dir params
)))
2947 ;; create the output-dir if it does not exist
2949 (make-directory dir t
))
2951 ;; :file given; add :output-dir if given
2953 (setcdr file-cons
(concat (file-name-as-directory dir
) (cdr file-cons
))))
2954 ;; :file not given; compute from name and :file-ext if possible
2955 (when (and src-name file-ext
)
2957 (setq fname
(concat (file-name-as-directory (or dir
""))
2958 src-name
"." file-ext
))
2959 (setq fname
(concat src-name
"." file-ext
)))
2960 (setq params
(cons (cons :file fname
) params
))))
2963 ;;; Used by backends: R, Maxima, Octave.
2964 (defun org-babel-graphical-output-file (params)
2965 "File where a babel block should send graphical output, per PARAMS."
2966 (unless (assq :file params
)
2967 (if (assq :file-ext params
)
2968 (user-error ":file-ext given but no :file generated; did you forget to give a block a #+NAME?")
2969 (user-error "No :file header argument given; cannot create graphical result.")))
2970 (and (member "graphics" (cdr (assq :result-params params
)))
2971 (cdr (assq :file params
))))
2976 ;; generated-autoload-file: "org-loaddefs.el"
2979 ;;; ob-core.el ends here