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