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