ob-tangle.el 11 KB

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