ob-tangle.el 11 KB

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