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