org-babel-tangle.el 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. ;;; org-babel-tangle.el --- Extract source code from org-mode files
  2. ;; Copyright (C) 2009 Dan Davison, Eric Schulte
  3. ;; Author: Dan Davison, Eric Schulte
  4. ;; Keywords: literate programming, reproducible research
  5. ;; Homepage: http://orgmode.org
  6. ;; Version: 0.01
  7. ;;; License:
  8. ;; This program is free software; you can redistribute it and/or modify
  9. ;; it under the terms of the GNU General Public License as published by
  10. ;; the Free Software Foundation; either version 3, or (at your option)
  11. ;; any later version.
  12. ;;
  13. ;; This program is distributed in the hope that it will be useful,
  14. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. ;; GNU General Public License for more details.
  17. ;;
  18. ;; You should have received a copy of the GNU General Public License
  19. ;; along with GNU Emacs; see the file COPYING. If not, write to the
  20. ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  21. ;; Boston, MA 02110-1301, USA.
  22. ;;; Commentary:
  23. ;; Extract the code from source blocks out into raw source-code files.
  24. ;;; Code:
  25. (require 'org-babel)
  26. (defvar org-babel-tangle-langs nil
  27. "Association list matching source-block languages. The car of
  28. each element should be a string indicating the source block
  29. language, and the cdr should be a list containing the extension
  30. shebang(#!) line to use when writing out the language to file,
  31. and an optional flag indicating that the language is not
  32. commentable.")
  33. (defun org-babel-load-file (file)
  34. "Load the contents of the Emacs Lisp source code blocks in the
  35. org-mode formatted FILE. This function will first export the
  36. source code using `org-babel-tangle' and then load the resulting
  37. file using `load-file'."
  38. (flet ((age (file)
  39. (time-to-seconds
  40. (time-subtract (current-time)
  41. (sixth (file-attributes file))))))
  42. (let* ((base-name (file-name-sans-extension file))
  43. (exported-file (concat base-name ".el")))
  44. ;; tangle if the org-mode file is newer than the elisp file
  45. (unless (and (file-exists-p exported-file) (> (age file) (age exported-file)))
  46. (org-babel-tangle-file file base-name "emacs-lisp"))
  47. (load-file exported-file)
  48. (message "loaded %s" exported-file))))
  49. (defun org-babel-tangle-file (file &optional target-file lang)
  50. "Extract the bodies of all source code blocks in FILE with
  51. `org-babel-tangle'. Optional argument TARGET-FILE can be used to
  52. specify a default export file for all source blocks. Optional
  53. argument LANG can be used to limit the exported source code
  54. blocks by language."
  55. (save-window-excursion (find-file file) (org-babel-tangle target-file lang)))
  56. (defun org-babel-tangle (&optional target-file lang)
  57. "Extract the bodies of all source code blocks from the current
  58. file into their own source-specific files. Optional argument
  59. TARGET-FILE can be used to specify a default export file for all
  60. source blocks. Optional argument LANG can be used to limit the
  61. exported source code blocks by language."
  62. (interactive)
  63. (save-excursion
  64. (let ((block-counter 0)
  65. path-collector)
  66. (mapc ;; map over all languages
  67. (lambda (by-lang)
  68. (let* ((lang (car by-lang))
  69. (specs (cdr by-lang))
  70. (lang-f (intern (concat
  71. (or (and (cdr (assoc lang org-src-lang-modes))
  72. (symbol-name
  73. (cdr (assoc lang org-src-lang-modes))))
  74. lang)
  75. "-mode")))
  76. (lang-specs (cdr (assoc lang org-babel-tangle-langs)))
  77. (ext (first lang-specs))
  78. (she-bang (second lang-specs))
  79. (commentable (not (third lang-specs))))
  80. (mapc
  81. (lambda (spec)
  82. (let* ((tangle (cdr (assoc :tangle (third spec))))
  83. (base-name (or (cond
  84. ((string= "yes" tangle)
  85. (file-name-sans-extension (buffer-file-name)))
  86. ((string= "no" tangle) nil)
  87. ((> (length tangle) 0) tangle))
  88. target-file))
  89. (file-name (when base-name
  90. (if (string= base-name
  91. (file-name-sans-extension base-name))
  92. (concat base-name "." ext) base-name))))
  93. ;; ;; debugging
  94. ;; (message "tangle=%S base-name=%S file-name=%S"
  95. ;; tangle base-name file-name)
  96. (when file-name
  97. ;; delete any old versions of file
  98. (when (and (file-exists-p file-name)
  99. (not (member file-name path-collector)))
  100. (delete-file file-name))
  101. ;; drop source-block to file
  102. (with-temp-buffer
  103. (funcall lang-f)
  104. (when she-bang (insert (concat she-bang "\n")))
  105. (when commentable
  106. (comment-region
  107. (point) (progn (insert "generated by org-babel-tangle") (point)))
  108. (move-end-of-line nil))
  109. (org-babel-spec-to-string spec)
  110. (append-to-file nil nil file-name))
  111. ;; update counter
  112. (setq block-counter (+ 1 block-counter))
  113. (add-to-list 'path-collector file-name))))
  114. specs)))
  115. (org-babel-tangle-collect-blocks lang))
  116. (message "tangled %d code block%s" block-counter
  117. (if (= block-counter 1) "" "s"))
  118. path-collector)))
  119. (defun org-babel-tangle-clean ()
  120. "Call this function inside of a source-code file generated by
  121. `org-babel-tangle' to remove all comments inserted automatically
  122. by `org-babel-tangle'. Warning, this comment removes any lines
  123. containing constructs which resemble org-mode file links or noweb
  124. references."
  125. (interactive)
  126. (goto-char (point-min))
  127. (while (or (re-search-forward "\\[\\[file:.*\\]\\[.*\\]\\]" nil t)
  128. (re-search-forward "<<[^[:space:]]*>>" nil t))
  129. (delete-region (save-excursion (move-beginning-of-line 1) (point))
  130. (save-excursion (move-end-of-line 1) (forward-char 1) (point)))))
  131. (defun org-babel-tangle-collect-blocks (&optional lang)
  132. "Collect all source blocks in the current org-mode file.
  133. Return an association list of source-code block specifications of
  134. the form used by `org-babel-spec-to-string' grouped by language.
  135. Optional argument LANG can be used to limit the collected source
  136. code blocks by language."
  137. (let ((block-counter 0) blocks)
  138. (org-babel-map-source-blocks (buffer-file-name)
  139. (setq block-counter (+ 1 block-counter))
  140. (let* ((link (progn (call-interactively 'org-store-link)
  141. (org-babel-clean-text-properties (car (pop org-stored-links)))))
  142. (source-name (intern (or (org-babel-get-src-block-name)
  143. (format "block-%d" block-counter))))
  144. (info (org-babel-get-src-block-info))
  145. (src-lang (first info))
  146. (body (org-babel-expand-noweb-references info))
  147. (params (third info))
  148. (spec (list link source-name params body (third (cdr (assoc src-lang org-babel-tangle-langs)))))
  149. by-lang)
  150. (unless (string= (cdr (assoc :tangle params)) "no") ;; maybe skip
  151. (unless (and lang (not (string= lang src-lang))) ;; maybe limit by language
  152. ;; add the spec for this block to blocks under it's language
  153. (setq by-lang (cdr (assoc src-lang blocks)))
  154. (setq blocks (delq (assoc src-lang blocks) blocks))
  155. (setq blocks (cons (cons src-lang (cons spec by-lang)) blocks))))))
  156. ;; ensure blocks in the correct order
  157. (setq blocks
  158. (mapcar (lambda (by-lang) (cons (car by-lang) (reverse (cdr by-lang)))) blocks))
  159. ;; blocks should contain all source-blocks organized by language
  160. ;; (message "blocks=%S" blocks) ;; debugging
  161. blocks))
  162. (defun org-babel-spec-to-string (spec)
  163. "Insert the source-code specified by SPEC into the current
  164. source code file. This function uses `comment-region' which
  165. assumes that the appropriate major-mode is set. SPEC has the
  166. form
  167. (link source-name params body)"
  168. (flet ((insert-comment (text)
  169. (when commentable
  170. (comment-region (point) (progn (insert text) (point)))
  171. (move-end-of-line nil))))
  172. (let ((link (first spec))
  173. (source-name (second spec))
  174. (body (fourth spec))
  175. (commentable (not (fifth spec))))
  176. (insert "\n\n")
  177. (insert-comment (format "[[%s][%s]]" (org-link-escape link) source-name))
  178. (insert (format "\n%s\n" (org-babel-chomp body)))
  179. (insert-comment (format "%s ends here" source-name))
  180. (insert "\n"))))
  181. (defun org-babel-expand-noweb-references (&optional info parent-buffer)
  182. "This function expands Noweb style references in the body of
  183. the current source-code block. For example the following
  184. reference would be replaced with the body of the source-code
  185. block named 'example-block' (assuming the '#' character starts a
  186. comment) .
  187. # <<example-block>>
  188. This function must be called from inside of the buffer containing
  189. the source-code block which holds BODY."
  190. (let* ((parent-buffer (or parent-buffer (current-buffer)))
  191. (info (or info (org-babel-get-src-block-info)))
  192. (lang (first info))
  193. (body (second info))
  194. (new-body "") index source-name)
  195. (flet ((nb-add (text)
  196. (setq new-body (concat new-body text))))
  197. (with-temp-buffer
  198. (insert body) (goto-char (point-min))
  199. (funcall (intern (concat (or (and (cdr (assoc lang org-src-lang-modes))
  200. (symbol-name
  201. (cdr (assoc lang org-src-lang-modes))))
  202. lang) "-mode")))
  203. (setq index (point))
  204. (while (and (re-search-forward "<<\\(.+\\)>>" nil t))
  205. (save-match-data (setf source-name (match-string 1)))
  206. ;; add interval to new-body
  207. (goto-char (match-end 0)) (move-end-of-line nil)
  208. (nb-add (buffer-substring index (point)))
  209. (setq index (point))
  210. ;; if found, add body of referenced source-block
  211. (nb-add (save-excursion
  212. (set-buffer parent-buffer)
  213. (let ((point (org-babel-find-named-block source-name)))
  214. (if point
  215. (save-excursion
  216. (goto-char point)
  217. (concat "\n" (org-babel-expand-noweb-references
  218. (org-babel-get-src-block-info))))
  219. "")))))
  220. (nb-add (buffer-substring index (point-max)))))
  221. new-body))
  222. (provide 'org-babel-tangle)
  223. ;;; org-babel-tangle.el ends here