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