New option `org-properties-postprocess-alist'.
[org-mode.git] / lisp / ob-tangle.el
blobf6450d6b6d3cdcca2d20f951ba2a4d3074d47d12
1 ;;; ob-tangle.el --- extract source code from org-mode files
3 ;; Copyright (C) 2009-2011 Free Software Foundation, Inc.
5 ;; Author: Eric Schulte
6 ;; Keywords: literate programming, reproducible research
7 ;; Homepage: http://orgmode.org
8 ;; Version: 7.7
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-body-hook nil
67 "Hook run over the contents of each code block body."
68 :group 'org-babel
69 :type 'hook)
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)))
122 (def-edebug-spec org-babel-with-temp-filebuffer (form body))
124 ;;;###autoload
125 (defun org-babel-load-file (file)
126 "Load Emacs Lisp source code blocks in the Org-mode FILE.
127 This function exports the source code using
128 `org-babel-tangle' and then loads the resulting file using
129 `load-file'."
130 (interactive "fFile to load: ")
131 (flet ((age (file)
132 (float-time
133 (time-subtract (current-time)
134 (nth 5 (or (file-attributes (file-truename file))
135 (file-attributes file)))))))
136 (let* ((base-name (file-name-sans-extension file))
137 (exported-file (concat base-name ".el")))
138 ;; tangle if the org-mode file is newer than the elisp file
139 (unless (and (file-exists-p exported-file)
140 (> (age file) (age exported-file)))
141 (org-babel-tangle-file file exported-file "emacs-lisp"))
142 (load-file exported-file)
143 (message "loaded %s" exported-file))))
145 ;;;###autoload
146 (defun org-babel-tangle-file (file &optional target-file lang)
147 "Extract the bodies of source code blocks in FILE.
148 Source code blocks are extracted with `org-babel-tangle'.
149 Optional argument TARGET-FILE can be used to specify a default
150 export file for all source blocks. Optional argument LANG can be
151 used to limit the exported source code blocks by language."
152 (interactive "fFile to tangle: \nP")
153 (let ((visited-p (get-file-buffer (expand-file-name file)))
154 to-be-removed)
155 (save-window-excursion
156 (find-file file)
157 (setq to-be-removed (current-buffer))
158 (org-babel-tangle nil target-file lang))
159 (unless visited-p
160 (kill-buffer to-be-removed))))
162 (defun org-babel-tangle-publish (_ filename pub-dir)
163 "Tangle FILENAME and place the results in PUB-DIR."
164 (mapc (lambda (el) (copy-file el pub-dir t)) (org-babel-tangle-file filename)))
166 ;;;###autoload
167 (defun org-babel-tangle (&optional only-this-block target-file lang)
168 "Write code blocks to source-specific files.
169 Extract the bodies of all source code blocks from the current
170 file into their own source-specific files. Optional argument
171 TARGET-FILE can be used to specify a default export file for all
172 source blocks. Optional argument LANG can be used to limit the
173 exported source code blocks by language."
174 (interactive "P")
175 (run-hooks 'org-babel-pre-tangle-hook)
176 ;; possibly restrict the buffer to the current code block
177 (save-restriction
178 (when only-this-block
179 (unless (org-babel-where-is-src-block-head)
180 (error "Point is not currently inside of a code block"))
181 (unless target-file
182 (setq target-file
183 (read-from-minibuffer "Tangle to: " (buffer-file-name))))
184 (narrow-to-region (match-beginning 0) (match-end 0)))
185 (save-excursion
186 (let ((block-counter 0)
187 (org-babel-default-header-args
188 (if target-file
189 (org-babel-merge-params org-babel-default-header-args
190 (list (cons :tangle target-file)))
191 org-babel-default-header-args))
192 path-collector)
193 (mapc ;; map over all languages
194 (lambda (by-lang)
195 (let* ((lang (car by-lang))
196 (specs (cdr by-lang))
197 (ext (or (cdr (assoc lang org-babel-tangle-lang-exts)) lang))
198 (lang-f (intern
199 (concat
200 (or (and (cdr (assoc lang org-src-lang-modes))
201 (symbol-name
202 (cdr (assoc lang org-src-lang-modes))))
203 lang)
204 "-mode")))
205 she-banged)
206 (mapc
207 (lambda (spec)
208 (flet ((get-spec (name)
209 (cdr (assoc name (nth 4 spec)))))
210 (let* ((tangle (get-spec :tangle))
211 (she-bang ((lambda (sheb) (when (> (length sheb) 0) sheb))
212 (get-spec :shebang)))
213 (base-name (cond
214 ((string= "yes" tangle)
215 (file-name-sans-extension
216 (buffer-file-name)))
217 ((string= "no" tangle) nil)
218 ((> (length tangle) 0) tangle)))
219 (file-name (when base-name
220 ;; decide if we want to add ext to base-name
221 (if (and ext (string= "yes" tangle))
222 (concat base-name "." ext) base-name))))
223 (when file-name
224 ;; possibly create the parent directories for file
225 (when ((lambda (m) (and m (not (string= m "no"))))
226 (get-spec :mkdirp))
227 (make-directory (file-name-directory file-name) 'parents))
228 ;; delete any old versions of file
229 (when (and (file-exists-p file-name)
230 (not (member file-name path-collector)))
231 (delete-file file-name))
232 ;; drop source-block to file
233 (with-temp-buffer
234 (when (fboundp lang-f) (ignore-errors (funcall lang-f)))
235 (when (and she-bang (not (member file-name she-banged)))
236 (insert (concat she-bang "\n"))
237 (setq she-banged (cons file-name she-banged)))
238 (org-babel-spec-to-string spec)
239 ;; We avoid append-to-file as it does not work with tramp.
240 (let ((content (buffer-string)))
241 (with-temp-buffer
242 (if (file-exists-p file-name)
243 (insert-file-contents file-name))
244 (goto-char (point-max))
245 (insert content)
246 (write-region nil nil file-name))))
247 ;; if files contain she-bangs, then make the executable
248 (when she-bang (set-file-modes file-name #o755))
249 ;; update counter
250 (setq block-counter (+ 1 block-counter))
251 (add-to-list 'path-collector file-name)))))
252 specs)))
253 (org-babel-tangle-collect-blocks lang))
254 (message "tangled %d code block%s from %s" block-counter
255 (if (= block-counter 1) "" "s")
256 (file-name-nondirectory
257 (buffer-file-name (or (buffer-base-buffer) (current-buffer)))))
258 ;; run `org-babel-post-tangle-hook' in all tangled files
259 (when org-babel-post-tangle-hook
260 (mapc
261 (lambda (file)
262 (org-babel-with-temp-filebuffer file
263 (run-hooks 'org-babel-post-tangle-hook)))
264 path-collector))
265 path-collector))))
267 (defun org-babel-tangle-clean ()
268 "Remove comments inserted by `org-babel-tangle'.
269 Call this function inside of a source-code file generated by
270 `org-babel-tangle' to remove all comments inserted automatically
271 by `org-babel-tangle'. Warning, this comment removes any lines
272 containing constructs which resemble org-mode file links or noweb
273 references."
274 (interactive)
275 (goto-char (point-min))
276 (while (or (re-search-forward "\\[\\[file:.*\\]\\[.*\\]\\]" nil t)
277 (re-search-forward "<<[^[:space:]]*>>" nil t))
278 (delete-region (save-excursion (beginning-of-line 1) (point))
279 (save-excursion (end-of-line 1) (forward-char 1) (point)))))
281 (defvar org-stored-links)
282 (defvar org-bracket-link-regexp)
283 (defun org-babel-tangle-collect-blocks (&optional language)
284 "Collect source blocks in the current Org-mode file.
285 Return an association list of source-code block specifications of
286 the form used by `org-babel-spec-to-string' grouped by language.
287 Optional argument LANG can be used to limit the collected source
288 code blocks by language."
289 (let ((block-counter 1) (current-heading "") blocks)
290 (org-babel-map-src-blocks (buffer-file-name)
291 ((lambda (new-heading)
292 (if (not (string= new-heading current-heading))
293 (progn
294 (setq block-counter 1)
295 (setq current-heading new-heading))
296 (setq block-counter (+ 1 block-counter))))
297 (replace-regexp-in-string "[ \t]" "-"
298 (condition-case nil
299 (nth 4 (org-heading-components))
300 (error (buffer-file-name)))))
301 (let* ((start-line (save-restriction (widen)
302 (+ 1 (line-number-at-pos (point)))))
303 (file (buffer-file-name))
304 (info (org-babel-get-src-block-info 'light))
305 (src-lang (nth 0 info)))
306 (unless (string= (cdr (assoc :tangle (nth 2 info))) "no")
307 (unless (and language (not (string= language src-lang)))
308 (let* ((info (org-babel-get-src-block-info))
309 (params (nth 2 info))
310 (link ((lambda (link)
311 (and (string-match org-bracket-link-regexp link)
312 (match-string 1 link)))
313 (org-babel-clean-text-properties
314 (org-store-link nil))))
315 (source-name
316 (intern (or (nth 4 info)
317 (format "%s:%d"
318 current-heading block-counter))))
319 (expand-cmd
320 (intern (concat "org-babel-expand-body:" src-lang)))
321 (assignments-cmd
322 (intern (concat "org-babel-variable-assignments:" src-lang)))
323 (body
324 ((lambda (body) ;; run the tangle-body-hook
325 (with-temp-buffer
326 (insert body)
327 (run-hooks 'org-babel-tangle-body-hook)
328 (buffer-string)))
329 ((lambda (body) ;; expand the body in language specific manner
330 (if (assoc :no-expand params)
331 body
332 (if (fboundp expand-cmd)
333 (funcall expand-cmd body params)
334 (org-babel-expand-body:generic
335 body params
336 (and (fboundp assignments-cmd)
337 (funcall assignments-cmd params))))))
338 (if (and (cdr (assoc :noweb params)) ;; expand noweb refs
339 (let ((nowebs (split-string
340 (cdr (assoc :noweb params)))))
341 (or (member "yes" nowebs)
342 (member "tangle" nowebs))))
343 (org-babel-expand-noweb-references info)
344 (nth 1 info)))))
345 (comment
346 (when (or (string= "both" (cdr (assoc :comments params)))
347 (string= "org" (cdr (assoc :comments params))))
348 ;; from the previous heading or code-block end
349 (buffer-substring
350 (max (condition-case nil
351 (save-excursion
352 (org-back-to-heading t) (point))
353 (error 0))
354 (save-excursion
355 (re-search-backward
356 org-babel-src-block-regexp nil t)
357 (match-end 0)))
358 (point))))
359 by-lang)
360 ;; add the spec for this block to blocks under it's language
361 (setq by-lang (cdr (assoc src-lang blocks)))
362 (setq blocks (delq (assoc src-lang blocks) blocks))
363 (setq blocks (cons
364 (cons src-lang
365 (cons (list start-line file link
366 source-name params body comment)
367 by-lang)) blocks)))))))
368 ;; ensure blocks in the correct order
369 (setq blocks
370 (mapcar
371 (lambda (by-lang) (cons (car by-lang) (reverse (cdr by-lang))))
372 blocks))
373 blocks))
375 (defun org-babel-spec-to-string (spec)
376 "Insert SPEC into the current file.
377 Insert the source-code specified by SPEC into the current
378 source code file. This function uses `comment-region' which
379 assumes that the appropriate major-mode is set. SPEC has the
380 form
382 (start-line file link source-name params body comment)"
383 (let* ((start-line (nth 0 spec))
384 (file (nth 1 spec))
385 (link (org-link-escape (nth 2 spec)))
386 (source-name (nth 3 spec))
387 (body (nth 5 spec))
388 (comment (nth 6 spec))
389 (comments (cdr (assoc :comments (nth 4 spec))))
390 (padline (not (string= "no" (cdr (assoc :padline (nth 4 spec))))))
391 (link-p (or (string= comments "both") (string= comments "link")
392 (string= comments "yes") (string= comments "noweb")))
393 (link-data (mapcar (lambda (el)
394 (cons (symbol-name el)
395 ((lambda (le)
396 (if (stringp le) le (format "%S" le)))
397 (eval el))))
398 '(start-line file link source-name))))
399 (flet ((insert-comment (text)
400 (let ((text (org-babel-trim text)))
401 (when (and comments (not (string= comments "no"))
402 (> (length text) 0))
403 (when padline (insert "\n"))
404 (comment-region (point) (progn (insert text) (point)))
405 (end-of-line nil) (insert "\n")))))
406 (when comment (insert-comment comment))
407 (when link-p
408 (insert-comment
409 (org-fill-template org-babel-tangle-comment-format-beg link-data)))
410 (when padline (insert "\n"))
411 (insert
412 (format
413 "%s\n"
414 (replace-regexp-in-string
415 "^," ""
416 (org-babel-trim body (if org-src-preserve-indentation "[\f\n\r\v]")))))
417 (when link-p
418 (insert-comment
419 (org-fill-template org-babel-tangle-comment-format-end link-data))))))
421 (defun org-babel-tangle-comment-links ( &optional info)
422 "Return a list of begin and end link comments for the code block at point."
423 (let* ((start-line (org-babel-where-is-src-block-head))
424 (file (buffer-file-name))
425 (link (org-link-escape (progn (call-interactively 'org-store-link)
426 (org-babel-clean-text-properties
427 (car (pop org-stored-links))))))
428 (source-name (nth 4 (or info (org-babel-get-src-block-info 'light))))
429 (link-data (mapcar (lambda (el)
430 (cons (symbol-name el)
431 ((lambda (le)
432 (if (stringp le) le (format "%S" le)))
433 (eval el))))
434 '(start-line file link source-name))))
435 (list (org-fill-template org-babel-tangle-comment-format-beg link-data)
436 (org-fill-template org-babel-tangle-comment-format-end link-data))))
438 ;; de-tangling functions
439 (defvar org-bracket-link-analytic-regexp)
440 (defun org-babel-detangle (&optional source-code-file)
441 "Propagate changes in source file back original to Org-mode file.
442 This requires that code blocks were tangled with link comments
443 which enable the original code blocks to be found."
444 (interactive)
445 (save-excursion
446 (when source-code-file (find-file source-code-file))
447 (goto-char (point-min))
448 (let ((counter 0) new-body end)
449 (while (re-search-forward org-bracket-link-analytic-regexp nil t)
450 (when (re-search-forward
451 (concat " " (regexp-quote (match-string 5)) " ends here"))
452 (setq end (match-end 0))
453 (forward-line -1)
454 (save-excursion
455 (when (setq new-body (org-babel-tangle-jump-to-org))
456 (org-babel-update-block-body new-body)))
457 (setq counter (+ 1 counter)))
458 (goto-char end))
459 (prog1 counter (message "detangled %d code blocks" counter)))))
461 (defun org-babel-tangle-jump-to-org ()
462 "Jump from a tangled code file to the related Org-mode file."
463 (interactive)
464 (let ((mid (point))
465 start end done
466 target-buffer target-char link path block-name body)
467 (save-window-excursion
468 (save-excursion
469 (while (and (re-search-backward org-bracket-link-analytic-regexp nil t)
470 (not ; ever wider searches until matching block comments
471 (and (setq start (point-at-eol))
472 (setq link (match-string 0))
473 (setq path (match-string 3))
474 (setq block-name (match-string 5))
475 (save-excursion
476 (save-match-data
477 (re-search-forward
478 (concat " " (regexp-quote block-name)
479 " ends here") nil t)
480 (setq end (point-at-bol))))))))
481 (unless (and start (< start mid) (< mid end))
482 (error "not in tangled code"))
483 (setq body (org-babel-trim (buffer-substring start end))))
484 (when (string-match "::" path)
485 (setq path (substring path 0 (match-beginning 0))))
486 (find-file path) (setq target-buffer (current-buffer))
487 (goto-char start) (org-open-link-from-string link)
488 (if (string-match "[^ \t\n\r]:\\([[:digit:]]+\\)" block-name)
489 (org-babel-next-src-block
490 (string-to-number (match-string 1 block-name)))
491 (org-babel-goto-named-src-block block-name))
492 (setq target-char (point)))
493 (pop-to-buffer target-buffer)
494 (prog1 body (goto-char target-char))))
496 (provide 'ob-tangle)
500 ;;; ob-tangle.el ends here