org-babel-tangle.el 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. ;;; org-babel-tangle.el --- Extract source code from org-mode files
  2. ;; Copyright (C) 2009 Eric Schulte
  3. ;; Author: 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. "List of languages supported by `org-babel-tangle'. The first
  28. element of each language's list is a string indicating the name
  29. of the language, the second element should be the file extension
  30. of the language, an optional third element the shebang(#!) line
  31. to use when writing out the language to file, and an optional
  32. fourth element is a flag which when true indicates that the
  33. language does not support comments.")
  34. (defvar org-babel-tangle-w-comments nil
  35. "Control the insertion of comments into tangled code. Non-nil
  36. value will result in the insertion of comments for those
  37. languages with comment support.")
  38. (defun org-babel-load-file (file)
  39. "Load the contents of the Emacs Lisp source code blocks in the
  40. org-mode formatted FILE. This function will first export the
  41. source code using `org-babel-tangle' and then load the resulting
  42. file using `load-file'."
  43. (flet ((age (file)
  44. (time-to-seconds
  45. (time-subtract (current-time)
  46. (sixth (or (file-attributes (file-truename file))
  47. (file-attributes file)))))))
  48. (let* ((base-name (file-name-sans-extension file))
  49. (exported-file (concat base-name ".el")))
  50. ;; tangle if the org-mode file is newer than the elisp file
  51. (unless (and (file-exists-p exported-file)
  52. (> (age file) (age exported-file)))
  53. (org-babel-tangle-file file exported-file "emacs-lisp"))
  54. (load-file exported-file)
  55. (message "loaded %s" exported-file))))
  56. (defun org-babel-tangle-file (file &optional target-file lang)
  57. "Extract the bodies of all source code blocks in FILE with
  58. `org-babel-tangle'. Optional argument TARGET-FILE can be used to
  59. specify a default export file for all source blocks. Optional
  60. argument LANG can be used to limit the exported source code
  61. blocks by language."
  62. (interactive "fFile to tangle: \nP")
  63. (let ((visited-p (get-file-buffer (expand-file-name file)))
  64. to-be-removed)
  65. (save-window-excursion
  66. (find-file file)
  67. (setq to-be-removed (current-buffer))
  68. (org-babel-tangle target-file lang))
  69. (unless visited-p
  70. (kill-buffer to-be-removed))))
  71. (defun org-babel-tangle-publish (_ filename pub-dir)
  72. "Tangle FILENAME and place the results in PUB-DIR."
  73. (mapc (lambda (el) (copy-file el pub-dir t)) (org-babel-tangle-file filename)))
  74. (defun org-babel-tangle (&optional target-file lang)
  75. "Extract the bodies of all source code blocks from the current
  76. file into their own source-specific files. Optional argument
  77. TARGET-FILE can be used to specify a default export file for all
  78. source blocks. Optional argument LANG can be used to limit the
  79. exported source code blocks by language."
  80. (interactive)
  81. (save-buffer)
  82. (save-excursion
  83. (let ((block-counter 0)
  84. path-collector)
  85. (mapc ;; map over all languages
  86. (lambda (by-lang)
  87. (let* ((lang (car by-lang))
  88. (specs (cdr by-lang))
  89. (lang-f (intern
  90. (concat
  91. (or (and (cdr (assoc lang org-src-lang-modes))
  92. (symbol-name
  93. (cdr (assoc lang org-src-lang-modes))))
  94. lang)
  95. "-mode")))
  96. (lang-specs (cdr (assoc lang org-babel-tangle-langs)))
  97. (ext (first lang-specs))
  98. (she-bang (second lang-specs))
  99. (commentable (and (fboundp lang-f) (not (third lang-specs))))
  100. she-banged)
  101. (mapc
  102. (lambda (spec)
  103. (flet ((get-spec (name)
  104. (cdr (assoc name (third spec)))))
  105. (let* ((tangle (get-spec :tangle))
  106. (she-bang (if (> (length (get-spec :shebang)) 0)
  107. (get-spec :shebang)
  108. she-bang))
  109. (base-name (or (cond
  110. ((string= "yes" tangle)
  111. (file-name-sans-extension
  112. (buffer-file-name)))
  113. ((string= "no" tangle) nil)
  114. ((> (length tangle) 0) tangle))
  115. target-file))
  116. (file-name (when base-name
  117. ;; decide if we want to add ext to base-name
  118. (if (and ext (string= "yes" tangle))
  119. (concat base-name "." ext) base-name))))
  120. (when file-name
  121. ;; delete any old versions of file
  122. (when (and (file-exists-p file-name)
  123. (not (member file-name path-collector)))
  124. (delete-file file-name))
  125. ;; drop source-block to file
  126. (with-temp-buffer
  127. (if (fboundp lang-f) (funcall lang-f))
  128. (when (and she-bang (not (member file-name she-banged)))
  129. (insert (concat she-bang "\n"))
  130. (setq she-banged (cons file-name she-banged)))
  131. (org-babel-spec-to-string spec)
  132. ;; We avoid append-to-file as it does not work with tramp.
  133. (let ((content (buffer-string)))
  134. (with-temp-buffer
  135. (if (file-exists-p file-name)
  136. (insert-file-contents file-name))
  137. (goto-char (point-max))
  138. (insert content)
  139. (write-region nil nil file-name))))
  140. ;; if files contain she-bangs, then make the executable
  141. (when she-bang (set-file-modes file-name ?\755))
  142. ;; update counter
  143. (setq block-counter (+ 1 block-counter))
  144. (add-to-list 'path-collector file-name)))))
  145. specs)))
  146. (org-babel-tangle-collect-blocks lang))
  147. (message "tangled %d code block%s" block-counter
  148. (if (= block-counter 1) "" "s"))
  149. path-collector)))
  150. (defun org-babel-tangle-clean ()
  151. "Call this function inside of a source-code file generated by
  152. `org-babel-tangle' to remove all comments inserted automatically
  153. by `org-babel-tangle'. Warning, this comment removes any lines
  154. containing constructs which resemble org-mode file links or noweb
  155. references."
  156. (interactive)
  157. (goto-char (point-min))
  158. (while (or (re-search-forward "\\[\\[file:.*\\]\\[.*\\]\\]" nil t)
  159. (re-search-forward "<<[^[:space:]]*>>" nil t))
  160. (delete-region (save-excursion (beginning-of-line 1) (point))
  161. (save-excursion (end-of-line 1) (forward-char 1) (point)))))
  162. (defun org-babel-tangle-collect-blocks (&optional lang)
  163. "Collect all source blocks in the current org-mode file.
  164. Return an association list of source-code block specifications of
  165. the form used by `org-babel-spec-to-string' grouped by language.
  166. Optional argument LANG can be used to limit the collected source
  167. code blocks by language."
  168. (let ((block-counter 0) blocks)
  169. (org-babel-map-source-blocks (buffer-file-name)
  170. (setq block-counter (+ 1 block-counter))
  171. (let* ((link (progn (call-interactively 'org-store-link)
  172. (org-babel-clean-text-properties
  173. (car (pop org-stored-links)))))
  174. (info (org-babel-get-src-block-info))
  175. (source-name (intern (or (fifth info)
  176. (format "block-%d" block-counter))))
  177. (src-lang (first info))
  178. (expand-cmd (intern (concat "org-babel-expand-body:" src-lang)))
  179. (params (third info))
  180. by-lang)
  181. (unless (string= (cdr (assoc :tangle params)) "no") ;; skip
  182. (unless (and lang (not (string= lang src-lang))) ;; limit by language
  183. ;; add the spec for this block to blocks under it's language
  184. (setq by-lang (cdr (assoc src-lang blocks)))
  185. (setq blocks (delq (assoc src-lang blocks) blocks))
  186. (setq blocks
  187. (cons
  188. (cons src-lang
  189. (cons (list link source-name params
  190. ((lambda (body)
  191. (if (assoc :no-expand params)
  192. body
  193. (funcall
  194. (if (fboundp expand-cmd)
  195. expand-cmd
  196. 'org-babel-expand-body:generic)
  197. body
  198. params)))
  199. (if (and (cdr (assoc :noweb params))
  200. (string=
  201. "yes"
  202. (cdr (assoc :noweb params))))
  203. (org-babel-expand-noweb-references
  204. info)
  205. (second info)))
  206. (third
  207. (cdr (assoc src-lang
  208. org-babel-tangle-langs))))
  209. by-lang)) blocks))))))
  210. ;; ensure blocks in the correct order
  211. (setq blocks
  212. (mapcar
  213. (lambda (by-lang) (cons (car by-lang) (reverse (cdr by-lang))))
  214. blocks))
  215. ;; blocks should contain all source-blocks organized by language
  216. ;; (message "blocks=%S" blocks) ;; debugging
  217. blocks))
  218. (defun org-babel-spec-to-string (spec)
  219. "Insert the source-code specified by SPEC into the current
  220. source code file. This function uses `comment-region' which
  221. assumes that the appropriate major-mode is set. SPEC has the
  222. form
  223. (link source-name params body)"
  224. (flet ((insert-comment (text)
  225. (when (and commentable
  226. org-babel-tangle-w-comments)
  227. (insert "\n")
  228. (comment-region (point)
  229. (progn (insert text) (point)))
  230. (end-of-line nil)
  231. (insert "\n"))))
  232. (let ((link (first spec))
  233. (source-name (second spec))
  234. (body (fourth spec))
  235. (commentable (not (if (> (length (cdr (assoc :comments (third spec))))
  236. 0)
  237. (string= (cdr (assoc :comments (third spec)))
  238. "no")
  239. (fifth spec)))))
  240. (insert-comment (format "[[%s][%s]]" (org-link-escape link) source-name))
  241. (insert (format "\n%s\n" (org-babel-chomp body)))
  242. (insert-comment (format "%s ends here" source-name)))))
  243. (provide 'org-babel-tangle)
  244. ;;; org-babel-tangle.el ends here