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