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