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
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/>.
27 ;; Extract the code from source blocks out into raw source-code files.
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
))
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
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'."
59 (defcustom org-babel-pre-tangle-hook
'(save-buffer)
60 "Hook run at the beginning of `org-babel-tangle'."
64 (defcustom org-babel-tangle-pad-newline t
65 "Switch indicating whether to pad tangled code with newlines."
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."
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."
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
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
))
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
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
))))
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
)))
151 (save-window-excursion
153 (setq to-be-removed
(current-buffer))
154 (org-babel-tangle target-file lang
))
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
)))
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."
171 (run-hooks 'org-babel-pre-tangle-hook
)
173 (let ((block-counter 0)
174 (org-babel-default-header-args
176 (org-babel-merge-params org-babel-default-header-args
177 (list (cons :tangle target-file
)))
178 org-babel-default-header-args
))
180 (mapc ;; map over all languages
182 (let* ((lang (car by-lang
))
183 (specs (cdr by-lang
))
184 (ext (or (cdr (assoc lang org-babel-tangle-lang-exts
)) lang
))
187 (or (and (cdr (assoc lang org-src-lang-modes
))
189 (cdr (assoc lang org-src-lang-modes
))))
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
)))
201 ((string= "yes" tangle
)
202 (file-name-sans-extension
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
))))
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
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)))
225 (if (file-exists-p file-name
)
226 (insert-file-contents file-name
))
227 (goto-char (point-max))
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
))
233 (setq block-counter
(+ 1 block-counter
))
234 (add-to-list 'path-collector file-name
)))))
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
244 (org-babel-with-temp-filebuffer file
245 (run-hooks 'org-babel-post-tangle-hook
)))
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
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
))
275 (setq block-counter
1)
276 (setq current-heading new-heading
))
277 (setq block-counter
(+ 1 block-counter
))))
278 (replace-regexp-in-string "[ \t]" "-"
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
)))))
295 (intern (or (nth 4 info
)
297 current-heading block-counter
))))
299 (intern (concat "org-babel-expand-body:" src-lang
)))
301 (intern (concat "org-babel-variable-assignments:" src-lang
)))
304 (if (assoc :no-expand params
)
306 (if (fboundp expand-cmd
)
307 (funcall expand-cmd body params
)
308 (org-babel-expand-body:generic
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
)
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
324 (max (condition-case nil
326 (org-back-to-heading t
) (point))
330 org-babel-src-block-regexp nil t
)
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
))
339 (cons (list start-line file link
340 source-name params body comment
)
341 by-lang
)) blocks
)))))))
342 ;; ensure blocks in the correct order
345 (lambda (by-lang) (cons (car by-lang
) (reverse (cdr by-lang
))))
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
356 (start-line file link source-name params body comment)"
357 (let* ((start-line (nth 0 spec
))
359 (link (org-link-escape (nth 2 spec
)))
360 (source-name (nth 3 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
)
369 (if (stringp le
) le
(format "%S" le
)))
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"))
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
))
382 (org-fill-template org-babel-tangle-comment-format-beg link-data
)))
383 (when org-babel-tangle-pad-newline
(insert "\n"))
387 (replace-regexp-in-string
389 (org-babel-trim body
(if org-src-preserve-indentation
"[\f\n\r\v]")))))
392 (org-fill-template org-babel-tangle-comment-format-end link-data
))))))
396 ;; arch-tag: 413ced93-48f5-4216-86e4-3fc5df8c8f24
398 ;;; ob-tangle.el ends here