Fix reference to wrong symbol
[org-mode.git] / lisp / ob-tangle.el
blob9f069fc8d3f3e26ebd6c92713b5d8257b92010c3
1 ;;; ob-tangle.el --- extract source code from org-mode files
3 ;; Copyright (C) 2009, 2010 Free Software Foundation, Inc.
5 ;; Author: Eric Schulte
6 ;; Keywords: literate programming, reproducible research
7 ;; Homepage: http://orgmode.org
8 ;; Version: 7.01trans
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 ;;; Commentary:
27 ;; Extract the code from source blocks out into raw source-code files.
29 ;;; Code:
30 (require 'ob)
31 (require 'org-src)
32 (eval-when-compile
33 (require 'cl))
35 (declare-function org-link-escape "org" (text &optional table))
36 (declare-function org-heading-components "org" ())
37 (declare-function org-back-to-heading "org" (invisible-ok))
38 (declare-function org-fill-template "org" (template alist))
40 ;;;###autoload
41 (defcustom org-babel-tangle-lang-exts
42 '(("emacs-lisp" . "el"))
43 "Alist mapping languages to their file extensions.
44 The key is the language name, the value is the string that should
45 be inserted as the extension commonly used to identify files
46 written in this language. If no entry is found in this list,
47 then the name of the language is used."
48 :group 'org-babel-tangle
49 :type '(repeat
50 (cons
51 (string "Language name")
52 (string "File Extension"))))
54 (defcustom org-babel-post-tangle-hook nil
55 "Hook run in code files tangled by `org-babel-tangle'."
56 :group 'org-babel
57 :type 'hook)
59 (defcustom org-babel-pre-tangle-hook '(save-buffer)
60 "Hook run at the beginning of `org-babel-tangle'."
61 :group 'org-babel
62 :type 'hook)
64 (defcustom org-babel-tangle-pad-newline t
65 "Switch indicating whether to pad tangled code with newlines."
66 :group 'org-babel
67 :type 'boolean)
69 (defcustom org-babel-tangle-comment-format-beg "[[%link][%sourcename]]"
70 "Format of inserted comments in tangled code files.
71 The following format strings can be used to insert special
72 information into the output using `org-fill-template'.
73 %start-line --- the line number at the start of the code block
74 %file --------- the file from which the code block was tangled
75 %link --------- Org-mode style link to the code block
76 %source-name -- name of the code block
78 Whether or not comments are inserted during tangling is
79 controlled by the :comments header argument."
80 :group 'org-babel
81 :type 'string)
83 (defcustom org-babel-tangle-comment-format-end "%sourcename ends here"
84 "Format of inserted comments in tangled code files.
85 The following format strings can be used to insert special
86 information into the output using `org-fill-template'.
87 %start-line --- the line number at the start of the code block
88 %file --------- the file from which the code block was tangled
89 %link --------- Org-mode style link to the code block
90 %source-name -- name of the code block
92 Whether or not comments are inserted during tangling is
93 controlled by the :comments header argument."
94 :group 'org-babel
95 :type 'string)
97 (defun org-babel-find-file-noselect-refresh (file)
98 "Find file ensuring that the latest changes on disk are
99 represented in the file."
100 (find-file-noselect file)
101 (with-current-buffer (get-file-buffer file)
102 (revert-buffer t t t)))
104 (defmacro org-babel-with-temp-filebuffer (file &rest body)
105 "Open FILE into a temporary buffer execute BODY there like
106 `progn', then kill the FILE buffer returning the result of
107 evaluating BODY."
108 (declare (indent 1))
109 (let ((temp-result (make-symbol "temp-result"))
110 (temp-file (make-symbol "temp-file"))
111 (visited-p (make-symbol "visited-p")))
112 `(let (,temp-result ,temp-file
113 (,visited-p (get-file-buffer ,file)))
114 (org-babel-find-file-noselect-refresh ,file)
115 (setf ,temp-file (get-file-buffer ,file))
116 (with-current-buffer ,temp-file
117 (setf ,temp-result (progn ,@body)))
118 (unless ,visited-p (kill-buffer ,temp-file))
119 ,temp-result)))
121 ;;;###autoload
122 (defun org-babel-load-file (file)
123 "Load Emacs Lisp source code blocks in the Org-mode FILE.
124 This function exports the source code using
125 `org-babel-tangle' and then loads the resulting file using
126 `load-file'."
127 (flet ((age (file)
128 (float-time
129 (time-subtract (current-time)
130 (nth 5 (or (file-attributes (file-truename file))
131 (file-attributes file)))))))
132 (let* ((base-name (file-name-sans-extension file))
133 (exported-file (concat base-name ".el")))
134 ;; tangle if the org-mode file is newer than the elisp file
135 (unless (and (file-exists-p exported-file)
136 (> (age file) (age exported-file)))
137 (org-babel-tangle-file file exported-file "emacs-lisp"))
138 (load-file exported-file)
139 (message "loaded %s" exported-file))))
141 ;;;###autoload
142 (defun org-babel-tangle-file (file &optional target-file lang)
143 "Extract the bodies of source code blocks in FILE.
144 Source code blocks are extracted with `org-babel-tangle'.
145 Optional argument TARGET-FILE can be used to specify a default
146 export file for all source blocks. Optional argument LANG can be
147 used to limit the exported source code blocks by language."
148 (interactive "fFile to tangle: \nP")
149 (let ((visited-p (get-file-buffer (expand-file-name file)))
150 to-be-removed)
151 (save-window-excursion
152 (find-file file)
153 (setq to-be-removed (current-buffer))
154 (org-babel-tangle target-file lang))
155 (unless visited-p
156 (kill-buffer to-be-removed))))
158 (defun org-babel-tangle-publish (_ filename pub-dir)
159 "Tangle FILENAME and place the results in PUB-DIR."
160 (mapc (lambda (el) (copy-file el pub-dir t)) (org-babel-tangle-file filename)))
162 ;;;###autoload
163 (defun org-babel-tangle (&optional target-file lang)
164 "Write code blocks to source-specific files.
165 Extract the bodies of all source code blocks from the current
166 file into their own source-specific files. Optional argument
167 TARGET-FILE can be used to specify a default export file for all
168 source blocks. Optional argument LANG can be used to limit the
169 exported source code blocks by language."
170 (interactive)
171 (run-hooks 'org-babel-pre-tangle-hook)
172 (save-excursion
173 (let ((block-counter 0)
174 (org-babel-default-header-args
175 (if target-file
176 (org-babel-merge-params org-babel-default-header-args
177 (list (cons :tangle target-file)))
178 org-babel-default-header-args))
179 path-collector)
180 (mapc ;; map over all languages
181 (lambda (by-lang)
182 (let* ((lang (car by-lang))
183 (specs (cdr by-lang))
184 (ext (or (cdr (assoc lang org-babel-tangle-lang-exts)) lang))
185 (lang-f (intern
186 (concat
187 (or (and (cdr (assoc lang org-src-lang-modes))
188 (symbol-name
189 (cdr (assoc lang org-src-lang-modes))))
190 lang)
191 "-mode")))
192 she-banged)
193 (mapc
194 (lambda (spec)
195 (flet ((get-spec (name)
196 (cdr (assoc name (nth 4 spec)))))
197 (let* ((tangle (get-spec :tangle))
198 (she-bang ((lambda (sheb) (when (> (length sheb) 0) sheb))
199 (get-spec :shebang)))
200 (base-name (cond
201 ((string= "yes" tangle)
202 (file-name-sans-extension
203 (buffer-file-name)))
204 ((string= "no" tangle) nil)
205 ((> (length tangle) 0) tangle)))
206 (file-name (when base-name
207 ;; decide if we want to add ext to base-name
208 (if (and ext (string= "yes" tangle))
209 (concat base-name "." ext) base-name))))
210 (when file-name
211 ;; delete any old versions of file
212 (when (and (file-exists-p file-name)
213 (not (member file-name path-collector)))
214 (delete-file file-name))
215 ;; drop source-block to file
216 (with-temp-buffer
217 (when (fboundp lang-f) (funcall lang-f))
218 (when (and she-bang (not (member file-name she-banged)))
219 (insert (concat she-bang "\n"))
220 (setq she-banged (cons file-name she-banged)))
221 (org-babel-spec-to-string spec)
222 ;; We avoid append-to-file as it does not work with tramp.
223 (let ((content (buffer-string)))
224 (with-temp-buffer
225 (if (file-exists-p file-name)
226 (insert-file-contents file-name))
227 (goto-char (point-max))
228 (insert content)
229 (write-region nil nil file-name))))
230 ;; if files contain she-bangs, then make the executable
231 (when she-bang (set-file-modes file-name #o755))
232 ;; update counter
233 (setq block-counter (+ 1 block-counter))
234 (add-to-list 'path-collector file-name)))))
235 specs)))
236 (org-babel-tangle-collect-blocks lang))
237 (message "tangled %d code block%s from %s" block-counter
238 (if (= block-counter 1) "" "s")
239 (file-name-nondirectory (buffer-file-name (current-buffer))))
240 ;; run `org-babel-post-tangle-hook' in all tangled files
241 (when org-babel-post-tangle-hook
242 (mapc
243 (lambda (file)
244 (org-babel-with-temp-filebuffer file
245 (run-hooks 'org-babel-post-tangle-hook)))
246 path-collector))
247 path-collector)))
249 (defun org-babel-tangle-clean ()
250 "Remove comments inserted by `org-babel-tangle'.
251 Call this function inside of a source-code file generated by
252 `org-babel-tangle' to remove all comments inserted automatically
253 by `org-babel-tangle'. Warning, this comment removes any lines
254 containing constructs which resemble org-mode file links or noweb
255 references."
256 (interactive)
257 (goto-char (point-min))
258 (while (or (re-search-forward "\\[\\[file:.*\\]\\[.*\\]\\]" nil t)
259 (re-search-forward "<<[^[:space:]]*>>" nil t))
260 (delete-region (save-excursion (beginning-of-line 1) (point))
261 (save-excursion (end-of-line 1) (forward-char 1) (point)))))
263 (defvar org-stored-links)
264 (defun org-babel-tangle-collect-blocks (&optional language)
265 "Collect source blocks in the current Org-mode file.
266 Return an association list of source-code block specifications of
267 the form used by `org-babel-spec-to-string' grouped by language.
268 Optional argument LANG can be used to limit the collected source
269 code blocks by language."
270 (let ((block-counter 1) (current-heading "") blocks)
271 (org-babel-map-src-blocks (buffer-file-name)
272 ((lambda (new-heading)
273 (if (not (string= new-heading current-heading))
274 (progn
275 (setq block-counter 1)
276 (setq current-heading new-heading))
277 (setq block-counter (+ 1 block-counter))))
278 (replace-regexp-in-string "[ \t]" "-"
279 (condition-case nil
280 (nth 4 (org-heading-components))
281 (error (buffer-file-name)))))
282 (let* ((start-line (save-restriction (widen)
283 (+ 1 (line-number-at-pos (point)))))
284 (file (buffer-file-name))
285 (info (org-babel-get-src-block-info 'light))
286 (src-lang (nth 0 info)))
287 (unless (string= (cdr (assoc :tangle (nth 2 info))) "no")
288 (unless (and language (not (string= language src-lang)))
289 (let* ((info (org-babel-get-src-block-info))
290 (params (nth 2 info))
291 (link (progn (call-interactively 'org-store-link)
292 (org-babel-clean-text-properties
293 (car (pop org-stored-links)))))
294 (source-name
295 (intern (or (nth 4 info)
296 (format "%s:%d"
297 current-heading block-counter))))
298 (expand-cmd
299 (intern (concat "org-babel-expand-body:" src-lang)))
300 (assignments-cmd
301 (intern (concat "org-babel-variable-assignments:" src-lang)))
302 (body
303 ((lambda (body)
304 (if (assoc :no-expand params)
305 body
306 (if (fboundp expand-cmd)
307 (funcall expand-cmd body params)
308 (org-babel-expand-body:generic
309 body params
310 (and (fboundp assignments-cmd)
311 (funcall assignments-cmd params))))))
312 (if (and (cdr (assoc :noweb params))
313 (let ((nowebs (split-string
314 (cdr (assoc :noweb params)))))
315 (or (member "yes" nowebs)
316 (member "tangle" nowebs))))
317 (org-babel-expand-noweb-references info)
318 (nth 1 info))))
319 (comment
320 (when (or (string= "both" (cdr (assoc :comments params)))
321 (string= "org" (cdr (assoc :comments params))))
322 ;; from the previous heading or code-block end
323 (buffer-substring
324 (max (condition-case nil
325 (save-excursion
326 (org-back-to-heading t) (point))
327 (error 0))
328 (save-excursion
329 (re-search-backward
330 org-babel-src-block-regexp nil t)
331 (match-end 0)))
332 (point))))
333 by-lang)
334 ;; add the spec for this block to blocks under it's language
335 (setq by-lang (cdr (assoc src-lang blocks)))
336 (setq blocks (delq (assoc src-lang blocks) blocks))
337 (setq blocks (cons
338 (cons src-lang
339 (cons (list start-line file link
340 source-name params body comment)
341 by-lang)) blocks)))))))
342 ;; ensure blocks in the correct order
343 (setq blocks
344 (mapcar
345 (lambda (by-lang) (cons (car by-lang) (reverse (cdr by-lang))))
346 blocks))
347 blocks))
349 (defun org-babel-spec-to-string (spec)
350 "Insert SPEC into the current file.
351 Insert the source-code specified by SPEC into the current
352 source code file. This function uses `comment-region' which
353 assumes that the appropriate major-mode is set. SPEC has the
354 form
356 (start-line file link source-name params body comment)"
357 (let* ((start-line (nth 0 spec))
358 (file (nth 1 spec))
359 (link (org-link-escape (nth 2 spec)))
360 (source-name (nth 3 spec))
361 (body (nth 5 spec))
362 (comment (nth 6 spec))
363 (comments (cdr (assoc :comments (nth 4 spec))))
364 (link-p (or (string= comments "both") (string= comments "link")
365 (string= comments "yes")))
366 (link-data (mapcar (lambda (el)
367 (cons (symbol-name el)
368 ((lambda (le)
369 (if (stringp le) le (format "%S" le)))
370 (eval el))))
371 '(start-line file link source-name))))
372 (flet ((insert-comment (text)
373 (let ((text (org-babel-trim text)))
374 (when (and comments (not (string= comments "no"))
375 (> (length text) 0))
376 (when org-babel-tangle-pad-newline (insert "\n"))
377 (comment-region (point) (progn (insert text) (point)))
378 (end-of-line nil) (insert "\n")))))
379 (when comment (insert-comment comment))
380 (when link-p
381 (insert-comment
382 (org-fill-template org-babel-tangle-comment-format-beg link-data)))
383 (when org-babel-tangle-pad-newline (insert "\n"))
384 (insert
385 (format
386 "%s\n"
387 (replace-regexp-in-string
388 "^," ""
389 (org-babel-trim body (if org-src-preserve-indentation "[\f\n\r\v]")))))
390 (when link-p
391 (insert-comment
392 (org-fill-template org-babel-tangle-comment-format-end link-data))))))
394 (provide 'ob-tangle)
396 ;; arch-tag: 413ced93-48f5-4216-86e4-3fc5df8c8f24
398 ;;; ob-tangle.el ends here