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