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