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