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"
53 (&optional context code edit-buffer-name quietp
))
54 (declare-function org-edit-src-exit
"org-src" (&optional context
))
55 (declare-function org-open-at-point
"org" (&optional in-emacs reference-buffer
))
56 (declare-function org-save-outline-visibility
"org-macs" (use-markers &rest body
))
57 (declare-function org-outline-overlay-data
"org" (&optional use-markers
))
58 (declare-function org-set-outline-overlay-data
"org" (data))
59 (declare-function org-narrow-to-subtree
"org" ())
60 (declare-function org-split-string
"org" (string &optional separators
))
61 (declare-function org-entry-get
"org"
62 (pom property
&optional inherit literal-nil
))
63 (declare-function org-make-options-regexp
"org" (kwds &optional extra
))
64 (declare-function org-do-remove-indentation
"org" (&optional n
))
65 (declare-function org-next-block
"org" (arg &optional backward block-regexp
))
66 (declare-function org-previous-block
"org" (arg &optional block-regexp
))
67 (declare-function org-show-context
"org" (&optional key
))
68 (declare-function org-at-table-p
"org" (&optional table-type
))
69 (declare-function org-cycle
"org" (&optional arg
))
70 (declare-function org-uniquify
"org" (list))
71 (declare-function org-current-level
"org" ())
72 (declare-function org-table-import
"org-table" (file arg
))
73 (declare-function org-add-hook
"org-compat"
74 (hook function
&optional append local
))
75 (declare-function org-table-align
"org-table" ())
76 (declare-function org-table-end
"org-table" (&optional table-type
))
77 (declare-function orgtbl-to-generic
"org-table" (table params
))
78 (declare-function orgtbl-to-orgtbl
"org-table" (table params
))
79 (declare-function org-babel-tangle-comment-links
"ob-tangle" (&optional info
))
80 (declare-function org-babel-lob-get-info
"ob-lob" nil
)
81 (declare-function org-babel-ref-split-args
"ob-ref" (arg-string))
82 (declare-function org-babel-ref-parse
"ob-ref" (assignment))
83 (declare-function org-babel-ref-resolve
"ob-ref" (ref))
84 (declare-function org-babel-ref-goto-headline-id
"ob-ref" (id))
85 (declare-function org-babel-ref-headline-body
"ob-ref" ())
86 (declare-function org-babel-lob-execute-maybe
"ob-lob" ())
87 (declare-function org-number-sequence
"org-compat" (from &optional to inc
))
88 (declare-function org-at-item-p
"org-list" ())
89 (declare-function org-list-parse-list
"org-list" (&optional delete
))
90 (declare-function org-list-to-generic
"org-list" (LIST PARAMS
))
91 (declare-function org-list-struct
"org-list" ())
92 (declare-function org-list-prevs-alist
"org-list" (struct))
93 (declare-function org-list-get-list-end
"org-list" (item struct prevs
))
94 (declare-function org-remove-if
"org" (predicate seq
))
95 (declare-function org-completing-read
"org" (&rest args
))
96 (declare-function org-escape-code-in-region
"org-src" (beg end
))
97 (declare-function org-unescape-code-in-string
"org-src" (s))
98 (declare-function org-table-to-lisp
"org-table" (&optional txt
))
99 (declare-function org-reverse-string
"org" (string))
100 (declare-function org-element-context
"org-element" (&optional ELEMENT
))
101 (declare-function org-every
"org" (pred seq
))
103 (defgroup org-babel nil
104 "Code block evaluation and management in `org-mode' documents."
108 (defcustom org-confirm-babel-evaluate t
109 "Confirm before evaluation.
110 Require confirmation before interactively evaluating code
111 blocks in Org-mode buffers. The default value of this variable
112 is t, meaning confirmation is required for any code block
113 evaluation. This variable can be set to nil to inhibit any
114 future confirmation requests. This variable can also be set to a
115 function which takes two arguments the language of the code block
116 and the body of the code block. Such a function should then
117 return a non-nil value if the user should be prompted for
118 execution or nil if no prompt is required.
120 Warning: Disabling confirmation may result in accidental
121 evaluation of potentially harmful code. It may be advisable
122 remove code block execution from C-c C-c as further protection
123 against accidental code block evaluation. The
124 `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
125 remove code block execution from the C-c C-c keybinding."
128 :type
'(choice boolean function
))
129 ;; don't allow this variable to be changed through file settings
130 (put 'org-confirm-babel-evaluate
'safe-local-variable
(lambda (x) (eq x t
)))
132 (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
133 "Remove code block evaluation from the C-c C-c key binding."
138 (defcustom org-babel-results-keyword
"RESULTS"
139 "Keyword used to name results generated by code blocks.
140 Should be either RESULTS or NAME however any capitalization may
144 :package-version
'(Org .
"8.0")
147 (defcustom org-babel-noweb-wrap-start
"<<"
148 "String used to begin a noweb reference in a code block.
149 See also `org-babel-noweb-wrap-end'."
153 (defcustom org-babel-noweb-wrap-end
">>"
154 "String used to end a noweb reference in a code block.
155 See also `org-babel-noweb-wrap-start'."
159 (defcustom org-babel-inline-result-wrap
"=%s="
160 "Format string used to wrap inline results.
161 This string must include a \"%s\" which will be replaced by the results."
164 (put 'org-babel-inline-result-wrap
168 (string-match-p "%s" value
))))
170 (defun org-babel-noweb-wrap (&optional regexp
)
171 (concat org-babel-noweb-wrap-start
172 (or regexp
"\\([^ \t\n].+?[^ \t]\\|[^ \t\n]\\)")
173 org-babel-noweb-wrap-end
))
175 (defvar org-babel-src-name-regexp
176 "^[ \t]*#\\+name:[ \t]*"
177 "Regular expression used to match a source name line.")
179 (defvar org-babel-multi-line-header-regexp
180 "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
181 "Regular expression used to match multi-line header arguments.")
183 (defvar org-babel-src-name-w-name-regexp
184 (concat org-babel-src-name-regexp
186 org-babel-multi-line-header-regexp
188 "\\([^ ()\f\t\n\r\v]+\\)")
189 "Regular expression matching source name lines with a name.")
191 (defvar org-babel-src-block-regexp
193 ;; (1) indentation (2) lang
194 "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
196 "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
197 ;; (4) header arguments
200 "\\([^\000]*?\n\\)??[ \t]*#\\+end_src")
201 "Regexp used to identify code blocks.")
203 (defvar org-babel-inline-src-block-regexp
205 ;; (1) replacement target (2) lang
206 "\\(?:^\\|[^-[:alnum:]]\\)\\(src_\\([^ \f\t\n\r\v]+\\)"
207 ;; (3,4) (unused, headers)
208 "\\(\\|\\[\\(.*?\\)\\]\\)"
210 "{\\([^\f\n\r\v]+?\\)}\\)")
211 "Regexp used to identify inline src-blocks.")
213 (defun org-babel-get-header (params key
&optional others
)
214 "Select only header argument of type KEY from a list.
215 Optional argument OTHERS indicates that only the header that do
216 not match KEY should be returned."
219 (lambda (p) (when (funcall (if others
#'not
#'identity
) (eq (car p
) key
)) p
))
222 (defun org-babel-get-inline-src-block-matches ()
223 "Set match data if within body of an inline source block.
224 Returns non-nil if match-data set"
225 (let ((src-at-0-p (save-excursion
226 (beginning-of-line 1)
227 (string= "src" (thing-at-point 'word
))))
228 (first-line-p (= (line-beginning-position) (point-min)))
230 (let ((search-for (cond ((and src-at-0-p first-line-p
"src_"))
231 (first-line-p "[[:punct:] \t]src_")
232 (t "[[:punct:] \f\t\n\r\v]src_")))
233 (lower-limit (if first-line-p
235 (- (point-at-bol) 1))))
237 (when (or (and src-at-0-p
(bobp))
238 (and (re-search-forward "}" (point-at-eol) t
)
239 (re-search-backward search-for lower-limit t
)
241 (when (looking-at org-babel-inline-src-block-regexp
)
244 (defvar org-babel-inline-lob-one-liner-regexp
)
245 (defun org-babel-get-lob-one-liner-matches ()
246 "Set match data if on line of an lob one liner.
247 Returns non-nil if match-data set"
249 (unless (= (point) (point-at-bol)) ;; move before inline block
250 (re-search-backward "[ \f\t\n\r\v]" nil t
))
251 (if (looking-at org-babel-inline-lob-one-liner-regexp
)
255 (defun org-babel-get-src-block-info (&optional light
)
256 "Get information on the current source block.
258 Optional argument LIGHT does not resolve remote variable
259 references; a process which could likely result in the execution
260 of other code blocks.
263 (language body header-arguments-alist switches name indent block-head)."
264 (let ((case-fold-search t
) head info name indent
)
266 (if (setq head
(org-babel-where-is-src-block-head))
269 (setq info
(org-babel-parse-src-block-match))
270 (setq indent
(car (last info
)))
271 (setq info
(butlast info
))
272 (while (and (forward-line -
1)
273 (looking-at org-babel-multi-line-header-regexp
))
275 (org-babel-merge-params
277 (org-babel-parse-header-arguments (match-string 1)))))
278 (when (looking-at org-babel-src-name-w-name-regexp
)
279 (setq name
(org-no-properties (match-string 3)))))
280 ;; inline source block
281 (when (org-babel-get-inline-src-block-matches)
282 (setq head
(match-beginning 0))
283 (setq info
(org-babel-parse-inline-src-block-match))))
284 ;; resolve variable references and add summary parameters
285 (when (and info
(not light
))
286 (setf (nth 2 info
) (org-babel-process-params (nth 2 info
))))
288 (setf (nth 2 info
) (org-babel-generate-file-param name
(nth 2 info
))))
289 (when info
(append info
(list name indent head
)))))
291 (defvar org-babel-exp-reference-buffer nil
292 "Buffer containing original contents of the exported buffer.
293 This is used by Babel to resolve references in source blocks.
294 Its value is dynamically bound during export.")
296 (defmacro org-babel-check-confirm-evaluate
(info &rest body
)
297 "Evaluate BODY with special execution confirmation variables set.
299 Specifically; NOEVAL will indicate if evaluation is allowed,
300 QUERY will indicate if a user query is required, CODE-BLOCK will
301 hold the language of the code block, and BLOCK-NAME will hold the
302 name of the code block."
303 (declare (indent defun
))
305 (lang block-body headers name head eval eval-no export eval-no-export
)
306 `(let* ((,lang
(nth 0 ,info
))
307 (,block-body
(nth 1 ,info
))
308 (,headers
(nth 2 ,info
))
309 (,name
(nth 4 ,info
))
310 (,head
(nth 6 ,info
))
311 (,eval
(or (cdr (assoc :eval
,headers
))
312 (when (assoc :noeval
,headers
) "no")))
313 (,eval-no
(or (equal ,eval
"no")
314 (equal ,eval
"never")))
315 (,export org-babel-exp-reference-buffer
)
316 (,eval-no-export
(and ,export
(or (equal ,eval
"no-export")
317 (equal ,eval
"never-export"))))
318 (noeval (or ,eval-no
,eval-no-export
))
319 (query (or (equal ,eval
"query")
320 (and ,export
(equal ,eval
"query-export"))
321 (if (functionp org-confirm-babel-evaluate
)
324 (funcall org-confirm-babel-evaluate
326 org-confirm-babel-evaluate
)))
327 (code-block (if ,info
(format " %s " ,lang
) " "))
328 (block-name (if ,name
(format " (%s) " ,name
) " ")))
331 (defsubst org-babel-check-evaluate
(info)
332 "Check if code block INFO should be evaluated.
333 Do not query the user."
334 (org-babel-check-confirm-evaluate info
336 (message (format "Evaluation of this%scode-block%sis disabled."
337 code-block block-name
))))))
339 ;; dynamically scoped for asynchronous export
340 (defvar org-babel-confirm-evaluate-answer-no
)
342 (defsubst org-babel-confirm-evaluate
(info)
343 "Confirm evaluation of the code block INFO.
345 If the variable `org-babel-confirm-evaluate-answer-no' is bound
346 to a non-nil value, auto-answer with \"no\".
348 This query can also be suppressed by setting the value of
349 `org-confirm-babel-evaluate' to nil, in which case all future
350 interactive code block evaluations will proceed without any
351 confirmation from the user.
353 Note disabling confirmation may result in accidental evaluation
354 of potentially harmful code."
355 (org-babel-check-confirm-evaluate info
358 (and (not (org-bound-and-true-p
359 org-babel-confirm-evaluate-answer-no
))
361 (format "Evaluate this%scode block%son your system? "
362 code-block block-name
)))
363 (message (format "Evaluation of this%scode-block%sis aborted."
364 code-block block-name
)))))))
367 (defun org-babel-execute-safely-maybe ()
368 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
369 (org-babel-execute-maybe)))
371 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-execute-safely-maybe
)
374 (defun org-babel-execute-maybe ()
376 (or (org-babel-execute-src-block-maybe)
377 (org-babel-lob-execute-maybe)))
379 (defmacro org-babel-when-in-src-block
(&rest body
)
380 "Execute BODY if point is in a source block and return t.
382 Otherwise do nothing and return nil."
383 `(if (or (org-babel-where-is-src-block-head)
384 (org-babel-get-inline-src-block-matches))
390 (defun org-babel-execute-src-block-maybe ()
391 "Conditionally execute a source block.
392 Detect if this is context for a Babel src-block and if so
393 then run `org-babel-execute-src-block'."
395 (org-babel-when-in-src-block
396 (org-babel-eval-wipe-error-buffer)
397 (org-babel-execute-src-block current-prefix-arg
)))
400 (defun org-babel-view-src-block-info ()
401 "Display information on the current source block.
402 This includes header arguments, language and name, and is largely
403 a window into the `org-babel-get-src-block-info' function."
405 (let ((info (org-babel-get-src-block-info 'light
))
406 (full (lambda (it) (> (length it
) 0)))
407 (printf (lambda (fmt &rest args
) (princ (apply #'format fmt args
)))))
409 (with-help-window (help-buffer)
410 (let ((name (nth 4 info
))
412 (switches (nth 3 info
))
413 (header-args (nth 2 info
)))
414 (when name
(funcall printf
"Name: %s\n" name
))
415 (when lang
(funcall printf
"Lang: %s\n" lang
))
416 (when (funcall full switches
) (funcall printf
"Switches: %s\n" switches
))
417 (funcall printf
"Header Arguments:\n")
418 (dolist (pair (sort header-args
419 (lambda (a b
) (string< (symbol-name (car a
))
420 (symbol-name (car b
))))))
421 (when (funcall full
(cdr pair
))
422 (funcall printf
"\t%S%s\t%s\n"
424 (if (> (length (format "%S" (car pair
))) 7) "" "\t")
428 (defun org-babel-expand-src-block-maybe ()
429 "Conditionally expand a source block.
430 Detect if this is context for a org-babel src-block and if so
431 then run `org-babel-expand-src-block'."
433 (org-babel-when-in-src-block
434 (org-babel-expand-src-block current-prefix-arg
)))
437 (defun org-babel-load-in-session-maybe ()
438 "Conditionally load a source block in a session.
439 Detect if this is context for a org-babel src-block and if so
440 then run `org-babel-load-in-session'."
442 (org-babel-when-in-src-block
443 (org-babel-load-in-session current-prefix-arg
)))
445 (add-hook 'org-metaup-hook
'org-babel-load-in-session-maybe
)
448 (defun org-babel-pop-to-session-maybe ()
449 "Conditionally pop to a session.
450 Detect if this is context for a org-babel src-block and if so
451 then run `org-babel-switch-to-session'."
453 (org-babel-when-in-src-block
454 (org-babel-switch-to-session current-prefix-arg
)))
456 (add-hook 'org-metadown-hook
'org-babel-pop-to-session-maybe
)
458 (defconst org-babel-common-header-args-w-values
459 '((cache .
((no yes
)))
461 (colnames .
((nil no yes
)))
462 (comments .
((no link yes org both noweb
)))
464 (eval .
((never query
)))
465 (exports .
((code results both none
)))
469 (hlines .
((no yes
)))
470 (mkdirp .
((yes no
)))
473 (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
)
780 (concat "*Org-Babel Preview " (buffer-name) "[ " lang
" ]*"))
783 (defun org-babel-edit-distance (s1 s2
)
784 "Return the edit (levenshtein) distance between strings S1 S2."
785 (let* ((l1 (length s1
))
787 (dist (vconcat (mapcar (lambda (_) (make-vector (1+ l2
) nil
))
788 (number-sequence 1 (1+ l1
)))))
789 (in (lambda (i j
) (aref (aref dist i
) j
))))
790 (setf (aref (aref dist
0) 0) 0)
791 (dolist (j (number-sequence 1 l2
))
792 (setf (aref (aref dist
0) j
) j
))
793 (dolist (i (number-sequence 1 l1
))
794 (setf (aref (aref dist i
) 0) i
)
795 (dolist (j (number-sequence 1 l2
))
796 (setf (aref (aref dist i
) j
)
798 (1+ (funcall in
(1- i
) j
))
799 (1+ (funcall in i
(1- j
)))
800 (+ (if (equal (aref s1
(1- i
)) (aref s2
(1- j
))) 0 1)
801 (funcall in
(1- i
) (1- j
)))))))
804 (defun org-babel-combine-header-arg-lists (original &rest others
)
805 "Combine a number of lists of header argument names and arguments."
806 (let ((results (copy-sequence original
)))
807 (dolist (new-list others
)
808 (dolist (arg-pair new-list
)
809 (let ((header (car arg-pair
))
810 (args (cdr arg-pair
)))
812 (cons arg-pair
(org-remove-if
813 (lambda (pair) (equal header
(car pair
)))
818 (defun org-babel-check-src-block ()
819 "Check for misspelled header arguments in the current code block."
821 ;; TODO: report malformed code block
822 ;; TODO: report incompatible combinations of header arguments
823 ;; TODO: report uninitialized variables
824 (let ((too-close 2) ;; <- control closeness to report potential match
825 (names (mapcar #'symbol-name org-babel-header-arg-names
)))
826 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg
)) 1))
827 (and (org-babel-where-is-src-block-head)
828 (org-babel-parse-header-arguments
830 (match-string 4))))))
832 (when (and (not (string= header name
))
833 (<= (org-babel-edit-distance header name
) too-close
)
834 (not (member header names
)))
835 (error "Supplied header \"%S\" is suspiciously close to \"%S\""
837 (message "No suspicious header arguments found.")))
840 (defun org-babel-insert-header-arg (&optional header-arg value
)
841 "Insert a header argument selecting from lists of common args and values."
843 (let* ((info (org-babel-get-src-block-info 'light
))
846 (lang-headers (intern (concat "org-babel-header-args:" lang
)))
847 (headers (org-babel-combine-header-arg-lists
848 org-babel-common-header-args-w-values
849 (when (boundp lang-headers
) (eval lang-headers
))))
850 (header-arg (or header-arg
851 (org-icompleting-read
854 (lambda (header-spec) (symbol-name (car header-spec
)))
856 (vals (cdr (assoc (intern header-arg
) headers
)))
860 (read-from-minibuffer "value: "))
864 (let ((arg (org-icompleting-read
867 (mapcar #'symbol-name group
)))))
868 (if (and arg
(not (string= "default" arg
)))
874 (goto-char (point-at-eol))
875 (unless (= (char-before (point)) ?\
) (insert " "))
876 (insert ":" header-arg
) (when value
(insert " " value
)))))
878 ;; Add support for completing-read insertion of header arguments after ":"
879 (defun org-babel-header-arg-expand ()
880 "Call `org-babel-enter-header-arg-w-completion' in appropriate contexts."
881 (when (and (equal (char-before) ?\
:) (org-babel-where-is-src-block-head))
882 (org-babel-enter-header-arg-w-completion (match-string 2))))
884 (defun org-babel-enter-header-arg-w-completion (&optional lang
)
885 "Insert header argument appropriate for LANG with completion."
886 (let* ((lang-headers-var (intern (concat "org-babel-header-args:" lang
)))
887 (lang-headers (when (boundp lang-headers-var
) (eval lang-headers-var
)))
888 (headers-w-values (org-babel-combine-header-arg-lists
889 org-babel-common-header-args-w-values lang-headers
))
890 (headers (mapcar #'symbol-name
(mapcar #'car headers-w-values
)))
891 (header (org-completing-read "Header Arg: " headers
))
892 (args (cdr (assoc (intern header
) headers-w-values
)))
893 (arg (when (and args
(listp args
))
895 (format "%s: " header
)
896 (mapcar #'symbol-name
(apply #'append args
))))))
897 (insert (concat header
" " (or arg
"")))
900 (add-hook 'org-tab-first-hook
'org-babel-header-arg-expand
)
903 (defun org-babel-load-in-session (&optional arg info
)
904 "Load the body of the current source-code block.
905 Evaluate the header arguments for the source block before
906 entering the session. After loading the body this pops open the
909 (let* ((info (or info
(org-babel-get-src-block-info)))
911 (params (nth 2 info
))
913 (user-error "No src code block at point")
915 (if (org-babel-noweb-p params
:eval
)
916 (org-babel-expand-noweb-references info
)
918 (session (cdr (assoc :session params
)))
919 (dir (cdr (assoc :dir params
)))
921 (or (and dir
(file-name-as-directory dir
)) default-directory
))
922 (cmd (intern (concat "org-babel-load-session:" lang
))))
923 (unless (fboundp cmd
)
924 (error "No org-babel-load-session function for %s!" lang
))
925 (pop-to-buffer (funcall cmd session body params
))
929 (defun org-babel-initiate-session (&optional arg info
)
930 "Initiate session for current code block.
931 If called with a prefix argument then resolve any variable
932 references in the header arguments and assign these variables in
933 the session. Copy the body of the code block to the kill ring."
935 (let* ((info (or info
(org-babel-get-src-block-info (not arg
))))
938 (params (nth 2 info
))
939 (session (cdr (assoc :session params
)))
940 (dir (cdr (assoc :dir params
)))
942 (or (and dir
(file-name-as-directory dir
)) default-directory
))
943 (init-cmd (intern (format "org-babel-%s-initiate-session" lang
)))
944 (prep-cmd (intern (concat "org-babel-prep-session:" lang
))))
945 (if (and (stringp session
) (string= session
"none"))
946 (error "This block is not using a session!"))
947 (unless (fboundp init-cmd
)
948 (error "No org-babel-initiate-session function for %s!" lang
))
949 (with-temp-buffer (insert (org-babel-trim body
))
950 (copy-region-as-kill (point-min) (point-max)))
952 (unless (fboundp prep-cmd
)
953 (error "No org-babel-prep-session function for %s!" lang
))
954 (funcall prep-cmd session params
))
955 (funcall init-cmd session params
)))
958 (defun org-babel-switch-to-session (&optional arg info
)
959 "Switch to the session of the current code block.
960 Uses `org-babel-initiate-session' to start the session. If called
961 with a prefix argument then this is passed on to
962 `org-babel-initiate-session'."
964 (pop-to-buffer (org-babel-initiate-session arg info
))
967 (defalias 'org-babel-pop-to-session
'org-babel-switch-to-session
)
969 (defvar org-src-window-setup
)
972 (defun org-babel-switch-to-session-with-code (&optional arg info
)
973 "Switch to code buffer and display session."
977 (let ((other-window-buffer (window-buffer (next-window))))
978 (set-window-buffer (next-window) (current-buffer))
979 (set-window-buffer (selected-window) other-window-buffer
))
981 (info (org-babel-get-src-block-info))
982 (org-src-window-setup 'reorganize-frame
))
984 (org-babel-switch-to-session arg info
))
986 (funcall swap-windows
)))
989 (defmacro org-babel-do-in-edit-buffer
(&rest body
)
990 "Evaluate BODY in edit buffer if there is a code block at point.
991 Return t if a code block was found at point, nil otherwise."
992 `(let ((org-src-window-setup 'switch-invisibly
))
993 (when (and (org-babel-where-is-src-block-head)
995 (unwind-protect (progn ,@body
)
996 (if (org-bound-and-true-p org-edit-src-from-org-mode
)
997 (org-edit-src-exit)))
999 (def-edebug-spec org-babel-do-in-edit-buffer
(body))
1001 (defun org-babel-do-key-sequence-in-edit-buffer (key)
1002 "Read key sequence and execute the command in edit buffer.
1003 Enter a key sequence to be executed in the language major-mode
1004 edit buffer. For example, TAB will alter the contents of the
1005 Org-mode code block according to the effect of TAB in the
1006 language major-mode buffer. For languages that support
1007 interactive sessions, this can be used to send code from the Org
1008 buffer to the session for evaluation using the native major-mode
1009 evaluation mechanisms."
1010 (interactive "kEnter key-sequence to execute in edit buffer: ")
1011 (org-babel-do-in-edit-buffer
1013 (key-binding (or key
(read-key-sequence nil
))))))
1015 (defvar org-bracket-link-regexp
)
1017 (defun org-babel-active-location-p ()
1018 (memq (car (save-match-data (org-element-context)))
1019 '(babel-call inline-babel-call inline-src-block src-block
)))
1022 (defun org-babel-open-src-block-result (&optional re-run
)
1023 "If `point' is on a src block then open the results of the
1024 source code block, otherwise return nil. With optional prefix
1025 argument RE-RUN the source-code block is evaluated even if
1026 results already exist."
1028 (let ((info (org-babel-get-src-block-info 'light
)))
1031 ;; go to the results, if there aren't any then run the block
1032 (goto-char (or (and (not re-run
) (org-babel-where-is-src-block-result))
1033 (progn (org-babel-execute-src-block)
1034 (org-babel-where-is-src-block-result))))
1036 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
1038 (if (looking-at org-bracket-link-regexp
)
1041 (let ((r (org-babel-format-result
1042 (org-babel-read-result) (cdr (assoc :sep
(nth 2 info
))))))
1043 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
1044 (delete-region (point-min) (point-max))
1049 (defmacro org-babel-map-src-blocks
(file &rest body
)
1050 "Evaluate BODY forms on each source-block in FILE.
1051 If FILE is nil evaluate BODY forms on source blocks in current
1052 buffer. During evaluation of BODY the following local variables
1053 are set relative to the currently matched code block.
1055 full-block ------- string holding the entirety of the code block
1056 beg-block -------- point at the beginning of the code block
1057 end-block -------- point at the end of the matched code block
1058 lang ------------- string holding the language of the code block
1059 beg-lang --------- point at the beginning of the lang
1060 end-lang --------- point at the end of the lang
1061 switches --------- string holding the switches
1062 beg-switches ----- point at the beginning of the switches
1063 end-switches ----- point at the end of the switches
1064 header-args ------ string holding the header-args
1065 beg-header-args -- point at the beginning of the header-args
1066 end-header-args -- point at the end of the header-args
1067 body ------------- string holding the body of the code block
1068 beg-body --------- point at the beginning of the body
1069 end-body --------- point at the end of the body"
1070 (declare (indent 1))
1071 (let ((tempvar (make-symbol "file")))
1072 `(let* ((,tempvar
,file
)
1073 (visited-p (or (null ,tempvar
)
1074 (get-file-buffer (expand-file-name ,tempvar
))))
1075 (point (point)) to-be-removed
)
1076 (save-window-excursion
1077 (when ,tempvar
(find-file ,tempvar
))
1078 (setq to-be-removed
(current-buffer))
1079 (goto-char (point-min))
1080 (while (re-search-forward org-babel-src-block-regexp nil t
)
1081 (when (org-babel-active-location-p)
1082 (goto-char (match-beginning 0))
1083 (let ((full-block (match-string 0))
1084 (beg-block (match-beginning 0))
1085 (end-block (match-end 0))
1086 (lang (match-string 2))
1087 (beg-lang (match-beginning 2))
1088 (end-lang (match-end 2))
1089 (switches (match-string 3))
1090 (beg-switches (match-beginning 3))
1091 (end-switches (match-end 3))
1092 (header-args (match-string 4))
1093 (beg-header-args (match-beginning 4))
1094 (end-header-args (match-end 4))
1095 (body (match-string 5))
1096 (beg-body (match-beginning 5))
1097 (end-body (match-end 5)))
1099 (goto-char end-block
)))))
1100 (unless visited-p
(kill-buffer to-be-removed
))
1101 (goto-char point
))))
1102 (def-edebug-spec org-babel-map-src-blocks
(form body
))
1105 (defmacro org-babel-map-inline-src-blocks
(file &rest body
)
1106 "Evaluate BODY forms on each inline source-block in FILE.
1107 If FILE is nil evaluate BODY forms on source blocks in current
1109 (declare (indent 1))
1110 (let ((tempvar (make-symbol "file")))
1111 `(let* ((,tempvar
,file
)
1112 (visited-p (or (null ,tempvar
)
1113 (get-file-buffer (expand-file-name ,tempvar
))))
1114 (point (point)) to-be-removed
)
1115 (save-window-excursion
1116 (when ,tempvar
(find-file ,tempvar
))
1117 (setq to-be-removed
(current-buffer))
1118 (goto-char (point-min))
1119 (while (re-search-forward org-babel-inline-src-block-regexp nil t
)
1120 (when (org-babel-active-location-p)
1121 (goto-char (match-beginning 1))
1122 (save-match-data ,@body
))
1123 (goto-char (match-end 0))))
1124 (unless visited-p
(kill-buffer to-be-removed
))
1125 (goto-char point
))))
1126 (def-edebug-spec org-babel-map-inline-src-blocks
(form body
))
1128 (defvar org-babel-lob-one-liner-regexp
)
1131 (defmacro org-babel-map-call-lines
(file &rest body
)
1132 "Evaluate BODY forms on each call line in FILE.
1133 If FILE is nil evaluate BODY forms on source blocks in current
1135 (declare (indent 1))
1136 (let ((tempvar (make-symbol "file")))
1137 `(let* ((,tempvar
,file
)
1138 (visited-p (or (null ,tempvar
)
1139 (get-file-buffer (expand-file-name ,tempvar
))))
1140 (point (point)) to-be-removed
)
1141 (save-window-excursion
1142 (when ,tempvar
(find-file ,tempvar
))
1143 (setq to-be-removed
(current-buffer))
1144 (goto-char (point-min))
1145 (while (re-search-forward org-babel-lob-one-liner-regexp nil t
)
1146 (when (org-babel-active-location-p)
1147 (goto-char (match-beginning 1))
1148 (save-match-data ,@body
))
1149 (goto-char (match-end 0))))
1150 (unless visited-p
(kill-buffer to-be-removed
))
1151 (goto-char point
))))
1152 (def-edebug-spec org-babel-map-call-lines
(form body
))
1155 (defmacro org-babel-map-executables
(file &rest body
)
1156 (declare (indent 1))
1157 (let ((tempvar (make-symbol "file"))
1158 (rx (make-symbol "rx")))
1159 `(let* ((,tempvar
,file
)
1160 (,rx
(concat "\\(" org-babel-src-block-regexp
1161 "\\|" org-babel-inline-src-block-regexp
1162 "\\|" org-babel-lob-one-liner-regexp
"\\)"))
1163 (visited-p (or (null ,tempvar
)
1164 (get-file-buffer (expand-file-name ,tempvar
))))
1165 (point (point)) to-be-removed
)
1166 (save-window-excursion
1167 (when ,tempvar
(find-file ,tempvar
))
1168 (setq to-be-removed
(current-buffer))
1169 (goto-char (point-min))
1170 (while (re-search-forward ,rx nil t
)
1171 (when (org-babel-active-location-p)
1172 (goto-char (match-beginning 1))
1173 (when (looking-at org-babel-inline-src-block-regexp
)
1175 (save-match-data ,@body
))
1176 (goto-char (match-end 0))))
1177 (unless visited-p
(kill-buffer to-be-removed
))
1178 (goto-char point
))))
1179 (def-edebug-spec org-babel-map-executables
(form body
))
1182 (defun org-babel-execute-buffer (&optional arg
)
1183 "Execute source code blocks in a buffer.
1184 Call `org-babel-execute-src-block' on every source block in
1185 the current buffer."
1187 (org-babel-eval-wipe-error-buffer)
1188 (org-save-outline-visibility t
1189 (org-babel-map-executables nil
1190 (if (looking-at org-babel-lob-one-liner-regexp
)
1191 (org-babel-lob-execute-maybe)
1192 (org-babel-execute-src-block arg
)))))
1195 (defun org-babel-execute-subtree (&optional arg
)
1196 "Execute source code blocks in a subtree.
1197 Call `org-babel-execute-src-block' on every source block in
1198 the current subtree."
1202 (org-narrow-to-subtree)
1203 (org-babel-execute-buffer arg
)
1207 (defun org-babel-sha1-hash (&optional info
)
1208 "Generate an sha1 hash based on the value of info."
1210 (let ((print-level nil
)
1211 (info (or info
(org-babel-get-src-block-info))))
1213 (sort (copy-sequence (nth 2 info
))
1214 (lambda (a b
) (string< (car a
) (car b
)))))
1215 (let* ((rm (lambda (lst)
1216 (dolist (p '("replace" "silent" "none"
1217 "append" "prepend"))
1218 (setq lst
(remove p lst
)))
1221 (let ((v (if (and (listp (cdr arg
)) (null (cddr arg
)))
1222 (copy-sequence (cdr arg
))
1224 (when (and v
(not (and (sequencep v
)
1228 ((and (listp v
) ; lists are sorted
1229 (member (car arg
) '(:result-params
)))
1230 (sort (funcall rm v
) #'string
<))
1231 ((and (stringp v
) ; strings are sorted
1232 (member (car arg
) '(:results
:exports
)))
1233 (mapconcat #'identity
(sort (funcall rm
(split-string v
))
1238 (params (nth 2 info
))
1239 (body (if (org-babel-noweb-p params
:eval
)
1240 (org-babel-expand-noweb-references info
) (nth 1 info
)))
1241 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
1242 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
1245 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
1246 (org-babel-expand-body:generic
1247 body params
(and (fboundp assignments-cmd
)
1248 (funcall assignments-cmd params
))))))
1249 (let* ((it (format "%s-%s"
1252 (delq nil
(mapcar (lambda (arg)
1253 (let ((normalized (funcall norm arg
)))
1255 (format "%S" normalized
))))
1259 (when (org-called-interactively-p 'interactive
) (message hash
))
1262 (defun org-babel-current-result-hash (&optional info
)
1263 "Return the current in-buffer hash."
1264 (org-babel-where-is-src-block-result nil info
)
1265 (org-no-properties (match-string 5)))
1267 (defun org-babel-set-current-result-hash (hash info
)
1268 "Set the current in-buffer hash to HASH."
1269 (org-babel-where-is-src-block-result nil info
)
1270 (save-excursion (goto-char (match-beginning 5))
1271 (mapc #'delete-overlay
(overlays-at (point)))
1272 (forward-char org-babel-hash-show
)
1273 (mapc #'delete-overlay
(overlays-at (point)))
1274 (replace-match hash nil nil nil
5)
1275 (goto-char (point-at-bol))
1276 (org-babel-hide-hash)))
1278 (defun org-babel-hide-hash ()
1279 "Hide the hash in the current results line.
1280 Only the initial `org-babel-hash-show' characters of the hash
1281 will remain visible."
1282 (add-to-invisibility-spec '(org-babel-hide-hash . t
))
1284 (when (and (re-search-forward org-babel-result-regexp nil t
)
1286 (let* ((start (match-beginning 5))
1287 (hide-start (+ org-babel-hash-show start
))
1289 (hash (match-string 5))
1291 (setq ov1
(make-overlay start hide-start
))
1292 (setq ov2
(make-overlay hide-start end
))
1293 (overlay-put ov2
'invisible
'org-babel-hide-hash
)
1294 (overlay-put ov1
'babel-hash hash
)))))
1296 (defun org-babel-hide-all-hashes ()
1297 "Hide the hash in the current buffer.
1298 Only the initial `org-babel-hash-show' characters of each hash
1299 will remain visible. This function should be called as part of
1300 the `org-mode-hook'."
1302 (while (and (not org-babel-hash-show-time
)
1303 (re-search-forward org-babel-result-regexp nil t
))
1304 (goto-char (match-beginning 0))
1305 (org-babel-hide-hash)
1306 (goto-char (match-end 0)))))
1307 (add-hook 'org-mode-hook
'org-babel-hide-all-hashes
)
1309 (defun org-babel-hash-at-point (&optional point
)
1310 "Return the value of the hash at POINT.
1311 The hash is also added as the last element of the kill ring.
1312 This can be called with C-c C-c."
1314 (let ((hash (car (delq nil
(mapcar
1315 (lambda (ol) (overlay-get ol
'babel-hash
))
1316 (overlays-at (or point
(point))))))))
1317 (when hash
(kill-new hash
) (message hash
))))
1318 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-hash-at-point
)
1320 (defun org-babel-result-hide-spec ()
1321 "Hide portions of results lines.
1322 Add `org-babel-hide-result' as an invisibility spec for hiding
1323 portions of results lines."
1324 (add-to-invisibility-spec '(org-babel-hide-result . t
)))
1325 (add-hook 'org-mode-hook
'org-babel-result-hide-spec
)
1327 (defvar org-babel-hide-result-overlays nil
1328 "Overlays hiding results.")
1330 (defun org-babel-result-hide-all ()
1331 "Fold all results in the current buffer."
1333 (org-babel-show-result-all)
1335 (while (re-search-forward org-babel-result-regexp nil t
)
1336 (save-excursion (goto-char (match-beginning 0))
1337 (org-babel-hide-result-toggle-maybe)))))
1339 (defun org-babel-show-result-all ()
1340 "Unfold all results in the current buffer."
1341 (mapc 'delete-overlay org-babel-hide-result-overlays
)
1342 (setq org-babel-hide-result-overlays nil
))
1345 (defun org-babel-hide-result-toggle-maybe ()
1346 "Toggle visibility of result at point."
1348 (let ((case-fold-search t
))
1350 (beginning-of-line 1)
1351 (looking-at org-babel-result-regexp
))
1352 (progn (org-babel-hide-result-toggle)
1353 t
) ;; to signal that we took action
1354 nil
))) ;; to signal that we did not
1356 (defun org-babel-hide-result-toggle (&optional force
)
1357 "Toggle the visibility of the current result."
1361 (if (re-search-forward org-babel-result-regexp nil t
)
1362 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
1364 (while (looking-at org-babel-multi-line-header-regexp
)
1366 (goto-char (- (org-babel-result-end) 1)) (point)))
1368 (if (memq t
(mapcar (lambda (overlay)
1369 (eq (overlay-get overlay
'invisible
)
1370 'org-babel-hide-result
))
1371 (overlays-at start
)))
1372 (if (or (not force
) (eq force
'off
))
1374 (when (member ov org-babel-hide-result-overlays
)
1375 (setq org-babel-hide-result-overlays
1376 (delq ov org-babel-hide-result-overlays
)))
1377 (when (eq (overlay-get ov
'invisible
)
1378 'org-babel-hide-result
)
1379 (delete-overlay ov
)))
1380 (overlays-at start
)))
1381 (setq ov
(make-overlay start end
))
1382 (overlay-put ov
'invisible
'org-babel-hide-result
)
1383 ;; make the block accessible to isearch
1385 ov
'isearch-open-invisible
1387 (when (member ov org-babel-hide-result-overlays
)
1388 (setq org-babel-hide-result-overlays
1389 (delq ov org-babel-hide-result-overlays
)))
1390 (when (eq (overlay-get ov
'invisible
)
1391 'org-babel-hide-result
)
1392 (delete-overlay ov
))))
1393 (push ov org-babel-hide-result-overlays
)))
1394 (error "Not looking at a result line"))))
1396 ;; org-tab-after-check-for-cycling-hook
1397 (add-hook 'org-tab-first-hook
'org-babel-hide-result-toggle-maybe
)
1398 ;; Remove overlays when changing major mode
1399 (add-hook 'org-mode-hook
1400 (lambda () (org-add-hook 'change-major-mode-hook
1401 'org-babel-show-result-all
'append
'local
)))
1403 (defvar org-file-properties
)
1404 (defun org-babel-params-from-properties (&optional lang
)
1405 "Retrieve parameters specified as properties.
1406 Return a list of association lists of source block params
1407 specified in the properties of the current outline entry."
1410 ;; DEPRECATED header arguments specified as separate property at
1411 ;; point of definition
1413 (org-babel-parse-multiple-vars
1416 (lambda (header-arg)
1417 (and (setq val
(org-entry-get (point) header-arg t
))
1418 (cons (intern (concat ":" header-arg
))
1419 (org-babel-read val
))))
1424 (org-babel-combine-header-arg-lists
1425 org-babel-common-header-args-w-values
1427 (setq sym
(intern (concat "org-babel-header-args:" lang
)))
1428 (and (boundp sym
) (eval sym
))))))))))
1429 ;; header arguments specified with the header-args property at
1431 (org-babel-parse-header-arguments
1432 (org-entry-get org-babel-current-src-block-location
1433 "header-args" 'inherit
))
1434 (when lang
;; language-specific header arguments at point of call
1435 (org-babel-parse-header-arguments
1436 (org-entry-get org-babel-current-src-block-location
1437 (concat "header-args:" lang
) 'inherit
))))))
1439 (defvar org-src-preserve-indentation
) ;; declare defcustom from org-src
1440 (defun org-babel-parse-src-block-match ()
1441 "Parse the results from a match of the `org-babel-src-block-regexp'."
1442 (let* ((block-indentation (length (match-string 1)))
1443 (lang (org-no-properties (match-string 2)))
1444 (lang-headers (intern (concat "org-babel-default-header-args:" lang
)))
1445 (switches (match-string 3))
1446 (body (org-no-properties
1447 (let* ((body (match-string 5))
1448 (sub-length (- (length body
) 1)))
1449 (if (and (> sub-length
0)
1450 (string= "\n" (substring body sub-length
)))
1451 (substring body
0 sub-length
)
1453 (preserve-indentation (or org-src-preserve-indentation
1455 (string-match "-i\\>" switches
)))))
1457 ;; get block body less properties, protective commas, and indentation
1460 (insert (org-unescape-code-in-string body
))
1461 (unless preserve-indentation
(org-do-remove-indentation))
1463 (apply #'org-babel-merge-params
1464 org-babel-default-header-args
1465 (when (boundp lang-headers
) (eval lang-headers
))
1467 (org-babel-params-from-properties lang
)
1468 (list (org-babel-parse-header-arguments
1469 (org-no-properties (or (match-string 4) ""))))))
1471 block-indentation
)))
1473 (defun org-babel-parse-inline-src-block-match ()
1474 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
1475 (let* ((lang (org-no-properties (match-string 2)))
1476 (lang-headers (intern (concat "org-babel-default-header-args:" lang
))))
1478 (org-unescape-code-in-string (org-no-properties (match-string 5)))
1479 (apply #'org-babel-merge-params
1480 org-babel-default-inline-header-args
1481 (if (boundp lang-headers
) (eval lang-headers
) nil
)
1483 (org-babel-params-from-properties lang
)
1484 (list (org-babel-parse-header-arguments
1485 (org-no-properties (or (match-string 4) ""))))))
1488 (defun org-babel-balanced-split (string alts
)
1489 "Split STRING on instances of ALTS.
1490 ALTS is a cons of two character options where each option may be
1491 either the numeric code of a single character or a list of
1492 character alternatives. For example to split on balanced
1493 instances of \"[ \t]:\" set ALTS to '((32 9) . 58)."
1494 (let* ((matches (lambda (ch spec
) (if (listp spec
) (member ch spec
) (equal spec ch
))))
1495 (matched (lambda (ch last
)
1497 (and (funcall matches ch
(cdr alts
))
1498 (funcall matches last
(car alts
)))
1499 (funcall matches ch alts
))))
1500 (balance 0) (last 0)
1502 (mapc (lambda (ch) ; split on [], (), "" balanced instances of [ \t]:
1503 (setq balance
(+ balance
1504 (cond ((or (equal 91 ch
) (equal 40 ch
)) 1)
1505 ((or (equal 93 ch
) (equal 41 ch
)) -
1)
1507 (when (and (equal 34 ch
) (not (equal 92 last
)))
1508 (setq quote
(not quote
)))
1509 (setq partial
(cons ch partial
))
1510 (when (and (= balance
0) (not quote
) (funcall matched ch last
))
1511 (setq lst
(cons (apply #'string
(nreverse
1518 (string-to-list string
))
1519 (nreverse (cons (apply #'string
(nreverse partial
)) lst
))))
1521 (defun org-babel-join-splits-near-ch (ch list
)
1522 "Join splits where \"=\" is on either end of the split."
1523 (let ((last= (lambda (str) (= ch
(aref str
(1- (length str
))))))
1524 (first= (lambda (str) (= ch
(aref str
0)))))
1526 (org-reduce (lambda (acc el
)
1527 (let ((head (car acc
)))
1528 (if (and head
(or (funcall last
= head
) (funcall first
= el
)))
1529 (cons (concat head el
) (cdr acc
))
1531 list
:initial-value nil
))))
1533 (defun org-babel-parse-header-arguments (arg-string)
1534 "Parse a string of header arguments returning an alist."
1535 (when (> (length arg-string
) 0)
1536 (org-babel-parse-multiple-vars
1541 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1543 (cons (intern (match-string 1 arg
))
1544 (org-babel-read (org-babel-chomp (match-string 2 arg
))))
1545 (cons (intern (org-babel-chomp arg
)) nil
)))
1546 (let ((raw (org-babel-balanced-split arg-string
'((32 9) .
58))))
1547 (cons (car raw
) (mapcar (lambda (r) (concat ":" r
)) (cdr raw
)))))))))
1549 (defun org-babel-parse-multiple-vars (header-arguments)
1550 "Expand multiple variable assignments behind a single :var keyword.
1552 This allows expression of multiple variables with one :var as
1555 #+PROPERTY: var foo=1, bar=2"
1557 (mapc (lambda (pair)
1558 (if (eq (car pair
) :var
)
1559 (mapcar (lambda (v) (push (cons :var
(org-babel-trim v
)) results
))
1560 (org-babel-join-splits-near-ch
1561 61 (org-babel-balanced-split (cdr pair
) 32)))
1562 (push pair results
)))
1564 (nreverse results
)))
1566 (defun org-babel-process-params (params)
1567 "Expand variables in PARAMS and add summary parameters."
1568 (let* ((processed-vars (mapcar (lambda (el)
1569 (if (consp (cdr el
))
1571 (org-babel-ref-parse (cdr el
))))
1572 (org-babel-get-header params
:var
)))
1573 (vars-and-names (if (and (assoc :colname-names params
)
1574 (assoc :rowname-names params
))
1575 (list processed-vars
)
1576 (org-babel-disassemble-tables
1578 (cdr (assoc :hlines params
))
1579 (cdr (assoc :colnames params
))
1580 (cdr (assoc :rownames params
)))))
1581 (raw-result (or (cdr (assoc :results params
)) ""))
1582 (result-params (append
1583 (split-string (if (stringp raw-result
)
1586 (cdr (assoc :result-params params
)))))
1588 (mapcar (lambda (var) (cons :var var
)) (car vars-and-names
))
1590 (cons :colname-names
(or (cdr (assoc :colname-names params
))
1591 (cadr vars-and-names
)))
1592 (cons :rowname-names
(or (cdr (assoc :rowname-names params
))
1593 (caddr vars-and-names
)))
1594 (cons :result-params result-params
)
1595 (cons :result-type
(cond ((member "output" result-params
) 'output
)
1596 ((member "value" result-params
) 'value
)
1598 (org-babel-get-header params
:var
'other
))))
1600 ;; row and column names
1601 (defun org-babel-del-hlines (table)
1602 "Remove all 'hlines from TABLE."
1603 (remq 'hline table
))
1605 (defun org-babel-get-colnames (table)
1606 "Return the column names of TABLE.
1607 Return a cons cell, the `car' of which contains the TABLE less
1608 colnames, and the `cdr' of which contains a list of the column
1610 (if (equal 'hline
(nth 1 table
))
1611 (cons (cddr table
) (car table
))
1612 (cons (cdr table
) (car table
))))
1614 (defun org-babel-get-rownames (table)
1615 "Return the row names of TABLE.
1616 Return a cons cell, the `car' of which contains the TABLE less
1617 rownames, and the `cdr' of which contains a list of the rownames.
1618 Note: this function removes any hlines in TABLE."
1619 (let* ((table (org-babel-del-hlines table
))
1620 (rownames (funcall (lambda ()
1626 (setq tp
(cdr tp
))))
1628 (cons table rownames
)))
1630 (defun org-babel-put-colnames (table colnames
)
1631 "Add COLNAMES to TABLE if they exist."
1632 (if colnames
(apply 'list colnames
'hline table
) table
))
1634 (defun org-babel-put-rownames (table rownames
)
1635 "Add ROWNAMES to TABLE if they exist."
1637 (mapcar (lambda (row)
1639 (cons (or (pop rownames
) "") row
)
1643 (defun org-babel-pick-name (names selector
)
1644 "Select one out of an alist of row or column names.
1645 SELECTOR can be either a list of names in which case those names
1646 will be returned directly, or an index into the list NAMES in
1647 which case the indexed names will be return."
1648 (if (listp selector
)
1651 (if (and selector
(symbolp selector
) (not (equal t selector
)))
1652 (cdr (assoc selector names
))
1653 (if (integerp selector
)
1654 (nth (- selector
1) names
)
1655 (cdr (car (last names
))))))))
1657 (defun org-babel-disassemble-tables (vars hlines colnames rownames
)
1658 "Parse tables for further processing.
1659 Process the variables in VARS according to the HLINES,
1660 ROWNAMES and COLNAMES header arguments. Return a list consisting
1661 of the vars, cnames and rnames."
1662 (let (cnames rnames
)
1666 (when (listp (cdr var
))
1667 (when (and (not (equal colnames
"no"))
1668 (or colnames
(and (equal (nth 1 (cdr var
)) 'hline
)
1669 (not (member 'hline
(cddr (cdr var
)))))))
1670 (let ((both (org-babel-get-colnames (cdr var
))))
1671 (setq cnames
(cons (cons (car var
) (cdr both
))
1673 (setq var
(cons (car var
) (car both
)))))
1674 (when (and rownames
(not (equal rownames
"no")))
1675 (let ((both (org-babel-get-rownames (cdr var
))))
1676 (setq rnames
(cons (cons (car var
) (cdr both
))
1678 (setq var
(cons (car var
) (car both
)))))
1679 (when (and hlines
(not (equal hlines
"yes")))
1680 (setq var
(cons (car var
) (org-babel-del-hlines (cdr var
))))))
1683 (reverse cnames
) (reverse rnames
))))
1685 (defun org-babel-reassemble-table (table colnames rownames
)
1686 "Add column and row names to a table.
1687 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1688 to the table for reinsertion to org-mode."
1690 (let ((table (if (and rownames
(= (length table
) (length rownames
)))
1691 (org-babel-put-rownames table rownames
) table
)))
1692 (if (and colnames
(listp (car table
)) (= (length (car table
))
1694 (org-babel-put-colnames table colnames
) table
))
1697 (defun org-babel-where-is-src-block-head ()
1698 "Find where the current source block begins.
1699 Return the point at the beginning of the current source
1700 block. Specifically at the beginning of the #+BEGIN_SRC line.
1701 If the point is not on a source block then return nil."
1702 (let ((initial (point)) (case-fold-search t
) top bottom
)
1704 (save-excursion ;; on a source name line or a #+header line
1705 (beginning-of-line 1)
1706 (and (or (looking-at org-babel-src-name-regexp
)
1707 (looking-at org-babel-multi-line-header-regexp
))
1709 (while (and (forward-line 1)
1710 (or (looking-at org-babel-src-name-regexp
)
1711 (looking-at org-babel-multi-line-header-regexp
))))
1712 (looking-at org-babel-src-block-regexp
))
1714 (save-excursion ;; on a #+begin_src line
1715 (beginning-of-line 1)
1716 (and (looking-at org-babel-src-block-regexp
)
1718 (save-excursion ;; inside a src block
1720 (re-search-backward "^[ \t]*#\\+begin_src" nil t
) (setq top
(point))
1721 (re-search-forward "^[ \t]*#\\+end_src" nil t
) (setq bottom
(point))
1722 (< top initial
) (< initial bottom
)
1723 (progn (goto-char top
) (beginning-of-line 1)
1724 (looking-at org-babel-src-block-regexp
))
1728 (defun org-babel-goto-src-block-head ()
1729 "Go to the beginning of the current code block."
1731 (let ((head (org-babel-where-is-src-block-head)))
1732 (if head
(goto-char head
) (error "Not currently in a code block"))))
1735 (defun org-babel-goto-named-src-block (name)
1736 "Go to a named source-code block."
1738 (let ((completion-ignore-case t
)
1739 (case-fold-search t
)
1740 (under-point (thing-at-point 'line
)))
1741 (list (org-icompleting-read
1742 "source-block name: " (org-babel-src-block-names) nil t
1745 ((string-match (org-babel-noweb-wrap) under-point
)
1746 (let ((block-name (match-string 1 under-point
)))
1747 (string-match "[^(]*" block-name
)
1748 (match-string 0 block-name
)))
1750 ((string-match org-babel-lob-one-liner-regexp under-point
)
1751 (let ((source-info (car (org-babel-lob-get-info))))
1752 (if (string-match "^\\([^\\[]+?\\)\\(\\[.*\\]\\)?(" source-info
)
1753 (let ((source-name (match-string 1 source-info
)))
1756 ((string-match (concat "#\\+" org-babel-results-keyword
1757 "\\:\s+\\([^\\(]*\\)") under-point
)
1758 (match-string 1 under-point
))
1760 ((and (thing-at-point 'symbol
))
1761 (org-babel-find-named-block (thing-at-point 'symbol
))
1762 (thing-at-point 'symbol
))
1764 (let ((point (org-babel-find-named-block name
)))
1766 ;; taken from `org-open-at-point'
1767 (progn (org-mark-ring-push) (goto-char point
) (org-show-context))
1768 (message "source-code block '%s' not found in this buffer" name
))))
1770 (defun org-babel-find-named-block (name)
1771 "Find a named source-code block.
1772 Return the location of the source block identified by source
1773 NAME, or nil if no such block exists. Set match data according to
1774 org-babel-named-src-block-regexp."
1776 (let ((case-fold-search t
)
1777 (regexp (org-babel-named-src-block-regexp-for-name name
)) msg
)
1778 (goto-char (point-min))
1779 (when (or (re-search-forward regexp nil t
)
1780 (re-search-backward regexp nil t
))
1781 (match-beginning 0)))))
1783 (defun org-babel-src-block-names (&optional file
)
1784 "Returns the names of source blocks in FILE or the current buffer."
1786 (when file
(find-file file
)) (goto-char (point-min))
1787 (let ((case-fold-search t
) names
)
1788 (while (re-search-forward org-babel-src-name-w-name-regexp nil t
)
1789 (setq names
(cons (match-string 3) names
)))
1793 (defun org-babel-goto-named-result (name)
1794 "Go to a named result."
1796 (let ((completion-ignore-case t
))
1797 (list (org-icompleting-read "source-block name: "
1798 (org-babel-result-names) nil t
))))
1799 (let ((point (org-babel-find-named-result name
)))
1801 ;; taken from `org-open-at-point'
1802 (progn (goto-char point
) (org-show-context))
1803 (message "result '%s' not found in this buffer" name
))))
1805 (defun org-babel-find-named-result (name &optional point
)
1806 "Find a named result.
1807 Return the location of the result named NAME in the current
1808 buffer or nil if no such result exists."
1810 (let ((case-fold-search t
))
1811 (goto-char (or point
(point-min)))
1812 (catch 'is-a-code-block
1813 (when (re-search-forward
1814 (concat org-babel-result-regexp
1815 "[ \t]" (regexp-quote name
) "[ \t]*[\n\f\v\r]") nil t
)
1816 (when (and (string= "name" (downcase (match-string 1)))
1817 (or (beginning-of-line 1)
1818 (looking-at org-babel-src-block-regexp
)
1819 (looking-at org-babel-multi-line-header-regexp
)
1820 (looking-at org-babel-lob-one-liner-regexp
)))
1821 (throw 'is-a-code-block
(org-babel-find-named-result name
(point))))
1822 (beginning-of-line 0) (point))))))
1824 (defun org-babel-result-names (&optional file
)
1825 "Returns the names of results in FILE or the current buffer."
1827 (when file
(find-file file
)) (goto-char (point-min))
1828 (let ((case-fold-search t
) names
)
1829 (while (re-search-forward org-babel-result-w-name-regexp nil t
)
1830 (setq names
(cons (match-string 4) names
)))
1834 (defun org-babel-next-src-block (&optional arg
)
1835 "Jump to the next source block.
1836 With optional prefix argument ARG, jump forward ARG many source blocks."
1838 (org-next-block arg nil org-babel-src-block-regexp
))
1841 (defun org-babel-previous-src-block (&optional arg
)
1842 "Jump to the previous source block.
1843 With optional prefix argument ARG, jump backward ARG many source blocks."
1845 (org-previous-block arg org-babel-src-block-regexp
))
1847 (defvar org-babel-load-languages
)
1850 (defun org-babel-mark-block ()
1851 "Mark current src block."
1853 (let ((head (org-babel-where-is-src-block-head)))
1857 (looking-at org-babel-src-block-regexp
))
1858 (push-mark (match-end 5) nil t
)
1859 (goto-char (match-beginning 5)))))
1861 (defun org-babel-demarcate-block (&optional arg
)
1862 "Wrap or split the code in the region or on the point.
1863 When called from inside of a code block the current block is
1864 split. When called from outside of a code block a new code block
1865 is created. In both cases if the region is demarcated and if the
1866 region is not active then the point is demarcated."
1868 (let* ((info (org-babel-get-src-block-info 'light
))
1869 (block (progn (org-babel-where-is-src-block-head) (match-string 0)))
1870 (headers (progn (org-babel-where-is-src-block-head) (match-string 4)))
1871 (stars (concat (make-string (or (org-current-level) 1) ?
*) " "))
1873 (if (let (case-fold-search) (string-match "#\\+begin_src" block
))
1874 (setq lower-case-p t
))
1880 (let ((lang (nth 0 info
))
1881 (indent (make-string (nth 5 info
) ?
)))
1882 (when (string-match "^[[:space:]]*$"
1883 (buffer-substring (point-at-bol)
1885 (delete-region (point-at-bol) (point-at-eol)))
1887 (if (looking-at "^") "" "\n")
1888 indent
(funcall (if lower-case-p
'downcase
'upcase
) "#+end_src\n")
1889 (if arg stars indent
) "\n"
1890 indent
(funcall (if lower-case-p
'downcase
'upcase
) "#+begin_src ")
1892 (if (> (length headers
) 1)
1893 (concat " " headers
) headers
)
1894 (if (looking-at "[\n\r]")
1896 (concat "\n" (make-string (current-column) ?
)))))))
1897 (move-end-of-line 2))
1898 (sort (if (org-region-active-p) (list (mark) (point)) (list (point))) #'>))
1899 (let ((start (point))
1900 (lang (org-icompleting-read
1902 (mapcar #'symbol-name
1904 (append (mapcar #'car org-babel-load-languages
)
1905 (mapcar (lambda (el) (intern (car el
)))
1906 org-src-lang-modes
))))))
1907 (body (delete-and-extract-region
1908 (if (org-region-active-p) (mark) (point)) (point))))
1909 (insert (concat (if (looking-at "^") "" "\n")
1910 (if arg
(concat stars
"\n") "")
1911 (funcall (if lower-case-p
'downcase
'upcase
) "#+begin_src ")
1914 (if (or (= (length body
) 0)
1915 (string-match "[\r\n]$" body
)) "" "\n")
1916 (funcall (if lower-case-p
'downcase
'upcase
) "#+end_src\n")))
1917 (goto-char start
) (move-end-of-line 1)))))
1919 (defvar org-babel-lob-one-liner-regexp
)
1920 (defun org-babel-where-is-src-block-result (&optional insert info hash indent
)
1921 "Find where the current source block results begin.
1922 Return the point at the beginning of the result of the current
1923 source block. Specifically at the beginning of the results line.
1924 If no result exists for this block then create a results line
1925 following the source block."
1927 (let* ((case-fold-search t
)
1928 (on-lob-line (save-excursion
1929 (beginning-of-line 1)
1930 (looking-at org-babel-lob-one-liner-regexp
)))
1931 (inlinep (when (org-babel-get-inline-src-block-matches)
1933 (name (nth 4 (or info
(org-babel-get-src-block-info 'light
))))
1934 (head (unless on-lob-line
(org-babel-where-is-src-block-head)))
1936 (when head
(goto-char head
))
1937 (org-with-wide-buffer
1939 found
;; was there a result (before we potentially insert one)
1944 ;; - return t if it is found, else return nil
1945 ;; - if it does not need to be rebuilt, then don't set end
1946 ;; - if it does need to be rebuilt then do set end
1947 name
(setq beg
(org-babel-find-named-result name
))
1949 (when (and hash
(not (string= hash
(match-string 5))))
1950 (goto-char beg
) (setq end beg
) ;; beginning of result
1952 (delete-region end
(org-babel-result-end)) nil
)))
1955 ;; - return t if it is found, else return nil
1956 ;; - if it is found, and the hash doesn't match, delete and set end
1957 (or on-lob-line
(re-search-forward "^[ \t]*#\\+end_src" nil t
))
1958 (progn (end-of-line 1)
1959 (if (eobp) (insert "\n") (forward-char 1))
1963 (progn ;; unnamed results line already exists
1965 (while (re-search-forward "[^ \f\t\n\r\v]" nil t
)
1966 (beginning-of-line 1)
1968 ((looking-at (concat org-babel-result-regexp
"\n"))
1969 (throw 'non-comment t
))
1970 ((and (looking-at "^[ \t]*#")
1972 org-babel-lob-one-liner-regexp
)))
1974 (t (throw 'non-comment nil
))))))
1975 (let ((this-hash (match-string 5)))
1977 ;; must remove and rebuild if hash!=old-hash
1978 (if (and hash
(not (string= hash this-hash
)))
1980 (setq end
(point-at-bol))
1982 (delete-region end
(org-babel-result-end))
1984 (setq end nil
))))))))))
1985 (if (not (and insert end
)) found
1988 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1990 (when (wholenump indent
) (make-string indent ?
))
1991 "#+" org-babel-results-keyword
1993 (if org-babel-hash-show-time
1995 "["(format-time-string "<%Y-%m-%d %H:%M:%S>")" "hash
"]")
1996 (concat "["hash
"]")))
1998 (when name
(concat " " name
)) "\n"))
1999 (unless beg
(insert "\n") (backward-char))
2000 (beginning-of-line 0)
2001 (if hash
(org-babel-hide-hash))
2004 (defvar org-block-regexp
)
2005 (defun org-babel-read-result ()
2006 "Read the result at `point' into emacs-lisp."
2007 (let ((case-fold-search t
) result-string
)
2009 ((org-at-table-p) (org-babel-read-table))
2010 ((org-at-item-p) (org-babel-read-list))
2011 ((looking-at org-bracket-link-regexp
) (org-babel-read-link))
2012 ((looking-at org-block-regexp
) (org-remove-indentation (match-string 4)))
2013 ((or (looking-at "^[ \t]*: ") (looking-at "^[ \t]*:$"))
2016 (mapconcat (lambda (line)
2017 (or (and (> (length line
) 1)
2018 (string-match "^[ \t]*: ?\\(.+\\)" line
)
2019 (match-string 1 line
))
2023 (point) (org-babel-result-end)) "[\r\n]+")
2025 (or (org-babel-number-p result-string
) result-string
))
2026 ((looking-at org-babel-result-regexp
)
2027 (save-excursion (forward-line 1) (org-babel-read-result))))))
2029 (defun org-babel-read-table ()
2030 "Read the table at `point' into emacs-lisp."
2031 (mapcar (lambda (row)
2032 (if (and (symbolp row
) (equal row
'hline
)) row
2033 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
)) row
)))
2034 (org-table-to-lisp)))
2036 (defun org-babel-read-list ()
2037 "Read the list at `point' into emacs-lisp."
2038 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
))
2039 (mapcar #'cadr
(cdr (org-list-parse-list)))))
2041 (defvar org-link-types-re
)
2042 (defun org-babel-read-link ()
2043 "Read the link at `point' into emacs-lisp.
2044 If the path of the link is a file path it is expanded using
2045 `expand-file-name'."
2046 (let* ((case-fold-search t
)
2047 (raw (and (looking-at org-bracket-link-regexp
)
2048 (org-no-properties (match-string 1))))
2049 (type (and (string-match org-link-types-re raw
)
2050 (match-string 1 raw
))))
2052 ((not type
) (expand-file-name raw
))
2053 ((string= type
"file")
2054 (and (string-match "file\\(.*\\):\\(.+\\)" raw
)
2055 (expand-file-name (match-string 2 raw
))))
2058 (defun org-babel-format-result (result &optional sep
)
2059 "Format RESULT for writing to file."
2060 (let ((echo-res (lambda (r) (if (stringp r
) r
(format "%S" r
)))))
2064 result
(list :sep
(or sep
"\t") :fmt echo-res
))
2066 (funcall echo-res result
))))
2068 (defun org-babel-insert-result
2069 (result &optional result-params info hash indent lang
)
2070 "Insert RESULT into the current buffer.
2071 By default RESULT is inserted after the end of the
2072 current source block. With optional argument RESULT-PARAMS
2073 controls insertion of results in the org-mode file.
2074 RESULT-PARAMS can take the following values:
2076 replace - (default option) insert results after the source block
2077 replacing any previously inserted results
2079 silent -- no results are inserted into the Org-mode buffer but
2080 the results are echoed to the minibuffer and are
2081 ingested by Emacs (a potentially time consuming
2084 file ---- the results are interpreted as a file path, and are
2085 inserted into the buffer using the Org-mode file syntax
2087 list ---- the results are interpreted as an Org-mode list.
2089 raw ----- results are added directly to the Org-mode file. This
2090 is a good option if you code block will output org-mode
2093 drawer -- results are added directly to the Org-mode file as with
2094 \"raw\", but are wrapped in a RESULTS drawer, allowing
2095 them to later be replaced or removed automatically.
2097 org ----- results are added inside of a \"#+BEGIN_SRC org\" block.
2098 They are not comma-escaped when inserted, but Org syntax
2099 here will be discarded when exporting the file.
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 #+BEGIN_SRC block with the source-code
2112 language set appropriately. Note this relies on the
2113 optional LANG argument."
2114 (if (stringp result
)
2116 (setq result
(org-no-properties result
))
2117 (when (member "file" result-params
)
2118 (setq result
(org-babel-result-to-file
2119 result
(when (assoc :file-desc
(nth 2 info
))
2120 (or (cdr (assoc :file-desc
(nth 2 info
)))
2122 (unless (listp result
) (setq result
(format "%S" result
))))
2123 (if (and result-params
(member "silent" result-params
))
2125 (message (replace-regexp-in-string "%" "%%" (format "%S" result
)))
2130 (when (or (org-babel-get-inline-src-block-matches)
2131 (org-babel-get-lob-one-liner-matches))
2132 (goto-char (match-end 0))
2133 (insert (if (listp result
) "\n" " "))
2135 (existing-result (unless inlinep
2136 (org-babel-where-is-src-block-result
2137 t info hash indent
)))
2139 (cdr (assoc :results_switches
(nth 2 info
))))
2140 (visible-beg (copy-marker (point-min)))
2141 (visible-end (copy-marker (point-max)))
2142 ;; When results exist outside of the current visible
2143 ;; region of the buffer, be sure to widen buffer to
2145 (outside-scope-p (and existing-result
2146 (or (> visible-beg existing-result
)
2147 (<= visible-end existing-result
))))
2149 (when (and (stringp result
) ; ensure results end in a newline
2151 (> (length result
) 0)
2152 (not (or (string-equal (substring result -
1) "\n")
2153 (string-equal (substring result -
1) "\r"))))
2154 (setq result
(concat result
"\n")))
2157 (when outside-scope-p
(widen))
2158 (if (not existing-result
)
2159 (setq beg
(or inlinep
(point)))
2160 (goto-char existing-result
)
2162 (re-search-forward "#" nil t
)
2163 (setq indent
(- (current-column) 1)))
2167 ((member "replace" result-params
)
2168 (delete-region (point) (org-babel-result-end)))
2169 ((member "append" result-params
)
2170 (goto-char (org-babel-result-end)) (setq beg
(point-marker)))
2171 ((member "prepend" result-params
)))) ; already there
2172 (setq results-switches
2173 (if results-switches
(concat " " results-switches
) ""))
2174 (let ((wrap (lambda (start finish
&optional no-escape
)
2175 (goto-char end
) (insert (concat finish
"\n"))
2176 (goto-char beg
) (insert (concat start
"\n"))
2178 (org-escape-code-in-region (min (point) end
) end
))
2179 (goto-char end
) (goto-char (point-at-eol))
2180 (setq end
(point-marker))))
2181 (proper-list-p (lambda (it) (and (listp it
) (null (cdr (last it
)))))))
2182 ;; insert results based on type
2184 ;; do nothing for an empty result
2186 ;; insert a list if preferred
2187 ((member "list" result-params
)
2190 (org-list-to-generic
2193 (lambda (el) (list nil
(if (stringp el
) el
(format "%S" el
))))
2194 (if (listp result
) result
(split-string result
"\n" t
))))
2195 '(:splicep nil
:istart
"- " :iend
"\n")))
2197 ;; assume the result is a table if it's not a string
2198 ((funcall proper-list-p result
)
2200 (insert (concat (orgtbl-to-orgtbl
2202 (lambda (el) (or (listp el
) (eq el
'hline
)))
2204 result
(list result
))
2205 '(:fmt
(lambda (cell) (format "%s" cell
)))) "\n"))
2206 (goto-char beg
) (when (org-at-table-p) (org-table-align)))
2207 ((and (listp result
) (not (funcall proper-list-p result
)))
2208 (insert (format "%s\n" result
)))
2209 ((member "file" result-params
)
2210 (when inlinep
(goto-char inlinep
))
2212 (t (goto-char beg
) (insert result
)))
2213 (when (funcall proper-list-p result
) (goto-char (org-table-end)))
2214 (setq end
(point-marker))
2215 ;; possibly wrap result
2217 ((assoc :wrap
(nth 2 info
))
2218 (let ((name (or (cdr (assoc :wrap
(nth 2 info
))) "RESULTS")))
2219 (funcall wrap
(concat "#+BEGIN_" name
)
2220 (concat "#+END_" (car (org-split-string name
))))))
2221 ((member "html" result-params
)
2222 (funcall wrap
"#+BEGIN_HTML" "#+END_HTML"))
2223 ((member "latex" result-params
)
2224 (funcall wrap
"#+BEGIN_LaTeX" "#+END_LaTeX"))
2225 ((member "org" result-params
)
2226 (goto-char beg
) (if (org-at-table-p) (org-cycle))
2227 (funcall wrap
"#+BEGIN_SRC org" "#+END_SRC"))
2228 ((member "code" result-params
)
2229 (funcall wrap
(format "#+BEGIN_SRC %s%s" (or lang
"none") results-switches
)
2231 ((member "raw" result-params
)
2232 (goto-char beg
) (if (org-at-table-p) (org-cycle)))
2233 ((or (member "drawer" result-params
)
2234 ;; Stay backward compatible with <7.9.2
2235 (member "wrap" result-params
))
2236 (goto-char beg
) (if (org-at-table-p) (org-cycle))
2237 (funcall wrap
":RESULTS:" ":END:" 'no-escape
))
2238 ((and (not (funcall proper-list-p result
))
2239 (not (member "file" result-params
)))
2240 (org-babel-examplify-region beg end results-switches
)
2241 (setq end
(point)))))
2242 ;; possibly indent the results to match the #+results line
2243 (when (and (not inlinep
) (numberp indent
) indent
(> indent
0)
2244 ;; in this case `table-align' does the work for us
2245 (not (and (listp result
)
2246 (member "append" result-params
))))
2247 (indent-rigidly beg end indent
))
2249 (if (member "value" result-params
)
2250 (message "Code block returned no value.")
2251 (message "Code block produced no output."))
2252 (message "Code block evaluation complete.")))
2253 (when outside-scope-p
(narrow-to-region visible-beg visible-end
))
2254 (set-marker visible-beg nil
)
2255 (set-marker visible-end nil
))))))
2257 (defun org-babel-remove-result (&optional info keep-keyword
)
2258 "Remove the result of the current source block."
2260 (let ((location (org-babel-where-is-src-block-result nil info
)))
2263 (goto-char location
)
2264 (when (looking-at (concat org-babel-result-regexp
".*$"))
2266 (if keep-keyword
(1+ (match-end 0)) (1- (match-beginning 0)))
2267 (progn (forward-line 1) (org-babel-result-end))))))))
2269 (defun org-babel-remove-result-one-or-many (x)
2270 "Remove the result of the current source block.
2271 If called with a prefix argument, remove all result blocks
2275 (org-babel-map-src-blocks nil
(org-babel-remove-result))
2276 (org-babel-remove-result)))
2278 (defun org-babel-result-end ()
2279 "Return the point at the end of the current set of results."
2282 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
2283 ((org-at-item-p) (let* ((struct (org-list-struct))
2284 (prvs (org-list-prevs-alist struct
)))
2285 (org-list-get-list-end (point-at-bol) struct prvs
)))
2286 ((let ((case-fold-search t
)) (looking-at "^\\([ \t]*\\):results:"))
2287 (progn (re-search-forward (concat "^" (match-string 1) ":END:"))
2288 (forward-char 1) (point)))
2290 (let ((case-fold-search t
))
2291 (if (looking-at (concat "[ \t]*#\\+begin_\\([^ \t\n\r]+\\)"))
2292 (progn (re-search-forward (concat "[ \t]*#\\+end_" (match-string 1))
2295 (while (looking-at "[ \t]*\\(: \\|:$\\|\\[\\[\\)")
2299 (defun org-babel-result-to-file (result &optional description
)
2300 "Convert RESULT into an `org-mode' link with optional DESCRIPTION.
2301 If the `default-directory' is different from the containing
2302 file's directory then expand relative links."
2303 (when (stringp result
)
2304 (format "[[file:%s]%s]"
2305 (if (and default-directory
2307 (not (string= (expand-file-name default-directory
)
2309 (file-name-directory buffer-file-name
)))))
2310 (expand-file-name result default-directory
)
2312 (if description
(concat "[" description
"]") ""))))
2314 (defvar org-babel-capitalize-example-region-markers nil
2315 "Make true to capitalize begin/end example markers inserted by code blocks.")
2317 (define-obsolete-function-alias
2318 'org-babel-examplize-region
2319 'org-babel-examplify-region
"24.5")
2321 (defun org-babel-examplify-region (beg end
&optional results-switches
)
2322 "Comment out region using the inline '==' or ': ' org example quote."
2324 (let ((chars-between (lambda (b e
)
2325 (not (string-match "^[\\s]*$"
2326 (buffer-substring b e
)))))
2327 (maybe-cap (lambda (str) (if org-babel-capitalize-example-region-markers
2329 (beg-bol (save-excursion (goto-char beg
) (point-at-bol)))
2330 (end-bol (save-excursion (goto-char end
) (point-at-bol)))
2331 (end-eol (save-excursion (goto-char end
) (point-at-eol))))
2332 (if (and (not (= end end-bol
))
2333 (or (funcall chars-between beg-bol beg
)
2334 (funcall chars-between end end-eol
)))
2337 (insert (format org-babel-inline-result-wrap
2338 (prog1 (buffer-substring beg end
)
2339 (delete-region beg end
)))))
2340 (let ((size (count-lines beg end
)))
2342 (cond ((= size
0)) ; do nothing for an empty result
2343 ((< size org-babel-min-lines-for-block-output
)
2346 (beginning-of-line 1) (insert ": ") (forward-line 1)))
2349 (insert (if results-switches
2351 (funcall maybe-cap
"#+begin_example")
2353 (funcall maybe-cap
"#+begin_example\n")))
2354 (if (markerp end
) (goto-char end
) (forward-char (- end beg
)))
2355 (insert (funcall maybe-cap
"#+end_example\n")))))))))
2357 (defun org-babel-update-block-body (new-body)
2358 "Update the body of the current code block to NEW-BODY."
2359 (if (not (org-babel-where-is-src-block-head))
2360 (error "Not in a source block")
2362 (replace-match (concat (org-babel-trim (org-remove-indentation new-body
))
2364 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
2366 (defun org-babel-merge-params (&rest plists
)
2367 "Combine all parameter association lists in PLISTS.
2368 Later elements of PLISTS override the values of previous elements.
2369 This takes into account some special considerations for certain
2370 parameters when merging lists."
2371 (let* ((results-exclusive-groups
2372 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2373 (cdr (assoc 'results org-babel-common-header-args-w-values
))))
2374 (exports-exclusive-groups
2375 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2376 (cdr (assoc 'exports org-babel-common-header-args-w-values
))))
2378 (e-merge (lambda (exclusive-groups &rest result-params
)
2379 ;; maintain exclusivity of mutually exclusive parameters
2381 (mapc (lambda (new-params)
2382 (mapc (lambda (new-param)
2383 (mapc (lambda (exclusive-group)
2384 (when (member new-param exclusive-group
)
2385 (mapcar (lambda (excluded-param)
2392 (setq output
(org-uniquify
2393 (cons new-param output
))))
2397 params results exports tangle noweb cache vars shebang comments padline
2406 (let ((name (if (listp (cdr pair
))
2408 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
2410 (intern (match-string 1 (cdr pair
)))))))
2414 (if (member name
(mapcar #'car vars
))
2416 (push name clearnames
)
2420 (unless (equal (car p
) name
) p
))
2423 (list (cons name pair
))))
2424 ;; if no name is given and we already have named variables
2425 ;; then assign to named variables in order
2426 (if (and vars
(nth variable-index vars
))
2427 (let ((name (car (nth variable-index vars
))))
2428 (push name clearnames
) ; clear out colnames
2431 (prog1 (setf (cddr (nth variable-index vars
))
2432 (concat (symbol-name name
) "=" (cdr pair
)))
2433 (incf variable-index
)))
2434 (error "Variable \"%s\" must be assigned a default value"
2437 (setq results
(funcall e-merge results-exclusive-groups
2440 (let ((r (cdr pair
)))
2441 (if (stringp r
) r
(eval r
)))))))
2444 (setq results
(funcall e-merge results-exclusive-groups
2446 (unless (or (member "both" exports
)
2447 (member "none" exports
)
2448 (member "code" exports
))
2449 (setq exports
(funcall e-merge exports-exclusive-groups
2450 exports
'("results"))))
2451 (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))
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
)))))
2463 (setq exports
(funcall e-merge exports-exclusive-groups
2464 exports
(split-string (cdr pair
)))))
2465 (:tangle
;; take the latest -- always overwrite
2466 (setq tangle
(or (list (cdr pair
)) tangle
)))
2468 (setq noweb
(funcall e-merge
2469 '(("yes" "no" "tangle" "no-export"
2470 "strip-export" "eval"))
2472 (split-string (or (cdr pair
) "")))))
2474 (setq cache
(funcall e-merge
'(("yes" "no")) cache
2475 (split-string (or (cdr pair
) "")))))
2477 (setq padline
(funcall e-merge
'(("yes" "no")) padline
2478 (split-string (or (cdr pair
) "")))))
2479 (:shebang
;; take the latest -- always overwrite
2480 (setq shebang
(or (list (cdr pair
)) shebang
)))
2482 (setq comments
(funcall e-merge
'(("yes" "no")) comments
2483 (split-string (or (cdr pair
) "")))))
2484 (t ;; replace: this covers e.g. :session
2485 (setq params
(cons pair
(assq-delete-all (car pair
) params
))))))
2488 (setq vars
(reverse vars
))
2489 (while vars
(setq params
(cons (cons :var
(cddr (pop vars
))) params
)))
2490 ;; clear out col-names and row-names for replaced variables
2495 (when (assoc param params
)
2496 (setf (cdr (assoc param params
))
2497 (org-remove-if (lambda (pair) (equal (car pair
) name
))
2498 (cdr (assoc param params
))))
2499 (setf params
(org-remove-if (lambda (pair) (and (equal (car pair
) param
)
2502 (list :colname-names
:rowname-names
)))
2506 (let ((key (intern (concat ":" (symbol-name hd
))))
2508 (setf params
(cons (cons key
(mapconcat 'identity val
" ")) params
))))
2509 '(results exports tangle noweb padline cache shebang comments
))
2512 (defvar org-babel-use-quick-and-dirty-noweb-expansion nil
2513 "Set to true to use regular expressions to expand noweb references.
2514 This results in much faster noweb reference expansion but does
2515 not properly allow code blocks to inherit the \":noweb-ref\"
2516 header argument from buffer or subtree wide properties.")
2518 (defun org-babel-noweb-p (params context
)
2519 "Check if PARAMS require expansion in CONTEXT.
2520 CONTEXT may be one of :tangle, :export or :eval."
2522 (intersect (lambda (as bs
)
2524 (if (member (car as
) bs
)
2526 (funcall intersect
(cdr as
) bs
))))))
2527 (funcall intersect
(case context
2528 (:tangle
'("yes" "tangle" "no-export" "strip-export"))
2529 (:eval
'("yes" "no-export" "strip-export" "eval"))
2531 (split-string (or (cdr (assoc :noweb params
)) "")))))
2533 (defun org-babel-expand-noweb-references (&optional info parent-buffer
)
2534 "Expand Noweb references in the body of the current source code block.
2536 For example the following reference would be replaced with the
2537 body of the source-code block named 'example-block'.
2541 Note that any text preceding the <<foo>> construct on a line will
2542 be interposed between the lines of the replacement text. So for
2543 example if <<foo>> is placed behind a comment, then the entire
2544 replacement text will also be commented.
2546 This function must be called from inside of the buffer containing
2547 the source-code block which holds BODY.
2549 In addition the following syntax can be used to insert the
2550 results of evaluating the source-code block named 'example-block'.
2554 Any optional arguments can be passed to example-block by placing
2555 the arguments inside the parenthesis following the convention
2556 defined by `org-babel-lob'. For example
2558 <<example-block(a=9)>>
2560 would set the value of argument \"a\" equal to \"9\". Note that
2561 these arguments are not evaluated in the current source-code
2562 block but are passed literally to the \"example-block\"."
2563 (let* ((parent-buffer (or parent-buffer
(current-buffer)))
2564 (info (or info
(org-babel-get-src-block-info 'light
)))
2567 (ob-nww-start org-babel-noweb-wrap-start
)
2568 (ob-nww-end org-babel-noweb-wrap-end
)
2569 (comment (string= "noweb" (cdr (assoc :comments
(nth 2 info
)))))
2570 (rx-prefix (concat "\\(" org-babel-src-name-regexp
"\\|"
2571 ":noweb-ref[ \t]+" "\\)"))
2573 (nb-add (lambda (text) (setq new-body
(concat new-body text
))))
2574 (c-wrap (lambda (text)
2576 (funcall (intern (concat lang
"-mode")))
2577 (comment-region (point) (progn (insert text
) (point)))
2578 (org-babel-trim (buffer-string)))))
2579 index source-name evaluate prefix
)
2581 (org-set-local 'org-babel-noweb-wrap-start ob-nww-start
)
2582 (org-set-local 'org-babel-noweb-wrap-end ob-nww-end
)
2583 (insert body
) (goto-char (point-min))
2584 (setq index
(point))
2585 (while (and (re-search-forward (org-babel-noweb-wrap) nil t
))
2586 (save-match-data (setf source-name
(match-string 1)))
2587 (save-match-data (setq evaluate
(string-match "\(.*\)" source-name
)))
2590 (buffer-substring (match-beginning 0)
2592 (beginning-of-line 1) (point)))))
2593 ;; add interval to new-body (removing noweb reference)
2594 (goto-char (match-beginning 0))
2595 (funcall nb-add
(buffer-substring index
(point)))
2596 (goto-char (match-end 0))
2597 (setq index
(point))
2600 (with-current-buffer parent-buffer
2603 (mapconcat ;; Interpose PREFIX between every line.
2607 (let ((raw (org-babel-ref-resolve source-name
)))
2608 (if (stringp raw
) raw
(format "%S" raw
)))
2610 ;; Retrieve from the library of babel.
2611 (nth 2 (assoc (intern source-name
)
2612 org-babel-library-of-babel
))
2613 ;; Return the contents of headlines literally.
2615 (when (org-babel-ref-goto-headline-id source-name
)
2616 (org-babel-ref-headline-body)))
2617 ;; Find the expansion of reference in this buffer.
2618 (let ((rx (concat rx-prefix source-name
"[ \t\n]"))
2621 (goto-char (point-min))
2622 (if org-babel-use-quick-and-dirty-noweb-expansion
2623 (while (re-search-forward rx nil t
)
2624 (let* ((i (org-babel-get-src-block-info 'light
))
2625 (body (org-babel-expand-noweb-references i
))
2626 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2629 (let ((cs (org-babel-tangle-comment-links i
)))
2630 (concat (funcall c-wrap
(car cs
)) "\n"
2632 (funcall c-wrap
(cadr cs
))))
2634 (setq expansion
(cons sep
(cons full expansion
)))))
2635 (org-babel-map-src-blocks nil
2636 (let ((i (org-babel-get-src-block-info 'light
)))
2637 (when (equal (or (cdr (assoc :noweb-ref
(nth 2 i
)))
2640 (let* ((body (org-babel-expand-noweb-references i
))
2641 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2644 (let ((cs (org-babel-tangle-comment-links i
)))
2645 (concat (funcall c-wrap
(car cs
)) "\n"
2647 (funcall c-wrap
(cadr cs
))))
2650 (cons sep
(cons full expansion
)))))))))
2652 (mapconcat #'identity
(nreverse (cdr expansion
)) "")))
2653 ;; Possibly raise an error if named block doesn't exist.
2654 (if (or org-babel-noweb-error-all-langs
2655 (member lang org-babel-noweb-error-langs
))
2657 (org-babel-noweb-wrap source-name
)
2658 "could not be resolved (see "
2659 "`org-babel-noweb-error-langs')"))
2661 "[\n\r]") (concat "\n" prefix
))))))
2662 (funcall nb-add
(buffer-substring index
(point-max))))
2665 (defun org-babel-script-escape (str &optional force
)
2666 "Safely convert tables into elisp lists."
2671 (or (and (string-equal "[" (substring str
0 1))
2672 (string-equal "]" (substring str -
1)))
2673 (and (string-equal "{" (substring str
0 1))
2674 (string-equal "}" (substring str -
1)))
2675 (and (string-equal "(" (substring str
0 1))
2676 (string-equal ")" (substring str -
1))))))
2680 (let (in-single in-double out
)
2686 (91 (if (or in-double in-single
) ; [
2689 (93 (if (or in-double in-single
) ; ]
2692 (123 (if (or in-double in-single
) ; {
2695 (125 (if (or in-double in-single
) ; }
2698 (44 (if (or in-double in-single
) ; ,
2699 (cons 44 out
) (cons 32 out
)))
2700 (39 (if in-double
; '
2702 (setq in-single
(not in-single
)) (cons 34 out
)))
2703 (34 (if in-single
; "
2704 (append (list 34 32) out
)
2705 (setq in-double
(not in-double
)) (cons 34 out
)))
2706 (t (cons ch out
)))))
2707 (string-to-list str
))
2708 (apply #'string
(reverse out
)))))
2710 (condition-case nil
(org-babel-read escaped
) (error escaped
))))
2712 (defun org-babel-read (cell &optional inhibit-lisp-eval
)
2713 "Convert the string value of CELL to a number if appropriate.
2714 Otherwise if cell looks like lisp (meaning it starts with a
2715 \"(\", \"'\", \"`\" or a \"[\") then read it as lisp,
2716 otherwise return it unmodified as a string. Optional argument
2717 NO-LISP-EVAL inhibits lisp evaluation for situations in which is
2718 it not appropriate."
2719 (if (and (stringp cell
) (not (equal cell
"")))
2720 (or (org-babel-number-p cell
)
2721 (if (and (not inhibit-lisp-eval
)
2722 (or (member (substring cell
0 1) '("(" "'" "`" "["))
2723 (string= cell
"*this*")))
2725 (if (string= (substring cell
0 1) "\"")
2727 (progn (set-text-properties 0 (length cell
) nil cell
) cell
))))
2730 (defun org-babel-number-p (string)
2731 "If STRING represents a number return its value."
2732 (if (and (string-match "[0-9]+" string
)
2733 (string-match "^-?[0-9]*\\.?[0-9]*$" string
)
2734 (= (length (substring string
(match-beginning 0)
2737 (string-to-number string
)))
2739 (defun org-babel-import-elisp-from-file (file-name &optional separator
)
2740 "Read the results located at FILE-NAME into an elisp table.
2741 If the table is trivial, then return it as a scalar."
2743 (save-window-excursion
2747 (org-table-import file-name separator
)
2748 (delete-file file-name
)
2749 (setq result
(mapcar (lambda (row)
2750 (mapcar #'org-babel-string-read row
))
2751 (org-table-to-lisp))))
2752 (error (message "Error reading results: %s" err
) nil
)))
2753 (if (null (cdr result
)) ;; if result is trivial vector, then scalarize it
2754 (if (consp (car result
))
2755 (if (null (cdr (car result
)))
2761 (defun org-babel-string-read (cell)
2762 "Strip nested \"s from around strings."
2763 (org-babel-read (or (and (stringp cell
)
2764 (string-match "\\\"\\(.+\\)\\\"" cell
)
2765 (match-string 1 cell
))
2768 (defun org-babel-chomp (string &optional regexp
)
2769 "Strip a trailing space or carriage return from STRING.
2770 The default regexp used is \"[ \\f\\t\\n\\r\\v]\" but another one
2771 can be specified as the REGEXP argument."
2772 (let ((regexp (or regexp
"[ \f\t\n\r\v]")))
2773 (while (and (> (length string
) 0)
2774 (string-match regexp
(substring string -
1)))
2775 (setq string
(substring string
0 -
1)))
2778 (defun org-babel-trim (string &optional regexp
)
2779 "Strip a leading and trailing space or carriage return from STRING.
2780 Like `org-babel-chomp', but run on both the first and last
2781 character of the string."
2784 (org-babel-chomp (org-reverse-string string
) regexp
)) regexp
))
2786 (defun org-babel-tramp-handle-call-process-region
2787 (start end program
&optional delete buffer display
&rest args
)
2788 "Use Tramp to handle `call-process-region'.
2789 Fixes a bug in `tramp-handle-call-process-region'."
2790 (if (and (featurep 'tramp
) (file-remote-p default-directory
))
2791 (let ((tmpfile (tramp-compat-make-temp-file "")))
2792 (write-region start end tmpfile
)
2793 (when delete
(delete-region start end
))
2795 ;; (apply 'call-process program tmpfile buffer display args)
2797 (apply 'process-file program tmpfile buffer display args
)
2798 (delete-file tmpfile
)))
2799 ;; org-babel-call-process-region-original is the original emacs
2800 ;; definition. It is in scope from the let binding in
2801 ;; org-babel-execute-src-block
2802 (apply org-babel-call-process-region-original
2803 start end program delete buffer display args
)))
2805 (defun org-babel-local-file-name (file)
2806 "Return the local name component of FILE."
2807 (or (file-remote-p file
'localname
) file
))
2809 (defun org-babel-process-file-name (name &optional no-quote-p
)
2810 "Prepare NAME to be used in an external process.
2811 If NAME specifies a remote location, the remote portion of the
2812 name is removed, since in that case the process will be executing
2813 remotely. The file name is then processed by `expand-file-name'.
2814 Unless second argument NO-QUOTE-P is non-nil, the file name is
2815 additionally processed by `shell-quote-argument'"
2816 (let ((f (org-babel-local-file-name (expand-file-name name
))))
2817 (if no-quote-p f
(shell-quote-argument f
))))
2819 (defvar org-babel-temporary-directory
)
2820 (unless (or noninteractive
(boundp 'org-babel-temporary-directory
))
2821 (defvar org-babel-temporary-directory
2822 (or (and (boundp 'org-babel-temporary-directory
)
2823 (file-exists-p org-babel-temporary-directory
)
2824 org-babel-temporary-directory
)
2825 (make-temp-file "babel-" t
))
2826 "Directory to hold temporary files created to execute code blocks.
2827 Used by `org-babel-temp-file'. This directory will be removed on
2830 (defcustom org-babel-remote-temporary-directory
"/tmp/"
2831 "Directory to hold temporary files on remote hosts."
2835 (defmacro org-babel-result-cond
(result-params scalar-form
&rest table-forms
)
2836 "Call the code to parse raw string results according to RESULT-PARAMS."
2838 (debug (form form
&rest form
)))
2839 (org-with-gensyms (params)
2840 `(let ((,params
,result-params
))
2841 (unless (member "none" ,params
)
2842 (if (or (member "scalar" ,params
)
2843 (member "verbatim" ,params
)
2844 (member "html" ,params
)
2845 (member "code" ,params
)
2846 (member "pp" ,params
)
2847 (and (or (member "output" ,params
)
2848 (member "raw" ,params
)
2849 (member "org" ,params
)
2850 (member "drawer" ,params
))
2851 (not (member "table" ,params
))))
2854 (def-edebug-spec org-babel-result-cond
(form form body
))
2856 (defun org-babel-temp-file (prefix &optional suffix
)
2857 "Create a temporary file in the `org-babel-temporary-directory'.
2858 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2859 value of `temporary-file-directory' temporarily set to the value
2860 of `org-babel-temporary-directory'."
2861 (if (file-remote-p default-directory
)
2863 (concat (file-remote-p default-directory
)
2865 prefix org-babel-remote-temporary-directory
))))
2866 (make-temp-file prefix nil suffix
))
2867 (let ((temporary-file-directory
2868 (or (and (boundp 'org-babel-temporary-directory
)
2869 (file-exists-p org-babel-temporary-directory
)
2870 org-babel-temporary-directory
)
2871 temporary-file-directory
)))
2872 (make-temp-file prefix nil suffix
))))
2874 (defun org-babel-remove-temporary-directory ()
2875 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2876 (when (and (boundp 'org-babel-temporary-directory
)
2877 (file-exists-p org-babel-temporary-directory
))
2878 ;; taken from `delete-directory' in files.el
2881 (mapc (lambda (file)
2882 ;; This test is equivalent to
2883 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2884 ;; but more efficient
2885 (if (eq t
(car (file-attributes file
)))
2886 (delete-directory file
)
2887 (delete-file file
)))
2888 ;; We do not want to delete "." and "..".
2889 (directory-files org-babel-temporary-directory
'full
2890 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2891 (delete-directory org-babel-temporary-directory
))
2893 (message "Failed to remove temporary Org-babel directory %s"
2894 (if (boundp 'org-babel-temporary-directory
)
2895 org-babel-temporary-directory
2896 "[directory not defined]"))))))
2898 (add-hook 'kill-emacs-hook
'org-babel-remove-temporary-directory
)
2900 (defun org-babel-one-header-arg-safe-p (pair safe-list
)
2901 "Determine if the PAIR is a safe babel header arg according to SAFE-LIST.
2903 For the format of SAFE-LIST, see `org-babel-safe-header-args'."
2905 (keywordp (car pair
))
2906 (stringp (cdr pair
))
2908 (memq (car pair
) safe-list
)
2909 (let ((entry (assq (car pair
) safe-list
)))
2912 (cond ((functionp (cdr entry
))
2913 (funcall (cdr entry
) (cdr pair
)))
2914 ((listp (cdr entry
))
2915 (member (cdr pair
) (cdr entry
)))
2918 (defun org-babel-generate-file-param (src-name params
)
2919 "Calculate the filename for source block results.
2921 The directory is calculated from the :output-dir property of the
2922 source block; if not specified, use the current directory.
2924 If the source block has a #+NAME and the :file parameter does not
2925 contain any period characters, then the :file parameter is
2926 treated as an extension, and the output file name is the
2927 concatenation of the directory (as calculated above), the block
2928 name, a period, and the parameter value as a file extension.
2929 Otherwise, the :file parameter is treated as a full file name,
2930 and the output file name is the directory (as calculated above)
2931 plus the parameter value."
2932 (let* ((file-cons (assq :file params
))
2933 (file-ext-cons (assq :file-ext params
))
2934 (file-ext (cdr-safe file-ext-cons
))
2935 (dir (cdr-safe (assq :output-dir params
)))
2937 ;; create the output-dir if it does not exist
2939 (make-directory dir t
))
2941 ;; :file given; add :output-dir if given
2943 (setcdr file-cons
(concat (file-name-as-directory dir
) (cdr file-cons
))))
2944 ;; :file not given; compute from name and :file-ext if possible
2945 (when (and src-name file-ext
)
2947 (setq fname
(concat (file-name-as-directory (or dir
""))
2948 src-name
"." file-ext
))
2949 (setq fname
(concat src-name
"." file-ext
)))
2950 (setq params
(cons (cons :file fname
) params
))))
2953 ;;; Used by backends: R, Maxima, Octave.
2954 (defun org-babel-graphical-output-file (params)
2955 "File where a babel block should send graphical output, per PARAMS."
2956 (unless (assq :file params
)
2957 (if (assq :file-ext params
)
2958 (user-error ":file-ext given but no :file generated; did you forget to give a block a #+NAME?")
2959 (user-error "No :file header argument given; cannot create graphical result.")))
2960 (and (member "graphics" (cdr (assq :result-params params
)))
2961 (cdr (assq :file params
))))
2966 ;; generated-autoload-file: "org-loaddefs.el"
2969 ;;; ob-core.el ends here