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