ob-tangle.el 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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. (declare-function with-temp-filebuffer "org" (file &rest body))
  27. (defcustom org-babel-tangle-lang-exts
  28. '(("emacs-lisp" . "el"))
  29. "Alist mapping languages to their file extensions.
  30. The key is the language name, the value is the string that should
  31. be inserted as the extension commonly used to identify files
  32. written in this language. If no entry is found in this list,
  33. then the name of the language is used."
  34. :group 'org-babel-tangle
  35. :type '(repeat
  36. (cons
  37. (string "Language name")
  38. (string "File Extension"))))
  39. (defcustom org-babel-post-tangle-hook nil
  40. "Hook run in code files tangled by `org-babel-tangle'."
  41. :group 'org-babel
  42. :type 'hook)
  43. ;;;###autoload
  44. (defun org-babel-load-file (file)
  45. "Load the contents of the Emacs Lisp source code blocks in the
  46. org-mode formatted FILE. This function will first export the
  47. source code using `org-babel-tangle' and then load the resulting
  48. file using `load-file'."
  49. (flet ((age (file)
  50. (float-time
  51. (time-subtract (current-time)
  52. (nth 5 (or (file-attributes (file-truename file))
  53. (file-attributes file)))))))
  54. (let* ((base-name (file-name-sans-extension file))
  55. (exported-file (concat base-name ".el")))
  56. ;; tangle if the org-mode file is newer than the elisp file
  57. (unless (and (file-exists-p exported-file)
  58. (> (age file) (age exported-file)))
  59. (org-babel-tangle-file file exported-file "emacs-lisp"))
  60. (load-file exported-file)
  61. (message "loaded %s" exported-file))))
  62. ;;;###autoload
  63. (defun org-babel-tangle-file (file &optional target-file lang)
  64. "Extract the bodies of all source code blocks in FILE with
  65. `org-babel-tangle'. Optional argument TARGET-FILE can be used to
  66. specify a default export file for all source blocks. Optional
  67. argument LANG can be used to limit the exported source code
  68. blocks by language."
  69. (interactive "fFile to tangle: \nP")
  70. (let ((visited-p (get-file-buffer (expand-file-name file)))
  71. to-be-removed)
  72. (save-window-excursion
  73. (find-file file)
  74. (setq to-be-removed (current-buffer))
  75. (org-babel-tangle target-file lang))
  76. (unless visited-p
  77. (kill-buffer to-be-removed))))
  78. (defun org-babel-tangle-publish (_ filename pub-dir)
  79. "Tangle FILENAME and place the results in PUB-DIR."
  80. (mapc (lambda (el) (copy-file el pub-dir t)) (org-babel-tangle-file filename)))
  81. ;;;###autoload
  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. (when (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. ;; run `org-babel-post-tangle-hook' in all tangled files
  154. (when org-babel-post-tangle-hook
  155. (mapc
  156. (lambda (file)
  157. (with-temp-filebuffer file
  158. (run-hooks 'org-babel-post-tangle-hook)))
  159. path-collector))
  160. path-collector)))
  161. (defun org-babel-tangle-clean ()
  162. "Call this function inside of a source-code file generated by
  163. `org-babel-tangle' to remove all comments inserted automatically
  164. by `org-babel-tangle'. Warning, this comment removes any lines
  165. containing constructs which resemble org-mode file links or noweb
  166. references."
  167. (interactive)
  168. (goto-char (point-min))
  169. (while (or (re-search-forward "\\[\\[file:.*\\]\\[.*\\]\\]" nil t)
  170. (re-search-forward "<<[^[:space:]]*>>" nil t))
  171. (delete-region (save-excursion (beginning-of-line 1) (point))
  172. (save-excursion (end-of-line 1) (forward-char 1) (point)))))
  173. (defvar org-stored-links)
  174. (defun org-babel-tangle-collect-blocks (&optional lang)
  175. "Collect all source blocks in the current org-mode file.
  176. Return an association list of source-code block specifications of
  177. the form used by `org-babel-spec-to-string' grouped by language.
  178. Optional argument LANG can be used to limit the collected source
  179. code blocks by language."
  180. (let ((block-counter 0) blocks)
  181. (org-babel-map-source-blocks (buffer-file-name)
  182. (setq block-counter (+ 1 block-counter))
  183. (let* ((link (progn (call-interactively 'org-store-link)
  184. (org-babel-clean-text-properties
  185. (car (pop org-stored-links)))))
  186. (info (org-babel-get-src-block-info))
  187. (source-name (intern (or (nth 4 info)
  188. (format "block-%d" block-counter))))
  189. (src-lang (nth 0 info))
  190. (expand-cmd (intern (concat "org-babel-expand-body:" src-lang)))
  191. (params (nth 2 info))
  192. by-lang)
  193. (unless (string= (cdr (assoc :tangle params)) "no") ;; skip
  194. (unless (and lang (not (string= lang src-lang))) ;; limit by language
  195. ;; add the spec for this block to blocks under it's language
  196. (setq by-lang (cdr (assoc src-lang blocks)))
  197. (setq blocks (delq (assoc src-lang blocks) blocks))
  198. (setq blocks
  199. (cons
  200. (cons src-lang
  201. (cons (list link source-name params
  202. ((lambda (body)
  203. (if (assoc :no-expand params)
  204. body
  205. (funcall
  206. (if (fboundp expand-cmd)
  207. expand-cmd
  208. 'org-babel-expand-body:generic)
  209. body
  210. params)))
  211. (if (and (cdr (assoc :noweb params))
  212. (string=
  213. "yes"
  214. (cdr (assoc :noweb params))))
  215. (org-babel-expand-noweb-references
  216. info)
  217. (nth 1 info))))
  218. by-lang)) blocks))))))
  219. ;; ensure blocks in the correct order
  220. (setq blocks
  221. (mapcar
  222. (lambda (by-lang) (cons (car by-lang) (reverse (cdr by-lang))))
  223. blocks))
  224. blocks))
  225. (defun org-babel-spec-to-string (spec)
  226. "Insert the source-code specified by SPEC into the current
  227. source code file. This function uses `comment-region' which
  228. assumes that the appropriate major-mode is set. SPEC has the
  229. form
  230. (link source-name params body)"
  231. (let ((link (nth 0 spec))
  232. (source-name (nth 1 spec))
  233. (body (nth 3 spec))
  234. (commentable (string= (cdr (assoc :comments (nth 2 spec))) "yes")))
  235. (flet ((insert-comment (text)
  236. (when commentable
  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. ;; arch-tag: 413ced93-48f5-4216-86e4-3fc5df8c8f24
  248. ;;; ob-tangle.el ends here