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