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