Minor fix
[org-mode/org-tableheadings.git] / contrib / babel / lisp / org-babel-tangle.el
blob5dfbb94d67149d555afd5a4d650c7f2363d764ff
1 ;;; org-babel-tangle.el --- Extract source code from org-mode files
3 ;; Copyright (C) 2009 Eric Schulte
5 ;; Author: Eric Schulte
6 ;; Keywords: literate programming, reproducible research
7 ;; Homepage: http://orgmode.org
8 ;; Version: 0.01
10 ;;; License:
12 ;; This program 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, or (at your option)
15 ;; any later version.
17 ;; This program 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; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
27 ;;; Commentary:
29 ;; Extract the code from source blocks out into raw source-code files.
31 ;;; Code:
32 (require 'org-babel)
34 (defvar org-babel-tangle-langs nil
35 "List of languages supported by `org-babel-tangle'. The first
36 element of each language's list is a string indicating the name
37 of the language, the second element should be the file extension
38 of the language, an optional third element the shebang(#!) line
39 to use when writing out the language to file, and an optional
40 fourth element is a flag which when true indicates that the
41 language does not support comments.")
43 (defun org-babel-load-file (file)
44 "Load the contents of the Emacs Lisp source code blocks in the
45 org-mode formatted FILE. This function will first export the
46 source code using `org-babel-tangle' and then load the resulting
47 file using `load-file'."
48 (flet ((age (file)
49 (time-to-seconds
50 (time-subtract (current-time)
51 (sixth (or (file-attributes (file-truename file))
52 (file-attributes file)))))))
53 (let* ((base-name (file-name-sans-extension file))
54 (exported-file (concat base-name ".el")))
55 ;; tangle if the org-mode file is newer than the elisp file
56 (unless (and (file-exists-p exported-file) (> (age file) (age exported-file)))
57 (org-babel-tangle-file file exported-file "emacs-lisp"))
58 (load-file exported-file)
59 (message "loaded %s" exported-file))))
61 (defun org-babel-tangle-file (file &optional target-file lang)
62 "Extract the bodies of all source code blocks in FILE with
63 `org-babel-tangle'. Optional argument TARGET-FILE can be used to
64 specify a default export file for all source blocks. Optional
65 argument LANG can be used to limit the exported source code
66 blocks by language."
67 (interactive "fFile to tangle: \nP")
68 (save-window-excursion (find-file file) (org-babel-tangle target-file lang)))
70 (defun org-babel-tangle (&optional target-file lang)
71 "Extract the bodies of all source code blocks from the current
72 file into their own source-specific files. Optional argument
73 TARGET-FILE can be used to specify a default export file for all
74 source blocks. Optional argument LANG can be used to limit the
75 exported source code blocks by language."
76 (interactive)
77 (save-buffer)
78 (save-excursion
79 (let ((block-counter 0)
80 path-collector)
81 (mapc ;; map over all languages
82 (lambda (by-lang)
83 (let* ((lang (car by-lang))
84 (specs (cdr by-lang))
85 (lang-f (intern (concat
86 (or (and (cdr (assoc lang org-src-lang-modes))
87 (symbol-name
88 (cdr (assoc lang org-src-lang-modes))))
89 lang)
90 "-mode")))
91 (lang-specs (cdr (assoc lang org-babel-tangle-langs)))
92 (ext (first lang-specs))
93 (she-bang (second lang-specs))
94 (commentable (and (fboundp lang-f) (not (third lang-specs))))
95 she-banged)
96 (mapc
97 (lambda (spec)
98 (flet ((get-spec (name)
99 (cdr (assoc name (third spec)))))
100 (let* ((tangle (get-spec :tangle))
101 (she-bang (if (> (length (get-spec :shebang)) 0)
102 (get-spec :shebang)
103 she-bang))
104 (base-name (or (cond
105 ((string= "yes" tangle)
106 (file-name-sans-extension (buffer-file-name)))
107 ((string= "no" tangle) nil)
108 ((> (length tangle) 0) tangle))
109 target-file))
110 (file-name (when base-name
111 ;; decide if we want to add ext to base-name
112 (if (and ext (string= "yes" tangle))
113 (concat base-name "." ext) base-name))))
114 ;; ;; debugging
115 ;; (message
116 ;; "tangle=%S base-name=%S file-name=%S she-bang=%S commentable=%s"
117 ;; tangle base-name file-name she-bang commentable)
118 (when file-name
119 ;; delete any old versions of file
120 (when (and (file-exists-p file-name)
121 (not (member file-name path-collector)))
122 (delete-file file-name))
123 ;; drop source-block to file
124 (with-temp-buffer
125 (if (fboundp lang-f) (funcall lang-f))
126 (when (and she-bang (not (member file-name she-banged)))
127 (insert (concat she-bang "\n"))
128 (setq she-banged (cons file-name she-banged)))
129 (org-babel-spec-to-string spec)
130 ;; We avoid append-to-file as it does not work with tramp.
131 (let ((content (buffer-string)))
132 (with-temp-buffer
133 (if (file-exists-p file-name)
134 (insert-file-contents file-name))
135 (goto-char (point-max))
136 (insert content)
137 (write-region nil nil file-name))))
138 ;; update counter
139 (setq block-counter (+ 1 block-counter))
140 (add-to-list 'path-collector file-name)))))
141 specs)))
142 (org-babel-tangle-collect-blocks lang))
143 (message "tangled %d code block%s" block-counter
144 (if (= block-counter 1) "" "s"))
145 path-collector)))
147 (defun org-babel-tangle-clean ()
148 "Call this function inside of a source-code file generated by
149 `org-babel-tangle' to remove all comments inserted automatically
150 by `org-babel-tangle'. Warning, this comment removes any lines
151 containing constructs which resemble org-mode file links or noweb
152 references."
153 (interactive)
154 (goto-char (point-min))
155 (while (or (re-search-forward "\\[\\[file:.*\\]\\[.*\\]\\]" nil t)
156 (re-search-forward "<<[^[:space:]]*>>" nil t))
157 (delete-region (save-excursion (move-beginning-of-line 1) (point))
158 (save-excursion (move-end-of-line 1) (forward-char 1) (point)))))
160 (defun org-babel-tangle-collect-blocks (&optional lang)
161 "Collect all source blocks in the current org-mode file.
162 Return an association list of source-code block specifications of
163 the form used by `org-babel-spec-to-string' grouped by language.
164 Optional argument LANG can be used to limit the collected source
165 code blocks by language."
166 (let ((block-counter 0) blocks)
167 (org-babel-map-source-blocks (buffer-file-name)
168 (setq block-counter (+ 1 block-counter))
169 (let* ((link (progn (call-interactively 'org-store-link)
170 (org-babel-clean-text-properties (car (pop org-stored-links)))))
171 (info (org-babel-get-src-block-info))
172 (source-name (intern (or (fifth info)
173 (format "block-%d" block-counter))))
174 (src-lang (first info))
175 (body (org-babel-expand-noweb-references info))
176 (params (third info))
177 (spec (list link source-name params body (third (cdr (assoc src-lang org-babel-tangle-langs)))))
178 by-lang)
179 (unless (string= (cdr (assoc :tangle params)) "no") ;; maybe skip
180 (unless (and lang (not (string= lang src-lang))) ;; maybe limit by language
181 ;; add the spec for this block to blocks under it's language
182 (setq by-lang (cdr (assoc src-lang blocks)))
183 (setq blocks (delq (assoc src-lang blocks) blocks))
184 (setq blocks (cons (cons src-lang (cons spec by-lang)) blocks))))))
185 ;; ensure blocks in the correct order
186 (setq blocks
187 (mapcar (lambda (by-lang) (cons (car by-lang) (reverse (cdr by-lang)))) blocks))
188 ;; blocks should contain all source-blocks organized by language
189 ;; (message "blocks=%S" blocks) ;; debugging
190 blocks))
192 (defun org-babel-spec-to-string (spec)
193 "Insert the source-code specified by SPEC into the current
194 source code file. This function uses `comment-region' which
195 assumes that the appropriate major-mode is set. SPEC has the
196 form
198 (link source-name params body)"
199 (flet ((insert-comment (text)
200 (when commentable
201 (insert "\n")
202 (comment-region (point) (progn (insert text) (point)))
203 (move-end-of-line nil)
204 (insert "\n"))))
205 (let ((link (first spec))
206 (source-name (second spec))
207 (body (fourth spec))
208 (commentable (not (if (> (length (cdr (assoc :comments (third spec)))) 0)
209 (string= (cdr (assoc :comments (third spec))) "no")
210 (fifth spec)))))
211 (insert-comment (format "[[%s][%s]]" (org-link-escape link) source-name))
212 (insert (format "%s" (org-babel-chomp body)))
213 (insert-comment (format "%s ends here" source-name)))))
215 (provide 'org-babel-tangle)
216 ;;; org-babel-tangle.el ends here