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