ob-tangle.el 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. ;;; ob-tangle.el --- extract source code from org-mode files
  2. ;; Copyright (C) 2009, 2010 Free Software Foundation, Inc.
  3. ;; Author: Eric Schulte
  4. ;; Keywords: literate programming, reproducible research
  5. ;; Homepage: http://orgmode.org
  6. ;; Version: 0.01
  7. ;; This file is part of GNU Emacs.
  8. ;; GNU Emacs 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 of the License, or
  11. ;; (at your option) any later version.
  12. ;; GNU Emacs is distributed in the hope that it will be useful,
  13. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. ;; GNU General Public License for more details.
  16. ;; You should have received a copy of the GNU General Public License
  17. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  18. ;;; Commentary:
  19. ;; Extract the code from source blocks out into raw source-code files.
  20. ;;; Code:
  21. (require 'ob)
  22. (require 'org-src)
  23. (eval-when-compile
  24. (require 'cl))
  25. (declare-function org-link-escape "org" (text &optional table))
  26. (defcustom org-babel-tangle-lang-exts
  27. '(("emacs-lisp" . "el"))
  28. "Alist mapping languages to their file extensions.
  29. The key is the language name, the value is the string that should
  30. be inserted as the extension commonly used to identify files
  31. written in this language. If no entry is found in this list,
  32. then the name of the language is used."
  33. :group 'org-babel-tangle
  34. :type '(repeat
  35. (cons
  36. (string "Language name")
  37. (string "File Extension"))))
  38. ;;;###autoload
  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. (float-time
  46. (time-subtract (current-time)
  47. (nth 5 (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. ;;;###autoload
  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. ;;;###autoload
  77. (defun org-babel-tangle (&optional target-file lang)
  78. "Extract the bodies of all source code blocks from the current
  79. file into their own source-specific files. Optional argument
  80. TARGET-FILE can be used to specify a default export file for all
  81. source blocks. Optional argument LANG can be used to limit the
  82. exported source code blocks by language."
  83. (interactive)
  84. (save-buffer)
  85. (save-excursion
  86. (let ((block-counter 0)
  87. path-collector)
  88. (mapc ;; map over all languages
  89. (lambda (by-lang)
  90. (let* ((lang (car by-lang))
  91. (specs (cdr by-lang))
  92. (ext (or (cdr (assoc lang org-babel-tangle-lang-exts)) lang))
  93. (lang-f (intern
  94. (concat
  95. (or (and (cdr (assoc lang org-src-lang-modes))
  96. (symbol-name
  97. (cdr (assoc lang org-src-lang-modes))))
  98. lang)
  99. "-mode")))
  100. she-banged)
  101. (mapc
  102. (lambda (spec)
  103. (flet ((get-spec (name)
  104. (cdr (assoc name (nth 2 spec)))))
  105. (let* ((tangle (get-spec :tangle))
  106. (she-bang ((lambda (sheb) (when (> (length sheb) 0) sheb))
  107. (get-spec :shebang)))
  108. (base-name (or (cond
  109. ((string= "yes" tangle)
  110. (file-name-sans-extension
  111. (buffer-file-name)))
  112. ((string= "no" tangle) nil)
  113. ((> (length tangle) 0) tangle))
  114. target-file))
  115. (file-name (when base-name
  116. ;; decide if we want to add ext to base-name
  117. (if (and ext (string= "yes" tangle))
  118. (concat base-name "." ext) base-name))))
  119. (when file-name
  120. ;; delete any old versions of file
  121. (when (and (file-exists-p file-name)
  122. (not (member file-name path-collector)))
  123. (delete-file file-name))
  124. ;; drop source-block to file
  125. (with-temp-buffer
  126. (if (fboundp lang-f) (funcall lang-f))
  127. (when (and she-bang (not (member file-name she-banged)))
  128. (insert (concat she-bang "\n"))
  129. (setq she-banged (cons file-name she-banged)))
  130. (org-babel-spec-to-string spec)
  131. ;; We avoid append-to-file as it does not work with tramp.
  132. (let ((content (buffer-string)))
  133. (with-temp-buffer
  134. (if (file-exists-p file-name)
  135. (insert-file-contents file-name))
  136. (goto-char (point-max))
  137. (insert content)
  138. (write-region nil nil file-name))))
  139. ;; if files contain she-bangs, then make the executable
  140. (when she-bang (set-file-modes file-name ?\755))
  141. ;; update counter
  142. (setq block-counter (+ 1 block-counter))
  143. (add-to-list 'path-collector file-name)))))
  144. specs)))
  145. (org-babel-tangle-collect-blocks lang))
  146. (message "tangled %d code block%s" block-counter
  147. (if (= block-counter 1) "" "s"))
  148. path-collector)))
  149. (defun org-babel-tangle-clean ()
  150. "Call this function inside of a source-code file generated by
  151. `org-babel-tangle' to remove all comments inserted automatically
  152. by `org-babel-tangle'. Warning, this comment removes any lines
  153. containing constructs which resemble org-mode file links or noweb
  154. references."
  155. (interactive)
  156. (goto-char (point-min))
  157. (while (or (re-search-forward "\\[\\[file:.*\\]\\[.*\\]\\]" nil t)
  158. (re-search-forward "<<[^[:space:]]*>>" nil t))
  159. (delete-region (save-excursion (beginning-of-line 1) (point))
  160. (save-excursion (end-of-line 1) (forward-char 1) (point)))))
  161. (defvar org-stored-links)
  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 (nth 4 info)
  176. (format "block-%d" block-counter))))
  177. (src-lang (nth 0 info))
  178. (expand-cmd (intern (concat "org-babel-expand-body:" src-lang)))
  179. (params (nth 2 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. (nth 1 info))))
  206. by-lang)) blocks))))))
  207. ;; ensure blocks in the correct order
  208. (setq blocks
  209. (mapcar
  210. (lambda (by-lang) (cons (car by-lang) (reverse (cdr by-lang))))
  211. blocks))
  212. blocks))
  213. (defun org-babel-spec-to-string (spec)
  214. "Insert the source-code specified by SPEC into the current
  215. source code file. This function uses `comment-region' which
  216. assumes that the appropriate major-mode is set. SPEC has the
  217. form
  218. (link source-name params body)"
  219. (let ((link (nth 0 spec))
  220. (source-name (nth 1 spec))
  221. (body (nth 3 spec))
  222. (commentable (string= (cdr (assoc :comments (nth 2 spec))) "yes")))
  223. (flet ((insert-comment (text)
  224. (when commentable
  225. (insert "\n")
  226. (comment-region (point)
  227. (progn (insert text) (point)))
  228. (end-of-line nil)
  229. (insert "\n"))))
  230. (insert-comment (format "[[%s][%s]]" (org-link-escape link) source-name))
  231. (insert (format "\n%s\n" (replace-regexp-in-string
  232. "^," "" (org-babel-chomp body))))
  233. (insert-comment (format "%s ends here" source-name)))))
  234. (provide 'ob-tangle)
  235. ;; arch-tag: 413ced93-48f5-4216-86e4-3fc5df8c8f24
  236. ;;; ob-tangle.el ends here