ob-core: allow language specific header arguments in properties
[org-mode.git] / lisp / ob-core.el
blobd339475e738af8dc26276c59bcdcef5386f6d71f
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 an association list of any source block params which
1295 may be specified in the properties of the current outline entry."
1296 (save-match-data
1297 (let* ((lang-props
1298 (save-match-data
1299 (org-babel-parse-header-arguments
1300 (org-entry-get (point) (concat "header-args:" lang)
1301 'inherit))))
1302 (default-props
1303 (save-match-data
1304 (org-babel-parse-header-arguments
1305 (org-entry-get (point) "header-args"
1306 'inherit))))
1307 (props
1308 (let (val sym)
1309 (org-babel-parse-multiple-vars
1310 (delq nil
1311 (mapcar
1312 (lambda (header-arg)
1313 (and (setq val (org-entry-get (point) header-arg t))
1314 (cons (intern (concat ":" header-arg))
1315 (org-babel-read val))))
1316 (mapcar
1317 #'symbol-name
1318 (mapcar
1319 #'car
1320 (org-babel-combine-header-arg-lists
1321 org-babel-common-header-args-w-values
1322 (progn
1323 (setq sym (intern (concat "org-babel-header-args:" lang)))
1324 (and (boundp sym) (eval sym))))))))))))
1325 (org-babel-merge-params props default-props lang-props))))
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 (org-babel-merge-params
1352 org-babel-default-header-args
1353 (when (boundp lang-headers) (eval lang-headers))
1354 (org-babel-params-from-properties lang)
1355 (org-babel-parse-header-arguments
1356 (org-no-properties (or (match-string 4) ""))))
1357 switches
1358 block-indentation)))
1360 (defun org-babel-parse-inline-src-block-match ()
1361 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
1362 (let* ((lang (org-no-properties (match-string 2)))
1363 (lang-headers (intern (concat "org-babel-default-header-args:" lang))))
1364 (list lang
1365 (org-unescape-code-in-string (org-no-properties (match-string 5)))
1366 (org-babel-merge-params
1367 org-babel-default-inline-header-args
1368 (if (boundp lang-headers) (eval lang-headers) nil)
1369 (org-babel-params-from-properties lang)
1370 (org-babel-parse-header-arguments
1371 (org-no-properties (or (match-string 4) "")))))))
1373 (defun org-babel-balanced-split (string alts)
1374 "Split STRING on instances of ALTS.
1375 ALTS is a cons of two character options where each option may be
1376 either the numeric code of a single character or a list of
1377 character alternatives. For example to split on balanced
1378 instances of \"[ \t]:\" set ALTS to '((32 9) . 58)."
1379 (let* ((matches (lambda (ch spec) (if (listp spec) (member ch spec) (equal spec ch))))
1380 (matched (lambda (ch last)
1381 (if (consp alts)
1382 (and (funcall matches ch (cdr alts))
1383 (funcall matches last (car alts)))
1384 (funcall matches ch alts))))
1385 (balance 0) (last 0)
1386 quote partial lst)
1387 (mapc (lambda (ch) ; split on [], (), "" balanced instances of [ \t]:
1388 (setq balance (+ balance
1389 (cond ((or (equal 91 ch) (equal 40 ch)) 1)
1390 ((or (equal 93 ch) (equal 41 ch)) -1)
1391 (t 0))))
1392 (when (and (equal 34 ch) (not (equal 92 last)))
1393 (setq quote (not quote)))
1394 (setq partial (cons ch partial))
1395 (when (and (= balance 0) (not quote) (funcall matched ch last))
1396 (setq lst (cons (apply #'string (nreverse
1397 (if (consp alts)
1398 (cddr partial)
1399 (cdr partial))))
1400 lst))
1401 (setq partial nil))
1402 (setq last ch))
1403 (string-to-list string))
1404 (nreverse (cons (apply #'string (nreverse partial)) lst))))
1406 (defun org-babel-join-splits-near-ch (ch list)
1407 "Join splits where \"=\" is on either end of the split."
1408 (let ((last= (lambda (str) (= ch (aref str (1- (length str))))))
1409 (first= (lambda (str) (= ch (aref str 0)))))
1410 (reverse
1411 (org-reduce (lambda (acc el)
1412 (let ((head (car acc)))
1413 (if (and head (or (funcall last= head) (funcall first= el)))
1414 (cons (concat head el) (cdr acc))
1415 (cons el acc))))
1416 list :initial-value nil))))
1418 (defun org-babel-parse-header-arguments (arg-string)
1419 "Parse a string of header arguments returning an alist."
1420 (when (> (length arg-string) 0)
1421 (org-babel-parse-multiple-vars
1422 (delq nil
1423 (mapcar
1424 (lambda (arg)
1425 (if (string-match
1426 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1427 arg)
1428 (cons (intern (match-string 1 arg))
1429 (org-babel-read (org-babel-chomp (match-string 2 arg))))
1430 (cons (intern (org-babel-chomp arg)) nil)))
1431 ((lambda (raw)
1432 (cons (car raw) (mapcar (lambda (r) (concat ":" r)) (cdr raw))))
1433 (org-babel-balanced-split arg-string '((32 9) . 58))))))))
1435 (defun org-babel-parse-multiple-vars (header-arguments)
1436 "Expand multiple variable assignments behind a single :var keyword.
1438 This allows expression of multiple variables with one :var as
1439 shown below.
1441 #+PROPERTY: var foo=1, bar=2"
1442 (let (results)
1443 (mapc (lambda (pair)
1444 (if (eq (car pair) :var)
1445 (mapcar (lambda (v) (push (cons :var (org-babel-trim v)) results))
1446 (org-babel-join-splits-near-ch
1447 61 (org-babel-balanced-split (cdr pair) 32)))
1448 (push pair results)))
1449 header-arguments)
1450 (nreverse results)))
1452 (defun org-babel-process-params (params)
1453 "Expand variables in PARAMS and add summary parameters."
1454 (let* ((processed-vars (mapcar (lambda (el)
1455 (if (consp (cdr el))
1456 (cdr el)
1457 (org-babel-ref-parse (cdr el))))
1458 (org-babel-get-header params :var)))
1459 (vars-and-names (if (and (assoc :colname-names params)
1460 (assoc :rowname-names params))
1461 (list processed-vars)
1462 (org-babel-disassemble-tables
1463 processed-vars
1464 (cdr (assoc :hlines params))
1465 (cdr (assoc :colnames params))
1466 (cdr (assoc :rownames params)))))
1467 (raw-result (or (cdr (assoc :results params)) ""))
1468 (result-params (append
1469 (split-string (if (stringp raw-result)
1470 raw-result
1471 (eval raw-result)))
1472 (cdr (assoc :result-params params)))))
1473 (append
1474 (mapcar (lambda (var) (cons :var var)) (car vars-and-names))
1475 (list
1476 (cons :colname-names (or (cdr (assoc :colname-names params))
1477 (cadr vars-and-names)))
1478 (cons :rowname-names (or (cdr (assoc :rowname-names params))
1479 (caddr vars-and-names)))
1480 (cons :result-params result-params)
1481 (cons :result-type (cond ((member "output" result-params) 'output)
1482 ((member "value" result-params) 'value)
1483 (t 'value))))
1484 (org-babel-get-header params :var 'other))))
1486 ;; row and column names
1487 (defun org-babel-del-hlines (table)
1488 "Remove all 'hlines from TABLE."
1489 (remove 'hline table))
1491 (defun org-babel-get-colnames (table)
1492 "Return the column names of TABLE.
1493 Return a cons cell, the `car' of which contains the TABLE less
1494 colnames, and the `cdr' of which contains a list of the column
1495 names."
1496 (if (equal 'hline (nth 1 table))
1497 (cons (cddr table) (car table))
1498 (cons (cdr table) (car table))))
1500 (defun org-babel-get-rownames (table)
1501 "Return the row names of TABLE.
1502 Return a cons cell, the `car' of which contains the TABLE less
1503 colnames, and the `cdr' of which contains a list of the column
1504 names. Note: this function removes any hlines in TABLE."
1505 (let* ((trans (lambda (table) (apply #'mapcar* #'list table)))
1506 (width (apply 'max
1507 (mapcar (lambda (el) (if (listp el) (length el) 0)) table)))
1508 (table (funcall trans (mapcar (lambda (row)
1509 (if (not (equal row 'hline))
1511 (setq row '())
1512 (dotimes (n width)
1513 (setq row (cons 'hline row)))
1514 row))
1515 table))))
1516 (cons (mapcar (lambda (row) (if (equal (car row) 'hline) 'hline row))
1517 (funcall trans (cdr table)))
1518 (remove 'hline (car table)))))
1520 (defun org-babel-put-colnames (table colnames)
1521 "Add COLNAMES to TABLE if they exist."
1522 (if colnames (apply 'list colnames 'hline table) table))
1524 (defun org-babel-put-rownames (table rownames)
1525 "Add ROWNAMES to TABLE if they exist."
1526 (if rownames
1527 (mapcar (lambda (row)
1528 (if (listp row)
1529 (cons (or (pop rownames) "") row)
1530 row)) table)
1531 table))
1533 (defun org-babel-pick-name (names selector)
1534 "Select one out of an alist of row or column names.
1535 SELECTOR can be either a list of names in which case those names
1536 will be returned directly, or an index into the list NAMES in
1537 which case the indexed names will be return."
1538 (if (listp selector)
1539 selector
1540 (when names
1541 (if (and selector (symbolp selector) (not (equal t selector)))
1542 (cdr (assoc selector names))
1543 (if (integerp selector)
1544 (nth (- selector 1) names)
1545 (cdr (car (last names))))))))
1547 (defun org-babel-disassemble-tables (vars hlines colnames rownames)
1548 "Parse tables for further processing.
1549 Process the variables in VARS according to the HLINES,
1550 ROWNAMES and COLNAMES header arguments. Return a list consisting
1551 of the vars, cnames and rnames."
1552 (let (cnames rnames)
1553 (list
1554 (mapcar
1555 (lambda (var)
1556 (when (listp (cdr var))
1557 (when (and (not (equal colnames "no"))
1558 (or colnames (and (equal (nth 1 (cdr var)) 'hline)
1559 (not (member 'hline (cddr (cdr var)))))))
1560 (let ((both (org-babel-get-colnames (cdr var))))
1561 (setq cnames (cons (cons (car var) (cdr both))
1562 cnames))
1563 (setq var (cons (car var) (car both)))))
1564 (when (and rownames (not (equal rownames "no")))
1565 (let ((both (org-babel-get-rownames (cdr var))))
1566 (setq rnames (cons (cons (car var) (cdr both))
1567 rnames))
1568 (setq var (cons (car var) (car both)))))
1569 (when (and hlines (not (equal hlines "yes")))
1570 (setq var (cons (car var) (org-babel-del-hlines (cdr var))))))
1571 var)
1572 vars)
1573 (reverse cnames) (reverse rnames))))
1575 (defun org-babel-reassemble-table (table colnames rownames)
1576 "Add column and row names to a table.
1577 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1578 to the table for reinsertion to org-mode."
1579 (if (listp table)
1580 ((lambda (table)
1581 (if (and colnames (listp (car table)) (= (length (car table))
1582 (length colnames)))
1583 (org-babel-put-colnames table colnames) table))
1584 (if (and rownames (= (length table) (length rownames)))
1585 (org-babel-put-rownames table rownames) table))
1586 table))
1588 (defun org-babel-where-is-src-block-head ()
1589 "Find where the current source block begins.
1590 Return the point at the beginning of the current source
1591 block. Specifically at the beginning of the #+BEGIN_SRC line.
1592 If the point is not on a source block then return nil."
1593 (let ((initial (point)) (case-fold-search t) top bottom)
1595 (save-excursion ;; on a source name line or a #+header line
1596 (beginning-of-line 1)
1597 (and (or (looking-at org-babel-src-name-regexp)
1598 (looking-at org-babel-multi-line-header-regexp))
1599 (progn
1600 (while (and (forward-line 1)
1601 (or (looking-at org-babel-src-name-regexp)
1602 (looking-at org-babel-multi-line-header-regexp))))
1603 (looking-at org-babel-src-block-regexp))
1604 (point)))
1605 (save-excursion ;; on a #+begin_src line
1606 (beginning-of-line 1)
1607 (and (looking-at org-babel-src-block-regexp)
1608 (point)))
1609 (save-excursion ;; inside a src block
1610 (and
1611 (re-search-backward "^[ \t]*#\\+begin_src" nil t) (setq top (point))
1612 (re-search-forward "^[ \t]*#\\+end_src" nil t) (setq bottom (point))
1613 (< top initial) (< initial bottom)
1614 (progn (goto-char top) (beginning-of-line 1)
1615 (looking-at org-babel-src-block-regexp))
1616 (point-marker))))))
1618 ;;;###autoload
1619 (defun org-babel-goto-src-block-head ()
1620 "Go to the beginning of the current code block."
1621 (interactive)
1622 ((lambda (head)
1623 (if head (goto-char head) (error "Not currently in a code block")))
1624 (org-babel-where-is-src-block-head)))
1626 ;;;###autoload
1627 (defun org-babel-goto-named-src-block (name)
1628 "Go to a named source-code block."
1629 (interactive
1630 (let ((completion-ignore-case t)
1631 (case-fold-search t)
1632 (under-point (thing-at-point 'line)))
1633 (list (org-icompleting-read
1634 "source-block name: " (org-babel-src-block-names) nil t
1635 (cond
1636 ;; noweb
1637 ((string-match (org-babel-noweb-wrap) under-point)
1638 (let ((block-name (match-string 1 under-point)))
1639 (string-match "[^(]*" block-name)
1640 (match-string 0 block-name)))
1641 ;; #+call:
1642 ((string-match org-babel-lob-one-liner-regexp under-point)
1643 (let ((source-info (car (org-babel-lob-get-info))))
1644 (if (string-match "^\\([^\\[]+?\\)\\(\\[.*\\]\\)?(" source-info)
1645 (let ((source-name (match-string 1 source-info)))
1646 source-name))))
1647 ;; #+results:
1648 ((string-match (concat "#\\+" org-babel-results-keyword
1649 "\\:\s+\\([^\\(]*\\)") under-point)
1650 (match-string 1 under-point))
1651 ;; symbol-at-point
1652 ((and (thing-at-point 'symbol))
1653 (org-babel-find-named-block (thing-at-point 'symbol))
1654 (thing-at-point 'symbol))
1655 (""))))))
1656 (let ((point (org-babel-find-named-block name)))
1657 (if point
1658 ;; taken from `org-open-at-point'
1659 (progn (org-mark-ring-push) (goto-char point) (org-show-context))
1660 (message "source-code block '%s' not found in this buffer" name))))
1662 (defun org-babel-find-named-block (name)
1663 "Find a named source-code block.
1664 Return the location of the source block identified by source
1665 NAME, or nil if no such block exists. Set match data according to
1666 org-babel-named-src-block-regexp."
1667 (save-excursion
1668 (let ((case-fold-search t)
1669 (regexp (org-babel-named-src-block-regexp-for-name name)) msg)
1670 (goto-char (point-min))
1671 (when (or (re-search-forward regexp nil t)
1672 (re-search-backward regexp nil t))
1673 (match-beginning 0)))))
1675 (defun org-babel-src-block-names (&optional file)
1676 "Returns the names of source blocks in FILE or the current buffer."
1677 (save-excursion
1678 (when file (find-file file)) (goto-char (point-min))
1679 (let ((case-fold-search t) names)
1680 (while (re-search-forward org-babel-src-name-w-name-regexp nil t)
1681 (setq names (cons (match-string 3) names)))
1682 names)))
1684 ;;;###autoload
1685 (defun org-babel-goto-named-result (name)
1686 "Go to a named result."
1687 (interactive
1688 (let ((completion-ignore-case t))
1689 (list (org-icompleting-read "source-block name: "
1690 (org-babel-result-names) nil t))))
1691 (let ((point (org-babel-find-named-result name)))
1692 (if point
1693 ;; taken from `org-open-at-point'
1694 (progn (goto-char point) (org-show-context))
1695 (message "result '%s' not found in this buffer" name))))
1697 (defun org-babel-find-named-result (name &optional point)
1698 "Find a named result.
1699 Return the location of the result named NAME in the current
1700 buffer or nil if no such result exists."
1701 (save-excursion
1702 (let ((case-fold-search t))
1703 (goto-char (or point (point-min)))
1704 (catch 'is-a-code-block
1705 (when (re-search-forward
1706 (concat org-babel-result-regexp
1707 "[ \t]" (regexp-quote name) "[ \t]*[\n\f\v\r]") nil t)
1708 (when (and (string= "name" (downcase (match-string 1)))
1709 (or (beginning-of-line 1)
1710 (looking-at org-babel-src-block-regexp)
1711 (looking-at org-babel-multi-line-header-regexp)))
1712 (throw 'is-a-code-block (org-babel-find-named-result name (point))))
1713 (beginning-of-line 0) (point))))))
1715 (defun org-babel-result-names (&optional file)
1716 "Returns the names of results in FILE or the current buffer."
1717 (save-excursion
1718 (when file (find-file file)) (goto-char (point-min))
1719 (let ((case-fold-search t) names)
1720 (while (re-search-forward org-babel-result-w-name-regexp nil t)
1721 (setq names (cons (match-string 4) names)))
1722 names)))
1724 ;;;###autoload
1725 (defun org-babel-next-src-block (&optional arg)
1726 "Jump to the next source block.
1727 With optional prefix argument ARG, jump forward ARG many source blocks."
1728 (interactive "p")
1729 (org-next-block arg nil org-babel-src-block-regexp))
1731 ;;;###autoload
1732 (defun org-babel-previous-src-block (&optional arg)
1733 "Jump to the previous source block.
1734 With optional prefix argument ARG, jump backward ARG many source blocks."
1735 (interactive "p")
1736 (org-previous-block arg org-babel-src-block-regexp))
1738 (defvar org-babel-load-languages)
1740 ;;;###autoload
1741 (defun org-babel-mark-block ()
1742 "Mark current src block."
1743 (interactive)
1744 ((lambda (head)
1745 (when head
1746 (save-excursion
1747 (goto-char head)
1748 (looking-at org-babel-src-block-regexp))
1749 (push-mark (match-end 5) nil t)
1750 (goto-char (match-beginning 5))))
1751 (org-babel-where-is-src-block-head)))
1753 (defun org-babel-demarcate-block (&optional arg)
1754 "Wrap or split the code in the region or on the point.
1755 When called from inside of a code block the current block is
1756 split. When called from outside of a code block a new code block
1757 is created. In both cases if the region is demarcated and if the
1758 region is not active then the point is demarcated."
1759 (interactive "P")
1760 (let ((info (org-babel-get-src-block-info 'light))
1761 (headers (progn (org-babel-where-is-src-block-head)
1762 (match-string 4)))
1763 (stars (concat (make-string (or (org-current-level) 1) ?*) " ")))
1764 (if info
1765 (mapc
1766 (lambda (place)
1767 (save-excursion
1768 (goto-char place)
1769 (let ((lang (nth 0 info))
1770 (indent (make-string (nth 5 info) ? )))
1771 (when (string-match "^[[:space:]]*$"
1772 (buffer-substring (point-at-bol)
1773 (point-at-eol)))
1774 (delete-region (point-at-bol) (point-at-eol)))
1775 (insert (concat
1776 (if (looking-at "^") "" "\n")
1777 indent "#+end_src\n"
1778 (if arg stars indent) "\n"
1779 indent "#+begin_src " lang
1780 (if (> (length headers) 1)
1781 (concat " " headers) headers)
1782 (if (looking-at "[\n\r]")
1784 (concat "\n" (make-string (current-column) ? )))))))
1785 (move-end-of-line 2))
1786 (sort (if (org-region-active-p) (list (mark) (point)) (list (point))) #'>))
1787 (let ((start (point))
1788 (lang (org-icompleting-read "Lang: "
1789 (mapcar (lambda (el) (symbol-name (car el)))
1790 org-babel-load-languages)))
1791 (body (delete-and-extract-region
1792 (if (org-region-active-p) (mark) (point)) (point))))
1793 (insert (concat (if (looking-at "^") "" "\n")
1794 (if arg (concat stars "\n") "")
1795 "#+begin_src " lang "\n"
1796 body
1797 (if (or (= (length body) 0)
1798 (string-match "[\r\n]$" body)) "" "\n")
1799 "#+end_src\n"))
1800 (goto-char start) (move-end-of-line 1)))))
1802 (defvar org-babel-lob-one-liner-regexp)
1803 (defun org-babel-where-is-src-block-result (&optional insert info hash indent)
1804 "Find where the current source block results begin.
1805 Return the point at the beginning of the result of the current
1806 source block. Specifically at the beginning of the results line.
1807 If no result exists for this block then create a results line
1808 following the source block."
1809 (save-excursion
1810 (let* ((case-fold-search t)
1811 (on-lob-line (save-excursion
1812 (beginning-of-line 1)
1813 (looking-at org-babel-lob-one-liner-regexp)))
1814 (inlinep (when (org-babel-get-inline-src-block-matches)
1815 (match-end 0)))
1816 (name (if on-lob-line
1817 (mapconcat #'identity (butlast (org-babel-lob-get-info))
1819 (nth 4 (or info (org-babel-get-src-block-info 'light)))))
1820 (head (unless on-lob-line (org-babel-where-is-src-block-head)))
1821 found beg end)
1822 (when head (goto-char head))
1823 (org-with-wide-buffer
1824 (setq
1825 found ;; was there a result (before we potentially insert one)
1827 inlinep
1828 (and
1829 ;; named results:
1830 ;; - return t if it is found, else return nil
1831 ;; - if it does not need to be rebuilt, then don't set end
1832 ;; - if it does need to be rebuilt then do set end
1833 name (setq beg (org-babel-find-named-result name))
1834 (prog1 beg
1835 (when (and hash (not (string= hash (match-string 5))))
1836 (goto-char beg) (setq end beg) ;; beginning of result
1837 (forward-line 1)
1838 (delete-region end (org-babel-result-end)) nil)))
1839 (and
1840 ;; unnamed results:
1841 ;; - return t if it is found, else return nil
1842 ;; - if it is found, and the hash doesn't match, delete and set end
1843 (or on-lob-line (re-search-forward "^[ \t]*#\\+end_src" nil t))
1844 (progn (end-of-line 1)
1845 (if (eobp) (insert "\n") (forward-char 1))
1846 (setq end (point))
1847 (or (and
1848 (not name)
1849 (progn ;; unnamed results line already exists
1850 (catch 'non-comment
1851 (while (re-search-forward "[^ \f\t\n\r\v]" nil t)
1852 (beginning-of-line 1)
1853 (cond
1854 ((looking-at (concat org-babel-result-regexp "\n"))
1855 (throw 'non-comment t))
1856 ((looking-at "^[ \t]*#") (end-of-line 1))
1857 (t (throw 'non-comment nil))))))
1858 (let ((this-hash (match-string 5)))
1859 (prog1 (point)
1860 ;; must remove and rebuild if hash!=old-hash
1861 (if (and hash (not (string= hash this-hash)))
1862 (prog1 nil
1863 (forward-line 1)
1864 (delete-region
1865 end (org-babel-result-end)))
1866 (setq end nil)))))))))))
1867 (if (not (and insert end)) found
1868 (goto-char end)
1869 (unless beg
1870 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1871 (insert (concat
1872 (when (wholenump indent) (make-string indent ? ))
1873 "#+" org-babel-results-keyword
1874 (when hash
1875 (if org-babel-hash-show-time
1876 (concat
1877 "["(format-time-string "<%Y-%m-%d %H:%M:%S>")" "hash"]")
1878 (concat "["hash"]")))
1880 (when name (concat " " name)) "\n"))
1881 (unless beg (insert "\n") (backward-char))
1882 (beginning-of-line 0)
1883 (if hash (org-babel-hide-hash))
1884 (point)))))
1886 (defvar org-block-regexp)
1887 (defun org-babel-read-result ()
1888 "Read the result at `point' into emacs-lisp."
1889 (let ((case-fold-search t) result-string)
1890 (cond
1891 ((org-at-table-p) (org-babel-read-table))
1892 ((org-at-item-p) (org-babel-read-list))
1893 ((looking-at org-bracket-link-regexp) (org-babel-read-link))
1894 ((looking-at org-block-regexp) (org-babel-trim (match-string 4)))
1895 ((looking-at "^[ \t]*: ")
1896 (setq result-string
1897 (org-babel-trim
1898 (mapconcat (lambda (line)
1899 (if (and (> (length line) 1)
1900 (string-match "^[ \t]*: \\(.+\\)" line))
1901 (match-string 1 line)
1902 line))
1903 (split-string
1904 (buffer-substring
1905 (point) (org-babel-result-end)) "[\r\n]+")
1906 "\n")))
1907 (or (org-babel-number-p result-string) result-string))
1908 ((looking-at org-babel-result-regexp)
1909 (save-excursion (forward-line 1) (org-babel-read-result))))))
1911 (defun org-babel-read-table ()
1912 "Read the table at `point' into emacs-lisp."
1913 (mapcar (lambda (row)
1914 (if (and (symbolp row) (equal row 'hline)) row
1915 (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval)) row)))
1916 (org-table-to-lisp)))
1918 (defun org-babel-read-list ()
1919 "Read the list at `point' into emacs-lisp."
1920 (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval))
1921 (mapcar #'cadr (cdr (org-list-parse-list)))))
1923 (defvar org-link-types-re)
1924 (defun org-babel-read-link ()
1925 "Read the link at `point' into emacs-lisp.
1926 If the path of the link is a file path it is expanded using
1927 `expand-file-name'."
1928 (let* ((case-fold-search t)
1929 (raw (and (looking-at org-bracket-link-regexp)
1930 (org-no-properties (match-string 1))))
1931 (type (and (string-match org-link-types-re raw)
1932 (match-string 1 raw))))
1933 (cond
1934 ((not type) (expand-file-name raw))
1935 ((string= type "file")
1936 (and (string-match "file\\(.*\\):\\(.+\\)" raw)
1937 (expand-file-name (match-string 2 raw))))
1938 (t raw))))
1940 (defun org-babel-format-result (result &optional sep)
1941 "Format RESULT for writing to file."
1942 (let ((echo-res (lambda (r) (if (stringp r) r (format "%S" r)))))
1943 (if (listp result)
1944 ;; table result
1945 (orgtbl-to-generic
1946 result (list :sep (or sep "\t") :fmt echo-res))
1947 ;; scalar result
1948 (funcall echo-res result))))
1950 (defun org-babel-insert-result
1951 (result &optional result-params info hash indent lang)
1952 "Insert RESULT into the current buffer.
1953 By default RESULT is inserted after the end of the
1954 current source block. With optional argument RESULT-PARAMS
1955 controls insertion of results in the org-mode file.
1956 RESULT-PARAMS can take the following values:
1958 replace - (default option) insert results after the source block
1959 replacing any previously inserted results
1961 silent -- no results are inserted into the Org-mode buffer but
1962 the results are echoed to the minibuffer and are
1963 ingested by Emacs (a potentially time consuming
1964 process)
1966 file ---- the results are interpreted as a file path, and are
1967 inserted into the buffer using the Org-mode file syntax
1969 list ---- the results are interpreted as an Org-mode list.
1971 raw ----- results are added directly to the Org-mode file. This
1972 is a good option if you code block will output org-mode
1973 formatted text.
1975 drawer -- results are added directly to the Org-mode file as with
1976 \"raw\", but are wrapped in a RESULTS drawer, allowing
1977 them to later be replaced or removed automatically.
1979 org ----- results are added inside of a \"#+BEGIN_SRC org\" block.
1980 They are not comma-escaped when inserted, but Org syntax
1981 here will be discarded when exporting the file.
1983 html ---- results are added inside of a #+BEGIN_HTML block. This
1984 is a good option if you code block will output html
1985 formatted text.
1987 latex --- results are added inside of a #+BEGIN_LATEX block.
1988 This is a good option if you code block will output
1989 latex formatted text.
1991 code ---- the results are extracted in the syntax of the source
1992 code of the language being evaluated and are added
1993 inside of a #+BEGIN_SRC block with the source-code
1994 language set appropriately. Note this relies on the
1995 optional LANG argument."
1996 (if (stringp result)
1997 (progn
1998 (setq result (org-no-properties result))
1999 (when (member "file" result-params)
2000 (setq result (org-babel-result-to-file
2001 result (when (assoc :file-desc (nth 2 info))
2002 (or (cdr (assoc :file-desc (nth 2 info)))
2003 result))))))
2004 (unless (listp result) (setq result (format "%S" result))))
2005 (if (and result-params (member "silent" result-params))
2006 (progn
2007 (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
2008 result)
2009 (save-excursion
2010 (let* ((inlinep
2011 (save-excursion
2012 (when (or (org-babel-get-inline-src-block-matches)
2013 (org-babel-get-lob-one-liner-matches))
2014 (goto-char (match-end 0))
2015 (insert (if (listp result) "\n" " "))
2016 (point))))
2017 (existing-result (unless inlinep
2018 (org-babel-where-is-src-block-result
2019 t info hash indent)))
2020 (results-switches
2021 (cdr (assoc :results_switches (nth 2 info))))
2022 (visible-beg (copy-marker (point-min)))
2023 (visible-end (copy-marker (point-max)))
2024 ;; When results exist outside of the current visible
2025 ;; region of the buffer, be sure to widen buffer to
2026 ;; update them.
2027 (outside-scope-p (and existing-result
2028 (or (> visible-beg existing-result)
2029 (<= visible-end existing-result))))
2030 beg end)
2031 (when (and (stringp result) ; ensure results end in a newline
2032 (not inlinep)
2033 (> (length result) 0)
2034 (not (or (string-equal (substring result -1) "\n")
2035 (string-equal (substring result -1) "\r"))))
2036 (setq result (concat result "\n")))
2037 (unwind-protect
2038 (progn
2039 (when outside-scope-p (widen))
2040 (if (not existing-result)
2041 (setq beg (or inlinep (point)))
2042 (goto-char existing-result)
2043 (save-excursion
2044 (re-search-forward "#" nil t)
2045 (setq indent (- (current-column) 1)))
2046 (forward-line 1)
2047 (setq beg (point))
2048 (cond
2049 ((member "replace" result-params)
2050 (delete-region (point) (org-babel-result-end)))
2051 ((member "append" result-params)
2052 (goto-char (org-babel-result-end)) (setq beg (point-marker)))
2053 ((member "prepend" result-params)))) ; already there
2054 (setq results-switches
2055 (if results-switches (concat " " results-switches) ""))
2056 (let ((wrap (lambda (start finish &optional no-escape)
2057 (goto-char end) (insert (concat finish "\n"))
2058 (goto-char beg) (insert (concat start "\n"))
2059 (unless no-escape
2060 (org-escape-code-in-region (min (point) end) end))
2061 (goto-char end) (goto-char (point-at-eol))
2062 (setq end (point-marker))))
2063 (proper-list-p (lambda (it) (and (listp it) (null (cdr (last it)))))))
2064 ;; insert results based on type
2065 (cond
2066 ;; do nothing for an empty result
2067 ((null result))
2068 ;; insert a list if preferred
2069 ((member "list" result-params)
2070 (insert
2071 (org-babel-trim
2072 (org-list-to-generic
2073 (cons 'unordered
2074 (mapcar
2075 (lambda (el) (list nil (if (stringp el) el (format "%S" el))))
2076 (if (listp result) result (split-string result "\n" t))))
2077 '(:splicep nil :istart "- " :iend "\n")))
2078 "\n"))
2079 ;; assume the result is a table if it's not a string
2080 ((funcall proper-list-p result)
2081 (goto-char beg)
2082 (insert (concat (orgtbl-to-orgtbl
2083 (if (or (eq 'hline (car result))
2084 (and (listp (car result))
2085 (listp (cdr (car result)))))
2086 result (list result))
2087 '(:fmt (lambda (cell) (format "%s" cell)))) "\n"))
2088 (goto-char beg) (when (org-at-table-p) (org-table-align)))
2089 ((and (listp result) (not (funcall proper-list-p result)))
2090 (insert (format "%s\n" result)))
2091 ((member "file" result-params)
2092 (when inlinep (goto-char inlinep))
2093 (insert result))
2094 (t (goto-char beg) (insert result)))
2095 (when (funcall proper-list-p result) (goto-char (org-table-end)))
2096 (setq end (point-marker))
2097 ;; possibly wrap result
2098 (cond
2099 ((assoc :wrap (nth 2 info))
2100 (let ((name (or (cdr (assoc :wrap (nth 2 info))) "RESULTS")))
2101 (funcall wrap (concat "#+BEGIN_" name)
2102 (concat "#+END_" (car (org-split-string name))))))
2103 ((member "html" result-params)
2104 (funcall wrap "#+BEGIN_HTML" "#+END_HTML"))
2105 ((member "latex" result-params)
2106 (funcall wrap "#+BEGIN_LaTeX" "#+END_LaTeX"))
2107 ((member "org" result-params)
2108 (goto-char beg) (if (org-at-table-p) (org-cycle))
2109 (funcall wrap "#+BEGIN_SRC org" "#+END_SRC"))
2110 ((member "code" result-params)
2111 (funcall wrap (format "#+BEGIN_SRC %s%s" (or lang "none") results-switches)
2112 "#+END_SRC"))
2113 ((member "raw" result-params)
2114 (goto-char beg) (if (org-at-table-p) (org-cycle)))
2115 ((or (member "drawer" result-params)
2116 ;; Stay backward compatible with <7.9.2
2117 (member "wrap" result-params))
2118 (goto-char beg) (if (org-at-table-p) (org-cycle))
2119 (funcall wrap ":RESULTS:" ":END:" 'no-escape))
2120 ((and (not (funcall proper-list-p result))
2121 (not (member "file" result-params)))
2122 (org-babel-examplize-region beg end results-switches)
2123 (setq end (point)))))
2124 ;; possibly indent the results to match the #+results line
2125 (when (and (not inlinep) (numberp indent) indent (> indent 0)
2126 ;; in this case `table-align' does the work for us
2127 (not (and (listp result)
2128 (member "append" result-params))))
2129 (indent-rigidly beg end indent))
2130 (if (null result)
2131 (if (member "value" result-params)
2132 (message "Code block returned no value.")
2133 (message "Code block produced no output."))
2134 (message "Code block evaluation complete.")))
2135 (when outside-scope-p (narrow-to-region visible-beg visible-end))
2136 (set-marker visible-beg nil)
2137 (set-marker visible-end nil))))))
2139 (defun org-babel-remove-result (&optional info)
2140 "Remove the result of the current source block."
2141 (interactive)
2142 (let ((location (org-babel-where-is-src-block-result nil info)) start)
2143 (when location
2144 (setq start (- location 1))
2145 (save-excursion
2146 (goto-char location) (forward-line 1)
2147 (delete-region start (org-babel-result-end))))))
2149 (defun org-babel-result-end ()
2150 "Return the point at the end of the current set of results."
2151 (save-excursion
2152 (cond
2153 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
2154 ((org-at-item-p) (let* ((struct (org-list-struct))
2155 (prvs (org-list-prevs-alist struct)))
2156 (org-list-get-list-end (point-at-bol) struct prvs)))
2157 ((let ((case-fold-search t)) (looking-at "^\\([ \t]*\\):results:"))
2158 (progn (re-search-forward (concat "^" (match-string 1) ":END:"))
2159 (forward-char 1) (point)))
2161 (let ((case-fold-search t))
2162 (if (looking-at (concat "[ \t]*#\\+begin_\\([^ \t\n\r]+\\)"))
2163 (progn (re-search-forward (concat "[ \t]*#\\+end_" (match-string 1))
2164 nil t)
2165 (forward-char 1))
2166 (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
2167 (forward-line 1))))
2168 (point)))))
2170 (defun org-babel-result-to-file (result &optional description)
2171 "Convert RESULT into an `org-mode' link with optional DESCRIPTION.
2172 If the `default-directory' is different from the containing
2173 file's directory then expand relative links."
2174 (when (stringp result)
2175 (format "[[file:%s]%s]"
2176 (if (and default-directory
2177 buffer-file-name
2178 (not (string= (expand-file-name default-directory)
2179 (expand-file-name
2180 (file-name-directory buffer-file-name)))))
2181 (expand-file-name result default-directory)
2182 result)
2183 (if description (concat "[" description "]") ""))))
2185 (defvar org-babel-capitalize-examplize-region-markers nil
2186 "Make true to capitalize begin/end example markers inserted by code blocks.")
2188 (defun org-babel-examplize-region (beg end &optional results-switches)
2189 "Comment out region using the inline '==' or ': ' org example quote."
2190 (interactive "*r")
2191 (let ((chars-between (lambda (b e)
2192 (not (string-match "^[\\s]*$" (buffer-substring b e)))))
2193 (maybe-cap (lambda (str) (if org-babel-capitalize-examplize-region-markers
2194 (upcase str) str))))
2195 (if (or (funcall chars-between (save-excursion (goto-char beg) (point-at-bol)) beg)
2196 (funcall chars-between end (save-excursion (goto-char end) (point-at-eol))))
2197 (save-excursion
2198 (goto-char beg)
2199 (insert (format org-babel-inline-result-wrap
2200 (prog1 (buffer-substring beg end)
2201 (delete-region beg end)))))
2202 (let ((size (count-lines beg end)))
2203 (save-excursion
2204 (cond ((= size 0)) ; do nothing for an empty result
2205 ((< size org-babel-min-lines-for-block-output)
2206 (goto-char beg)
2207 (dotimes (n size)
2208 (beginning-of-line 1) (insert ": ") (forward-line 1)))
2210 (goto-char beg)
2211 (insert (if results-switches
2212 (format "%s%s\n"
2213 (funcall maybe-cap "#+begin_example")
2214 results-switches)
2215 (funcall maybe-cap "#+begin_example\n")))
2216 (if (markerp end) (goto-char end) (forward-char (- end beg)))
2217 (insert (funcall maybe-cap "#+end_example\n")))))))))
2219 (defun org-babel-update-block-body (new-body)
2220 "Update the body of the current code block to NEW-BODY."
2221 (if (not (org-babel-where-is-src-block-head))
2222 (error "Not in a source block")
2223 (save-match-data
2224 (replace-match (concat (org-babel-trim new-body) "\n") nil t nil 5))
2225 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
2227 (defun org-babel-merge-params (&rest plists)
2228 "Combine all parameter association lists in PLISTS.
2229 Later elements of PLISTS override the values of previous elements.
2230 This takes into account some special considerations for certain
2231 parameters when merging lists."
2232 (let* ((results-exclusive-groups
2233 (mapcar (lambda (group) (mapcar #'symbol-name group))
2234 (cdr (assoc 'results org-babel-common-header-args-w-values))))
2235 (exports-exclusive-groups
2236 (mapcar (lambda (group) (mapcar #'symbol-name group))
2237 (cdr (assoc 'exports org-babel-common-header-args-w-values))))
2238 (variable-index 0)
2239 (e-merge (lambda (exclusive-groups &rest result-params)
2240 ;; maintain exclusivity of mutually exclusive parameters
2241 (let (output)
2242 (mapc (lambda (new-params)
2243 (mapc (lambda (new-param)
2244 (mapc (lambda (exclusive-group)
2245 (when (member new-param exclusive-group)
2246 (mapcar (lambda (excluded-param)
2247 (setq output
2248 (delete
2249 excluded-param
2250 output)))
2251 exclusive-group)))
2252 exclusive-groups)
2253 (setq output (org-uniquify
2254 (cons new-param output))))
2255 new-params))
2256 result-params)
2257 output)))
2258 params results exports tangle noweb cache vars shebang comments padline)
2260 (mapc
2261 (lambda (plist)
2262 (mapc
2263 (lambda (pair)
2264 (case (car pair)
2265 (:var
2266 (let ((name (if (listp (cdr pair))
2267 (cadr pair)
2268 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
2269 (cdr pair))
2270 (intern (match-string 1 (cdr pair)))))))
2271 (if name
2272 (setq vars
2273 (append
2274 (if (member name (mapcar #'car vars))
2275 (delq nil
2276 (mapcar
2277 (lambda (p)
2278 (unless (equal (car p) name) p))
2279 vars))
2280 vars)
2281 (list (cons name pair))))
2282 ;; if no name is given and we already have named variables
2283 ;; then assign to named variables in order
2284 (if (and vars (nth variable-index vars))
2285 (prog1 (setf (cddr (nth variable-index vars))
2286 (concat (symbol-name
2287 (car (nth variable-index vars)))
2288 "=" (cdr pair)))
2289 (incf variable-index))
2290 (error "Variable \"%s\" must be assigned a default value"
2291 (cdr pair))))))
2292 (:results
2293 (setq results (funcall e-merge results-exclusive-groups
2294 results
2295 (split-string
2296 (let ((r (cdr pair)))
2297 (if (stringp r) r (eval r)))))))
2298 (:file
2299 (when (cdr pair)
2300 (setq results (funcall e-merge results-exclusive-groups
2301 results '("file")))
2302 (unless (or (member "both" exports)
2303 (member "none" exports)
2304 (member "code" exports))
2305 (setq exports (funcall e-merge exports-exclusive-groups
2306 exports '("results"))))
2307 (setq params (cons pair (assq-delete-all (car pair) params)))))
2308 (:exports
2309 (setq exports (funcall e-merge exports-exclusive-groups
2310 exports (split-string (cdr pair)))))
2311 (:tangle ;; take the latest -- always overwrite
2312 (setq tangle (or (list (cdr pair)) tangle)))
2313 (:noweb
2314 (setq noweb (funcall e-merge
2315 '(("yes" "no" "tangle" "no-export"
2316 "strip-export" "eval"))
2317 noweb
2318 (split-string (or (cdr pair) "")))))
2319 (:cache
2320 (setq cache (funcall e-merge '(("yes" "no")) cache
2321 (split-string (or (cdr pair) "")))))
2322 (:padline
2323 (setq padline (funcall e-merge '(("yes" "no")) padline
2324 (split-string (or (cdr pair) "")))))
2325 (:shebang ;; take the latest -- always overwrite
2326 (setq shebang (or (list (cdr pair)) shebang)))
2327 (:comments
2328 (setq comments (funcall e-merge '(("yes" "no")) comments
2329 (split-string (or (cdr pair) "")))))
2330 (t ;; replace: this covers e.g. :session
2331 (setq params (cons pair (assq-delete-all (car pair) params))))))
2332 plist))
2333 plists)
2334 (setq vars (reverse vars))
2335 (while vars (setq params (cons (cons :var (cddr (pop vars))) params)))
2336 (mapc
2337 (lambda (hd)
2338 (let ((key (intern (concat ":" (symbol-name hd))))
2339 (val (eval hd)))
2340 (setf params (cons (cons key (mapconcat 'identity val " ")) params))))
2341 '(results exports tangle noweb padline cache shebang comments))
2342 params))
2344 (defvar org-babel-use-quick-and-dirty-noweb-expansion nil
2345 "Set to true to use regular expressions to expand noweb references.
2346 This results in much faster noweb reference expansion but does
2347 not properly allow code blocks to inherit the \":noweb-ref\"
2348 header argument from buffer or subtree wide properties.")
2350 (defun org-babel-noweb-p (params context)
2351 "Check if PARAMS require expansion in CONTEXT.
2352 CONTEXT may be one of :tangle, :export or :eval."
2353 (let* (intersect
2354 (intersect (lambda (as bs)
2355 (when as
2356 (if (member (car as) bs)
2357 (car as)
2358 (funcall intersect (cdr as) bs))))))
2359 (funcall intersect (case context
2360 (:tangle '("yes" "tangle" "no-export" "strip-export"))
2361 (:eval '("yes" "no-export" "strip-export" "eval"))
2362 (:export '("yes")))
2363 (split-string (or (cdr (assoc :noweb params)) "")))))
2365 (defun org-babel-expand-noweb-references (&optional info parent-buffer)
2366 "Expand Noweb references in the body of the current source code block.
2368 For example the following reference would be replaced with the
2369 body of the source-code block named 'example-block'.
2371 <<example-block>>
2373 Note that any text preceding the <<foo>> construct on a line will
2374 be interposed between the lines of the replacement text. So for
2375 example if <<foo>> is placed behind a comment, then the entire
2376 replacement text will also be commented.
2378 This function must be called from inside of the buffer containing
2379 the source-code block which holds BODY.
2381 In addition the following syntax can be used to insert the
2382 results of evaluating the source-code block named 'example-block'.
2384 <<example-block()>>
2386 Any optional arguments can be passed to example-block by placing
2387 the arguments inside the parenthesis following the convention
2388 defined by `org-babel-lob'. For example
2390 <<example-block(a=9)>>
2392 would set the value of argument \"a\" equal to \"9\". Note that
2393 these arguments are not evaluated in the current source-code
2394 block but are passed literally to the \"example-block\"."
2395 (let* ((parent-buffer (or parent-buffer (current-buffer)))
2396 (info (or info (org-babel-get-src-block-info 'light)))
2397 (lang (nth 0 info))
2398 (body (nth 1 info))
2399 (ob-nww-start org-babel-noweb-wrap-start)
2400 (ob-nww-end org-babel-noweb-wrap-end)
2401 (comment (string= "noweb" (cdr (assoc :comments (nth 2 info)))))
2402 (rx-prefix (concat "\\(" org-babel-src-name-regexp "\\|"
2403 ":noweb-ref[ \t]+" "\\)"))
2404 (new-body "")
2405 (nb-add (lambda (text) (setq new-body (concat new-body text))))
2406 (c-wrap (lambda (text)
2407 (with-temp-buffer
2408 (funcall (intern (concat lang "-mode")))
2409 (comment-region (point) (progn (insert text) (point)))
2410 (org-babel-trim (buffer-string)))))
2411 index source-name evaluate prefix blocks-in-buffer)
2412 (with-temp-buffer
2413 (org-set-local 'org-babel-noweb-wrap-start ob-nww-start)
2414 (org-set-local 'org-babel-noweb-wrap-end ob-nww-end)
2415 (insert body) (goto-char (point-min))
2416 (setq index (point))
2417 (while (and (re-search-forward (org-babel-noweb-wrap) nil t))
2418 (save-match-data (setf source-name (match-string 1)))
2419 (save-match-data (setq evaluate (string-match "\(.*\)" source-name)))
2420 (save-match-data
2421 (setq prefix
2422 (buffer-substring (match-beginning 0)
2423 (save-excursion
2424 (beginning-of-line 1) (point)))))
2425 ;; add interval to new-body (removing noweb reference)
2426 (goto-char (match-beginning 0))
2427 (funcall nb-add (buffer-substring index (point)))
2428 (goto-char (match-end 0))
2429 (setq index (point))
2430 (funcall nb-add
2431 (with-current-buffer parent-buffer
2432 (save-restriction
2433 (widen)
2434 (mapconcat ;; interpose PREFIX between every line
2435 #'identity
2436 (split-string
2437 (if evaluate
2438 (let ((raw (org-babel-ref-resolve source-name)))
2439 (if (stringp raw) raw (format "%S" raw)))
2441 ;; retrieve from the library of babel
2442 (nth 2 (assoc (intern source-name)
2443 org-babel-library-of-babel))
2444 ;; return the contents of headlines literally
2445 (save-excursion
2446 (when (org-babel-ref-goto-headline-id source-name)
2447 (org-babel-ref-headline-body)))
2448 ;; find the expansion of reference in this buffer
2449 (let ((rx (concat rx-prefix source-name "[ \t\n]"))
2450 expansion)
2451 (save-excursion
2452 (goto-char (point-min))
2453 (if org-babel-use-quick-and-dirty-noweb-expansion
2454 (while (re-search-forward rx nil t)
2455 (let* ((i (org-babel-get-src-block-info 'light))
2456 (body (org-babel-expand-noweb-references i))
2457 (sep (or (cdr (assoc :noweb-sep (nth 2 i)))
2458 "\n"))
2459 (full (if comment
2460 ((lambda (cs)
2461 (concat (funcall c-wrap (car cs)) "\n"
2462 body "\n"
2463 (funcall c-wrap (cadr cs))))
2464 (org-babel-tangle-comment-links i))
2465 body)))
2466 (setq expansion (cons sep (cons full expansion)))))
2467 (org-babel-map-src-blocks nil
2468 (let ((i (org-babel-get-src-block-info 'light)))
2469 (when (equal (or (cdr (assoc :noweb-ref (nth 2 i)))
2470 (nth 4 i))
2471 source-name)
2472 (let* ((body (org-babel-expand-noweb-references i))
2473 (sep (or (cdr (assoc :noweb-sep (nth 2 i)))
2474 "\n"))
2475 (full (if comment
2476 ((lambda (cs)
2477 (concat (funcall c-wrap (car cs)) "\n"
2478 body "\n"
2479 (funcall c-wrap (cadr cs))))
2480 (org-babel-tangle-comment-links i))
2481 body)))
2482 (setq expansion
2483 (cons sep (cons full expansion)))))))))
2484 (and expansion
2485 (mapconcat #'identity (nreverse (cdr expansion)) "")))
2486 ;; possibly raise an error if named block doesn't exist
2487 (if (member lang org-babel-noweb-error-langs)
2488 (error "%s" (concat
2489 (org-babel-noweb-wrap source-name)
2490 "could not be resolved (see "
2491 "`org-babel-noweb-error-langs')"))
2492 "")))
2493 "[\n\r]") (concat "\n" prefix))))))
2494 (funcall nb-add (buffer-substring index (point-max))))
2495 new-body))
2497 (defun org-babel-script-escape (str &optional force)
2498 "Safely convert tables into elisp lists."
2499 (let (in-single in-double out)
2500 ((lambda (escaped) (condition-case nil (org-babel-read escaped) (error escaped)))
2501 (if (or force
2502 (and (stringp str)
2503 (> (length str) 2)
2504 (or (and (string-equal "[" (substring str 0 1))
2505 (string-equal "]" (substring str -1)))
2506 (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 (org-babel-read
2511 (concat
2513 (progn
2514 (mapc
2515 (lambda (ch)
2516 (setq
2518 (case ch
2519 (91 (if (or in-double in-single) ; [
2520 (cons 91 out)
2521 (cons 40 out)))
2522 (93 (if (or in-double in-single) ; ]
2523 (cons 93 out)
2524 (cons 41 out)))
2525 (123 (if (or in-double in-single) ; {
2526 (cons 123 out)
2527 (cons 40 out)))
2528 (125 (if (or in-double in-single) ; }
2529 (cons 125 out)
2530 (cons 41 out)))
2531 (44 (if (or in-double in-single) ; ,
2532 (cons 44 out) (cons 32 out)))
2533 (39 (if in-double ; '
2534 (cons 39 out)
2535 (setq in-single (not in-single)) (cons 34 out)))
2536 (34 (if in-single ; "
2537 (append (list 34 32) out)
2538 (setq in-double (not in-double)) (cons 34 out)))
2539 (t (cons ch out)))))
2540 (string-to-list str))
2541 (apply #'string (reverse out)))))
2542 str))))
2544 (defun org-babel-read (cell &optional inhibit-lisp-eval)
2545 "Convert the string value of CELL to a number if appropriate.
2546 Otherwise if cell looks like lisp (meaning it starts with a
2547 \"(\", \"'\", \"`\" or a \"[\") then read it as lisp,
2548 otherwise return it unmodified as a string. Optional argument
2549 NO-LISP-EVAL inhibits lisp evaluation for situations in which is
2550 it not appropriate."
2551 (if (and (stringp cell) (not (equal cell "")))
2552 (or (org-babel-number-p cell)
2553 (if (and (not inhibit-lisp-eval)
2554 (or (member (substring cell 0 1) '("(" "'" "`" "["))
2555 (string= cell "*this*")))
2556 (eval (read cell))
2557 (if (string= (substring cell 0 1) "\"")
2558 (read cell)
2559 (progn (set-text-properties 0 (length cell) nil cell) cell))))
2560 cell))
2562 (defun org-babel-number-p (string)
2563 "If STRING represents a number return its value."
2564 (if (and (string-match "[0-9]+" string)
2565 (string-match "^-?[0-9]*\\.?[0-9]*$" string)
2566 (= (length (substring string (match-beginning 0)
2567 (match-end 0)))
2568 (length string)))
2569 (string-to-number string)))
2571 (defun org-babel-import-elisp-from-file (file-name &optional separator)
2572 "Read the results located at FILE-NAME into an elisp table.
2573 If the table is trivial, then return it as a scalar."
2574 (let (result)
2575 (save-window-excursion
2576 (with-temp-buffer
2577 (condition-case err
2578 (progn
2579 (org-table-import file-name separator)
2580 (delete-file file-name)
2581 (setq result (mapcar (lambda (row)
2582 (mapcar #'org-babel-string-read row))
2583 (org-table-to-lisp))))
2584 (error (message "Error reading results: %s" err) nil)))
2585 (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
2586 (if (consp (car result))
2587 (if (null (cdr (car result)))
2588 (caar result)
2589 result)
2590 (car result))
2591 result))))
2593 (defun org-babel-string-read (cell)
2594 "Strip nested \"s from around strings."
2595 (org-babel-read (or (and (stringp cell)
2596 (string-match "\\\"\\(.+\\)\\\"" cell)
2597 (match-string 1 cell))
2598 cell) t))
2600 (defun org-babel-chomp (string &optional regexp)
2601 "Strip trailing spaces and carriage returns from STRING.
2602 Default regexp used is \"[ \f\t\n\r\v]\" but can be
2603 overwritten by specifying a regexp as a second argument."
2604 (let ((regexp (or regexp "[ \f\t\n\r\v]")))
2605 (while (and (> (length string) 0)
2606 (string-match regexp (substring string -1)))
2607 (setq string (substring string 0 -1)))
2608 string))
2610 (defun org-babel-trim (string &optional regexp)
2611 "Strip leading and trailing spaces and carriage returns from STRING.
2612 Like `org-babel-chomp' only it runs on both the front and back
2613 of the string."
2614 (org-babel-chomp (org-reverse-string
2615 (org-babel-chomp (org-reverse-string string) regexp))
2616 regexp))
2618 (defun org-babel-tramp-handle-call-process-region
2619 (start end program &optional delete buffer display &rest args)
2620 "Use Tramp to handle `call-process-region'.
2621 Fixes a bug in `tramp-handle-call-process-region'."
2622 (if (and (featurep 'tramp) (file-remote-p default-directory))
2623 (let ((tmpfile (tramp-compat-make-temp-file "")))
2624 (write-region start end tmpfile)
2625 (when delete (delete-region start end))
2626 (unwind-protect
2627 ;; (apply 'call-process program tmpfile buffer display args)
2628 ;; bug in tramp
2629 (apply 'process-file program tmpfile buffer display args)
2630 (delete-file tmpfile)))
2631 ;; org-babel-call-process-region-original is the original emacs
2632 ;; definition. It is in scope from the let binding in
2633 ;; org-babel-execute-src-block
2634 (apply org-babel-call-process-region-original
2635 start end program delete buffer display args)))
2637 (defun org-babel-local-file-name (file)
2638 "Return the local name component of FILE."
2639 (if (file-remote-p file)
2640 (let (localname)
2641 (with-parsed-tramp-file-name file nil
2642 localname))
2643 file))
2645 (defun org-babel-process-file-name (name &optional no-quote-p)
2646 "Prepare NAME to be used in an external process.
2647 If NAME specifies a remote location, the remote portion of the
2648 name is removed, since in that case the process will be executing
2649 remotely. The file name is then processed by `expand-file-name'.
2650 Unless second argument NO-QUOTE-P is non-nil, the file name is
2651 additionally processed by `shell-quote-argument'"
2652 ((lambda (f) (if no-quote-p f (shell-quote-argument f)))
2653 (expand-file-name (org-babel-local-file-name name))))
2655 (defvar org-babel-temporary-directory)
2656 (unless (or noninteractive (boundp 'org-babel-temporary-directory))
2657 (defvar org-babel-temporary-directory
2658 (or (and (boundp 'org-babel-temporary-directory)
2659 (file-exists-p org-babel-temporary-directory)
2660 org-babel-temporary-directory)
2661 (make-temp-file "babel-" t))
2662 "Directory to hold temporary files created to execute code blocks.
2663 Used by `org-babel-temp-file'. This directory will be removed on
2664 Emacs shutdown."))
2666 (defmacro org-babel-result-cond (result-params scalar-form &rest table-forms)
2667 "Call the code to parse raw string results according to RESULT-PARAMS."
2668 (declare (indent 1)
2669 (debug (form form &rest form)))
2670 (org-with-gensyms (params)
2671 `(let ((,params ,result-params))
2672 (unless (member "none" ,params)
2673 (if (or (member "scalar" ,params)
2674 (member "verbatim" ,params)
2675 (member "html" ,params)
2676 (member "code" ,params)
2677 (member "pp" ,params)
2678 (and (or (member "output" ,params)
2679 (member "raw" ,params)
2680 (member "org" ,params)
2681 (member "drawer" ,params))
2682 (not (member "table" ,params))))
2683 ,scalar-form
2684 ,@table-forms)))))
2685 (def-edebug-spec org-babel-result-cond (form form body))
2687 (defun org-babel-temp-file (prefix &optional suffix)
2688 "Create a temporary file in the `org-babel-temporary-directory'.
2689 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2690 value of `temporary-file-directory' temporarily set to the value
2691 of `org-babel-temporary-directory'."
2692 (if (file-remote-p default-directory)
2693 (let ((prefix
2694 (concat (file-remote-p default-directory)
2695 (expand-file-name prefix temporary-file-directory))))
2696 (make-temp-file prefix nil suffix))
2697 (let ((temporary-file-directory
2698 (or (and (boundp 'org-babel-temporary-directory)
2699 (file-exists-p org-babel-temporary-directory)
2700 org-babel-temporary-directory)
2701 temporary-file-directory)))
2702 (make-temp-file prefix nil suffix))))
2704 (defun org-babel-remove-temporary-directory ()
2705 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2706 (when (and (boundp 'org-babel-temporary-directory)
2707 (file-exists-p org-babel-temporary-directory))
2708 ;; taken from `delete-directory' in files.el
2709 (condition-case nil
2710 (progn
2711 (mapc (lambda (file)
2712 ;; This test is equivalent to
2713 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2714 ;; but more efficient
2715 (if (eq t (car (file-attributes file)))
2716 (delete-directory file)
2717 (delete-file file)))
2718 ;; We do not want to delete "." and "..".
2719 (directory-files org-babel-temporary-directory 'full
2720 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2721 (delete-directory org-babel-temporary-directory))
2722 (error
2723 (message "Failed to remove temporary Org-babel directory %s"
2724 (if (boundp 'org-babel-temporary-directory)
2725 org-babel-temporary-directory
2726 "[directory not defined]"))))))
2728 (add-hook 'kill-emacs-hook 'org-babel-remove-temporary-directory)
2730 (provide 'ob-core)
2732 ;; Local variables:
2733 ;; generated-autoload-file: "org-loaddefs.el"
2734 ;; End:
2736 ;;; ob-core.el ends here