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
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/>.
26 ;; Extract the code from source blocks out into raw source-code files.
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
))
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
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'."
60 (defcustom org-babel-pre-tangle-hook
'(save-buffer)
61 "Hook run at the beginning of `org-babel-tangle'."
65 (defcustom org-babel-tangle-body-hook nil
66 "Hook run over the contents of each code block body."
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."
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."
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
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
))
121 (def-edebug-spec org-babel-with-temp-filebuffer
(form body
))
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
129 (interactive "fFile to load: ")
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
))))
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
)))
154 (save-window-excursion
156 (setq to-be-removed
(current-buffer))
157 (org-babel-tangle nil target-file lang
))
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
)))
166 (defun org-babel-tangle (&optional only-this-block 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."
174 (run-hooks 'org-babel-pre-tangle-hook
)
175 ;; possibly restrict the buffer to the current code block
177 (when only-this-block
178 (unless (org-babel-where-is-src-block-head)
179 (error "Point is not currently inside of a code block"))
182 (read-from-minibuffer "Tangle to: " (buffer-file-name))))
183 (narrow-to-region (match-beginning 0) (match-end 0)))
185 (let ((block-counter 0)
186 (org-babel-default-header-args
188 (org-babel-merge-params org-babel-default-header-args
189 (list (cons :tangle target-file
)))
190 org-babel-default-header-args
))
192 (mapc ;; map over all languages
194 (let* ((lang (car by-lang
))
195 (specs (cdr by-lang
))
196 (ext (or (cdr (assoc lang org-babel-tangle-lang-exts
)) lang
))
199 (or (and (cdr (assoc lang org-src-lang-modes
))
201 (cdr (assoc lang org-src-lang-modes
))))
207 (flet ((get-spec (name)
208 (cdr (assoc name
(nth 4 spec
)))))
209 (let* ((tangle (get-spec :tangle
))
210 (she-bang ((lambda (sheb) (when (> (length sheb
) 0) sheb
))
211 (get-spec :shebang
)))
213 ((string= "yes" tangle
)
214 (file-name-sans-extension
216 ((string= "no" tangle
) nil
)
217 ((> (length tangle
) 0) tangle
)))
218 (file-name (when base-name
219 ;; decide if we want to add ext to base-name
220 (if (and ext
(string= "yes" tangle
))
221 (concat base-name
"." ext
) base-name
))))
223 ;; possibly create the parent directories for file
224 (when ((lambda (m) (and m
(not (string= m
"no"))))
226 (make-directory (file-name-directory file-name
) 'parents
))
227 ;; delete any old versions of file
228 (when (and (file-exists-p file-name
)
229 (not (member file-name path-collector
)))
230 (delete-file file-name
))
231 ;; drop source-block to file
233 (when (fboundp lang-f
) (ignore-errors (funcall lang-f
)))
234 (when (and she-bang
(not (member file-name she-banged
)))
235 (insert (concat she-bang
"\n"))
236 (setq she-banged
(cons file-name she-banged
)))
237 (org-babel-spec-to-string spec
)
238 ;; We avoid append-to-file as it does not work with tramp.
239 (let ((content (buffer-string)))
241 (if (file-exists-p file-name
)
242 (insert-file-contents file-name
))
243 (goto-char (point-max))
245 (write-region nil nil file-name
))))
246 ;; if files contain she-bangs, then make the executable
247 (when she-bang
(set-file-modes file-name
#o755
))
249 (setq block-counter
(+ 1 block-counter
))
250 (add-to-list 'path-collector file-name
)))))
252 (org-babel-tangle-collect-blocks lang
))
253 (message "tangled %d code block%s from %s" block-counter
254 (if (= block-counter
1) "" "s")
255 (file-name-nondirectory
256 (buffer-file-name (or (buffer-base-buffer) (current-buffer)))))
257 ;; run `org-babel-post-tangle-hook' in all tangled files
258 (when org-babel-post-tangle-hook
261 (org-babel-with-temp-filebuffer file
262 (run-hooks 'org-babel-post-tangle-hook
)))
266 (defun org-babel-tangle-clean ()
267 "Remove comments inserted by `org-babel-tangle'.
268 Call this function inside of a source-code file generated by
269 `org-babel-tangle' to remove all comments inserted automatically
270 by `org-babel-tangle'. Warning, this comment removes any lines
271 containing constructs which resemble org-mode file links or noweb
274 (goto-char (point-min))
275 (while (or (re-search-forward "\\[\\[file:.*\\]\\[.*\\]\\]" nil t
)
276 (re-search-forward "<<[^[:space:]]*>>" nil t
))
277 (delete-region (save-excursion (beginning-of-line 1) (point))
278 (save-excursion (end-of-line 1) (forward-char 1) (point)))))
280 (defvar org-stored-links
)
281 (defvar org-bracket-link-regexp
)
282 (defun org-babel-tangle-collect-blocks (&optional language
)
283 "Collect source blocks in the current Org-mode file.
284 Return an association list of source-code block specifications of
285 the form used by `org-babel-spec-to-string' grouped by language.
286 Optional argument LANG can be used to limit the collected source
287 code blocks by language."
288 (let ((block-counter 1) (current-heading "") blocks
)
289 (org-babel-map-src-blocks (buffer-file-name)
290 ((lambda (new-heading)
291 (if (not (string= new-heading current-heading
))
293 (setq block-counter
1)
294 (setq current-heading new-heading
))
295 (setq block-counter
(+ 1 block-counter
))))
296 (replace-regexp-in-string "[ \t]" "-"
298 (nth 4 (org-heading-components))
299 (error (buffer-file-name)))))
300 (let* ((start-line (save-restriction (widen)
301 (+ 1 (line-number-at-pos (point)))))
302 (file (buffer-file-name))
303 (info (org-babel-get-src-block-info 'light
))
304 (src-lang (nth 0 info
)))
305 (unless (string= (cdr (assoc :tangle
(nth 2 info
))) "no")
306 (unless (and language
(not (string= language src-lang
)))
307 (let* ((info (org-babel-get-src-block-info))
308 (params (nth 2 info
))
309 (link ((lambda (link)
310 (and (string-match org-bracket-link-regexp link
)
311 (match-string 1 link
)))
312 (org-babel-clean-text-properties
313 (org-store-link nil
))))
315 (intern (or (nth 4 info
)
317 current-heading block-counter
))))
319 (intern (concat "org-babel-expand-body:" src-lang
)))
321 (intern (concat "org-babel-variable-assignments:" src-lang
)))
323 ((lambda (body) ;; run the tangle-body-hook
326 (run-hooks 'org-babel-tangle-body-hook
)
328 ((lambda (body) ;; expand the body in language specific manner
329 (if (assoc :no-expand params
)
331 (if (fboundp expand-cmd
)
332 (funcall expand-cmd body params
)
333 (org-babel-expand-body:generic
335 (and (fboundp assignments-cmd
)
336 (funcall assignments-cmd params
))))))
337 (if (and (cdr (assoc :noweb params
)) ;; expand noweb refs
338 (let ((nowebs (split-string
339 (cdr (assoc :noweb params
)))))
340 (or (member "yes" nowebs
)
341 (member "tangle" nowebs
))))
342 (org-babel-expand-noweb-references info
)
345 (when (or (string= "both" (cdr (assoc :comments params
)))
346 (string= "org" (cdr (assoc :comments params
))))
347 ;; from the previous heading or code-block end
349 (max (condition-case nil
351 (org-back-to-heading t
) (point))
355 org-babel-src-block-regexp nil t
)
359 ;; add the spec for this block to blocks under it's language
360 (setq by-lang
(cdr (assoc src-lang blocks
)))
361 (setq blocks
(delq (assoc src-lang blocks
) blocks
))
364 (cons (list start-line file link
365 source-name params body comment
)
366 by-lang
)) blocks
)))))))
367 ;; ensure blocks in the correct order
370 (lambda (by-lang) (cons (car by-lang
) (reverse (cdr by-lang
))))
374 (defun org-babel-spec-to-string (spec)
375 "Insert SPEC into the current file.
376 Insert the source-code specified by SPEC into the current
377 source code file. This function uses `comment-region' which
378 assumes that the appropriate major-mode is set. SPEC has the
381 (start-line file link source-name params body comment)"
382 (let* ((start-line (nth 0 spec
))
384 (link (org-link-escape (nth 2 spec
)))
385 (source-name (nth 3 spec
))
387 (comment (nth 6 spec
))
388 (comments (cdr (assoc :comments
(nth 4 spec
))))
389 (padline (not (string= "no" (cdr (assoc :padline
(nth 4 spec
))))))
390 (link-p (or (string= comments
"both") (string= comments
"link")
391 (string= comments
"yes") (string= comments
"noweb")))
392 (link-data (mapcar (lambda (el)
393 (cons (symbol-name el
)
395 (if (stringp le
) le
(format "%S" le
)))
397 '(start-line file link source-name
))))
398 (flet ((insert-comment (text)
399 (let ((text (org-babel-trim text
)))
400 (when (and comments
(not (string= comments
"no"))
402 (when padline
(insert "\n"))
403 (comment-region (point) (progn (insert text
) (point)))
404 (end-of-line nil
) (insert "\n")))))
405 (when comment
(insert-comment comment
))
408 (org-fill-template org-babel-tangle-comment-format-beg link-data
)))
409 (when padline
(insert "\n"))
413 (replace-regexp-in-string
415 (org-babel-trim body
(if org-src-preserve-indentation
"[\f\n\r\v]")))))
418 (org-fill-template org-babel-tangle-comment-format-end link-data
))))))
420 (defun org-babel-tangle-comment-links ( &optional info
)
421 "Return a list of begin and end link comments for the code block at point."
422 (let* ((start-line (org-babel-where-is-src-block-head))
423 (file (buffer-file-name))
424 (link (org-link-escape (progn (call-interactively 'org-store-link
)
425 (org-babel-clean-text-properties
426 (car (pop org-stored-links
))))))
427 (source-name (nth 4 (or info
(org-babel-get-src-block-info 'light
))))
428 (link-data (mapcar (lambda (el)
429 (cons (symbol-name el
)
431 (if (stringp le
) le
(format "%S" le
)))
433 '(start-line file link source-name
))))
434 (list (org-fill-template org-babel-tangle-comment-format-beg link-data
)
435 (org-fill-template org-babel-tangle-comment-format-end link-data
))))
437 ;; de-tangling functions
438 (defvar org-bracket-link-analytic-regexp
)
439 (defun org-babel-detangle (&optional source-code-file
)
440 "Propagate changes in source file back original to Org-mode file.
441 This requires that code blocks were tangled with link comments
442 which enable the original code blocks to be found."
445 (when source-code-file
(find-file source-code-file
))
446 (goto-char (point-min))
447 (let ((counter 0) new-body end
)
448 (while (re-search-forward org-bracket-link-analytic-regexp nil t
)
449 (when (re-search-forward
450 (concat " " (regexp-quote (match-string 5)) " ends here"))
451 (setq end
(match-end 0))
454 (when (setq new-body
(org-babel-tangle-jump-to-org))
455 (org-babel-update-block-body new-body
)))
456 (setq counter
(+ 1 counter
)))
458 (prog1 counter
(message "detangled %d code blocks" counter
)))))
460 (defun org-babel-tangle-jump-to-org ()
461 "Jump from a tangled code file to the related Org-mode file."
465 target-buffer target-char link path block-name body
)
466 (save-window-excursion
468 (while (and (re-search-backward org-bracket-link-analytic-regexp nil t
)
469 (not ; ever wider searches until matching block comments
470 (and (setq start
(point-at-eol))
471 (setq link
(match-string 0))
472 (setq path
(match-string 3))
473 (setq block-name
(match-string 5))
477 (concat " " (regexp-quote block-name
)
479 (setq end
(point-at-bol))))))))
480 (unless (and start
(< start mid
) (< mid end
))
481 (error "not in tangled code"))
482 (setq body
(org-babel-trim (buffer-substring start end
))))
483 (when (string-match "::" path
)
484 (setq path
(substring path
0 (match-beginning 0))))
485 (find-file path
) (setq target-buffer
(current-buffer))
486 (goto-char start
) (org-open-link-from-string link
)
487 (if (string-match "[^ \t\n\r]:\\([[:digit:]]+\\)" block-name
)
488 (org-babel-next-src-block
489 (string-to-number (match-string 1 block-name
)))
490 (org-babel-goto-named-src-block block-name
))
491 (setq target-char
(point)))
492 (pop-to-buffer target-buffer
)
493 (prog1 body
(goto-char target-char
))))
499 ;;; ob-tangle.el ends here