Update copyright year to 2014 by running admin/update-copyright.
[emacs.git] / lisp / org / ob-exp.el
blob973cea0bff8c2b6432c5fd6ced2b8d373fa22371
1 ;;; ob-exp.el --- Exportation of org-babel source blocks
3 ;; Copyright (C) 2009-2014 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 (require 'ob-core)
27 (eval-when-compile
28 (require 'cl))
30 (defvar org-current-export-file)
31 (defvar org-babel-lob-one-liner-regexp)
32 (defvar org-babel-ref-split-regexp)
33 (defvar org-list-forbidden-blocks)
35 (declare-function org-babel-lob-get-info "ob-lob" ())
36 (declare-function org-babel-eval-wipe-error-buffer "ob-eval" ())
37 (declare-function org-between-regexps-p "org"
38 (start-re end-re &optional lim-up lim-down))
39 (declare-function org-get-indentation "org" (&optional line))
40 (declare-function org-heading-components "org" ())
41 (declare-function org-in-block-p "org" (names))
42 (declare-function org-in-verbatim-emphasis "org" ())
43 (declare-function org-link-search "org" (s &optional type avoid-pos stealth))
44 (declare-function org-fill-template "org" (template alist))
45 (declare-function org-split-string "org" (string &optional separators))
46 (declare-function org-element-at-point "org-element" (&optional keep-trail))
47 (declare-function org-element-context "org-element" ())
48 (declare-function org-element-property "org-element" (property element))
49 (declare-function org-element-type "org-element" (element))
50 (declare-function org-escape-code-in-string "org-src" (s))
52 (defcustom org-export-babel-evaluate t
53 "Switch controlling code evaluation during export.
54 When set to nil no code will be evaluated as part of the export
55 process. When set to 'inline-only, only inline code blocks will
56 be executed."
57 :group 'org-babel
58 :version "24.1"
59 :type '(choice (const :tag "Never" nil)
60 (const :tag "Only inline code" inline-only)
61 (const :tag "Always" t)))
62 (put 'org-export-babel-evaluate 'safe-local-variable (lambda (x) (eq x nil)))
64 (defun org-babel-exp-get-export-buffer ()
65 "Return the current export buffer if possible."
66 (cond
67 ((bufferp org-current-export-file) org-current-export-file)
68 (org-current-export-file (get-file-buffer org-current-export-file))
69 ('otherwise
70 (error "Requested export buffer when `org-current-export-file' is nil"))))
72 (defvar org-link-search-inhibit-query)
74 (defmacro org-babel-exp-in-export-file (lang &rest body)
75 (declare (indent 1))
76 `(let* ((lang-headers (intern (concat "org-babel-default-header-args:" ,lang)))
77 (heading (nth 4 (ignore-errors (org-heading-components))))
78 (export-buffer (current-buffer))
79 (original-buffer (org-babel-exp-get-export-buffer)) results)
80 (when original-buffer
81 ;; resolve parameters in the original file so that
82 ;; headline and file-wide parameters are included, attempt
83 ;; to go to the same heading in the original file
84 (set-buffer original-buffer)
85 (save-restriction
86 (when heading
87 (condition-case nil
88 (let ((org-link-search-inhibit-query t))
89 (org-link-search heading))
90 (error (when heading
91 (goto-char (point-min))
92 (re-search-forward (regexp-quote heading) nil t)))))
93 (setq results ,@body))
94 (set-buffer export-buffer)
95 results)))
96 (def-edebug-spec org-babel-exp-in-export-file (form body))
98 (defun org-babel-exp-src-block (&rest headers)
99 "Process source block for export.
100 Depending on the 'export' headers argument, replace the source
101 code block like this:
103 both ---- display the code and the results
105 code ---- the default, display the code inside the block but do
106 not process
108 results - just like none only the block is run on export ensuring
109 that it's results are present in the org-mode buffer
111 none ---- do not display either code or results upon export
113 Assume point is at the beginning of block's starting line."
114 (interactive)
115 (unless noninteractive (message "org-babel-exp processing..."))
116 (save-excursion
117 (let* ((info (org-babel-get-src-block-info 'light))
118 (lang (nth 0 info))
119 (raw-params (nth 2 info)) hash)
120 ;; bail if we couldn't get any info from the block
121 (when info
122 ;; if we're actually going to need the parameters
123 (when (member (cdr (assoc :exports (nth 2 info))) '("both" "results"))
124 (org-babel-exp-in-export-file lang
125 (setf (nth 2 info)
126 (org-babel-process-params
127 (apply #'org-babel-merge-params
128 org-babel-default-header-args
129 (if (boundp lang-headers) (eval lang-headers) nil)
130 (append (org-babel-params-from-properties lang)
131 (list raw-params))))))
132 (setf hash (org-babel-sha1-hash info)))
133 (org-babel-exp-do-export info 'block hash)))))
135 (defcustom org-babel-exp-call-line-template
137 "Template used to export call lines.
138 This template may be customized to include the call line name
139 with any export markup. The template is filled out using
140 `org-fill-template', and the following %keys may be used.
142 line --- call line
144 An example value would be \"\\n: call: %line\" to export the call line
145 wrapped in a verbatim environment.
147 Note: the results are inserted separately after the contents of
148 this template."
149 :group 'org-babel
150 :type 'string)
152 (defvar org-babel-default-lob-header-args)
153 (defun org-babel-exp-non-block-elements (start end)
154 "Process inline source and call lines between START and END for export."
155 (interactive)
156 (save-excursion
157 (goto-char start)
158 (unless (markerp end)
159 (let ((m (make-marker)))
160 (set-marker m end (current-buffer))
161 (setq end m)))
162 (let ((rx (concat "\\(?:" org-babel-inline-src-block-regexp
163 "\\|" org-babel-lob-one-liner-regexp "\\)")))
164 (while (re-search-forward rx end t)
165 (save-excursion
166 (let* ((element (save-excursion
167 ;; If match is inline, point is at its
168 ;; end. Move backward so
169 ;; `org-element-context' can get the
170 ;; object, not the following one.
171 (backward-char)
172 (save-match-data (org-element-context))))
173 (type (org-element-type element)))
174 (when (memq type '(babel-call inline-babel-call inline-src-block))
175 (let ((beg-el (org-element-property :begin element))
176 (end-el (org-element-property :end element)))
177 (case type
178 (inline-src-block
179 (let* ((info (org-babel-parse-inline-src-block-match))
180 (params (nth 2 info)))
181 (setf (nth 1 info)
182 (if (and (cdr (assoc :noweb params))
183 (string= "yes" (cdr (assoc :noweb params))))
184 (org-babel-expand-noweb-references
185 info (org-babel-exp-get-export-buffer))
186 (nth 1 info)))
187 (goto-char beg-el)
188 (let ((replacement (org-babel-exp-do-export info 'inline)))
189 (if (equal replacement "")
190 ;; Replacement code is empty: completely
191 ;; remove inline src block, including extra
192 ;; white space that might have been created
193 ;; when inserting results.
194 (delete-region beg-el
195 (progn (goto-char end-el)
196 (skip-chars-forward " \t")
197 (point)))
198 ;; Otherwise: remove inline src block but
199 ;; preserve following white spaces. Then
200 ;; insert value.
201 (delete-region beg-el
202 (progn (goto-char end-el)
203 (skip-chars-backward " \t")
204 (point)))
205 (insert replacement)))))
206 ((babel-call inline-babel-call)
207 (let* ((lob-info (org-babel-lob-get-info))
208 (results
209 (org-babel-exp-do-export
210 (list "emacs-lisp" "results"
211 (apply #'org-babel-merge-params
212 org-babel-default-header-args
213 org-babel-default-lob-header-args
214 (append
215 (org-babel-params-from-properties)
216 (list
217 (org-babel-parse-header-arguments
218 (org-no-properties
219 (concat
220 ":var results="
221 (mapconcat 'identity
222 (butlast lob-info 2)
223 " ")))))))
224 "" (nth 3 lob-info) (nth 2 lob-info))
225 'lob))
226 (rep (org-fill-template
227 org-babel-exp-call-line-template
228 `(("line" . ,(nth 0 lob-info))))))
229 ;; If replacement is empty, completely remove the
230 ;; object/element, including any extra white space
231 ;; that might have been created when including
232 ;; results.
233 (if (equal rep "")
234 (delete-region
235 beg-el
236 (progn (goto-char end-el)
237 (if (not (eq type 'babel-call))
238 (progn (skip-chars-forward " \t") (point))
239 (skip-chars-forward " \r\t\n")
240 (line-beginning-position))))
241 ;; Otherwise, preserve following white
242 ;; spaces/newlines and then, insert replacement
243 ;; string.
244 (goto-char beg-el)
245 (delete-region beg-el
246 (progn (goto-char end-el)
247 (skip-chars-backward " \r\t\n")
248 (point)))
249 (insert rep)))))))))))))
251 (defvar org-src-preserve-indentation) ; From org-src.el
252 (defun org-babel-exp-process-buffer ()
253 "Execute all blocks in visible part of buffer."
254 (interactive)
255 (save-window-excursion
256 (let ((case-fold-search t)
257 (pos (point-min)))
258 (goto-char pos)
259 (while (re-search-forward "^[ \t]*#\\+BEGIN_SRC" nil t)
260 (let ((element (save-match-data (org-element-at-point))))
261 (when (eq (org-element-type element) 'src-block)
262 (let* ((match-start (copy-marker (match-beginning 0)))
263 (begin (copy-marker (org-element-property :begin element)))
264 ;; Make sure we don't remove any blank lines after
265 ;; the block when replacing it.
266 (block-end (save-excursion
267 (goto-char (org-element-property :end element))
268 (skip-chars-backward " \r\t\n")
269 (copy-marker (line-end-position))))
270 (ind (org-get-indentation))
271 (headers
272 (cons
273 (org-element-property :language element)
274 (let ((params (org-element-property :parameters element)))
275 (and params (org-split-string params "[ \t]+"))))))
276 ;; Execute all non-block elements between POS and
277 ;; current block.
278 (org-babel-exp-non-block-elements pos begin)
279 ;; Take care of matched block: compute replacement
280 ;; string. In particular, a nil REPLACEMENT means the
281 ;; block should be left as-is while an empty string
282 ;; should remove the block.
283 (let ((replacement (progn (goto-char match-start)
284 (org-babel-exp-src-block headers))))
285 (cond ((not replacement) (goto-char block-end))
286 ((equal replacement "")
287 (delete-region begin
288 (progn (goto-char block-end)
289 (skip-chars-forward " \r\t\n")
290 (if (eobp) (point)
291 (line-beginning-position)))))
293 (goto-char match-start)
294 (delete-region (point) block-end)
295 (insert replacement)
296 (if (org-element-property :preserve-indent element)
297 ;; Indent only the code block markers.
298 (save-excursion (skip-chars-backward " \r\t\n")
299 (indent-line-to ind)
300 (goto-char match-start)
301 (indent-line-to ind))
302 ;; Indent everything.
303 (indent-rigidly match-start (point) ind)))))
304 (setq pos (line-beginning-position))
305 ;; Cleanup markers.
306 (set-marker match-start nil)
307 (set-marker begin nil)
308 (set-marker block-end nil)))))
309 ;; Eventually execute all non-block Babel elements between last
310 ;; src-block and end of buffer.
311 (org-babel-exp-non-block-elements pos (point-max)))))
313 (defun org-babel-in-example-or-verbatim ()
314 "Return true if point is in example or verbatim code.
315 Example and verbatim code include escaped portions of
316 an org-mode buffer code that should be treated as normal
317 org-mode text."
318 (or (save-match-data
319 (save-excursion
320 (goto-char (point-at-bol))
321 (looking-at "[ \t]*:[ \t]")))
322 (org-in-verbatim-emphasis)
323 (org-in-block-p org-list-forbidden-blocks)
324 (org-between-regexps-p "^[ \t]*#\\+begin_src" "^[ \t]*#\\+end_src")))
326 (defun org-babel-exp-do-export (info type &optional hash)
327 "Return a string with the exported content of a code block.
328 The function respects the value of the :exports header argument."
329 (let ((silently (lambda () (let ((session (cdr (assoc :session (nth 2 info)))))
330 (when (not (and session (equal "none" session)))
331 (org-babel-exp-results info type 'silent)))))
332 (clean (lambda () (unless (eq type 'inline) (org-babel-remove-result info)))))
333 (case (intern (or (cdr (assoc :exports (nth 2 info))) "code"))
334 ('none (funcall silently) (funcall clean) "")
335 ('code (funcall silently) (funcall clean) (org-babel-exp-code info))
336 ('results (org-babel-exp-results info type nil hash) "")
337 ('both (org-babel-exp-results info type nil hash)
338 (org-babel-exp-code info)))))
340 (defcustom org-babel-exp-code-template
341 "#+BEGIN_SRC %lang%flags\n%body\n#+END_SRC"
342 "Template used to export the body of code blocks.
343 This template may be customized to include additional information
344 such as the code block name, or the values of particular header
345 arguments. The template is filled out using `org-fill-template',
346 and the following %keys may be used.
348 lang ------ the language of the code block
349 name ------ the name of the code block
350 body ------ the body of the code block
351 flags ----- the flags passed to the code block
353 In addition to the keys mentioned above, every header argument
354 defined for the code block may be used as a key and will be
355 replaced with its value."
356 :group 'org-babel
357 :type 'string)
359 (defun org-babel-exp-code (info)
360 "Return the original code block formatted for export."
361 (setf (nth 1 info)
362 (if (string= "strip-export" (cdr (assoc :noweb (nth 2 info))))
363 (replace-regexp-in-string
364 (org-babel-noweb-wrap) "" (nth 1 info))
365 (if (org-babel-noweb-p (nth 2 info) :export)
366 (org-babel-expand-noweb-references
367 info (org-babel-exp-get-export-buffer))
368 (nth 1 info))))
369 (org-fill-template
370 org-babel-exp-code-template
371 `(("lang" . ,(nth 0 info))
372 ("body" . ,(org-escape-code-in-string (nth 1 info)))
373 ,@(mapcar (lambda (pair)
374 (cons (substring (symbol-name (car pair)) 1)
375 (format "%S" (cdr pair))))
376 (nth 2 info))
377 ("flags" . ,(let ((f (nth 3 info))) (when f (concat " " f))))
378 ("name" . ,(or (nth 4 info) "")))))
380 (defun org-babel-exp-results (info type &optional silent hash)
381 "Evaluate and return the results of the current code block for export.
382 Results are prepared in a manner suitable for export by org-mode.
383 This function is called by `org-babel-exp-do-export'. The code
384 block will be evaluated. Optional argument SILENT can be used to
385 inhibit insertion of results into the buffer."
386 (when (and (or (eq org-export-babel-evaluate t)
387 (and (eq type 'inline)
388 (eq org-export-babel-evaluate 'inline-only)))
389 (not (and hash (equal hash (org-babel-current-result-hash)))))
390 (let ((lang (nth 0 info))
391 (body (if (org-babel-noweb-p (nth 2 info) :eval)
392 (org-babel-expand-noweb-references
393 info (org-babel-exp-get-export-buffer))
394 (nth 1 info)))
395 (info (copy-sequence info))
396 (org-babel-current-src-block-location (point-marker)))
397 ;; skip code blocks which we can't evaluate
398 (when (fboundp (intern (concat "org-babel-execute:" lang)))
399 (org-babel-eval-wipe-error-buffer)
400 (prog1 nil
401 (setf (nth 1 info) body)
402 (setf (nth 2 info)
403 (org-babel-exp-in-export-file lang
404 (org-babel-process-params
405 (org-babel-merge-params
406 (nth 2 info)
407 `((:results . ,(if silent "silent" "replace")))))))
408 (cond
409 ((equal type 'block)
410 (org-babel-execute-src-block nil info))
411 ((equal type 'inline)
412 ;; position the point on the inline source block allowing
413 ;; `org-babel-insert-result' to check that the block is
414 ;; inline
415 (re-search-backward "[ \f\t\n\r\v]" nil t)
416 (re-search-forward org-babel-inline-src-block-regexp nil t)
417 (re-search-backward "src_" nil t)
418 (org-babel-execute-src-block nil info))
419 ((equal type 'lob)
420 (save-excursion
421 (re-search-backward org-babel-lob-one-liner-regexp nil t)
422 (let (org-confirm-babel-evaluate)
423 (org-babel-execute-src-block nil info))))))))))
426 (provide 'ob-exp)
428 ;;; ob-exp.el ends here