ob-tangle.el 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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-interaction" (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. (org-babel-default-header-args
  93. (if target-file
  94. (org-babel-merge-params org-babel-default-header-args
  95. (list (cons :tangle target-file)))
  96. org-babel-default-header-args))
  97. path-collector)
  98. (mapc ;; map over all languages
  99. (lambda (by-lang)
  100. (let* ((lang (car by-lang))
  101. (specs (cdr by-lang))
  102. (ext (or (cdr (assoc lang org-babel-tangle-lang-exts)) lang))
  103. (lang-f (intern
  104. (concat
  105. (or (and (cdr (assoc lang org-src-lang-modes))
  106. (symbol-name
  107. (cdr (assoc lang org-src-lang-modes))))
  108. lang)
  109. "-mode")))
  110. she-banged)
  111. (mapc
  112. (lambda (spec)
  113. (flet ((get-spec (name)
  114. (cdr (assoc name (nth 2 spec)))))
  115. (let* ((tangle (get-spec :tangle))
  116. (she-bang ((lambda (sheb) (when (> (length sheb) 0) sheb))
  117. (get-spec :shebang)))
  118. (base-name (cond
  119. ((string= "yes" tangle)
  120. (file-name-sans-extension
  121. (buffer-file-name)))
  122. ((string= "no" tangle) nil)
  123. ((> (length tangle) 0) tangle)))
  124. (file-name (when base-name
  125. ;; decide if we want to add ext to base-name
  126. (if (and ext (string= "yes" tangle))
  127. (concat base-name "." ext) base-name))))
  128. (when file-name
  129. ;; delete any old versions of file
  130. (when (and (file-exists-p file-name)
  131. (not (member file-name path-collector)))
  132. (delete-file file-name))
  133. ;; drop source-block to file
  134. (with-temp-buffer
  135. (when (fboundp lang-f) (funcall lang-f))
  136. (when (and she-bang (not (member file-name she-banged)))
  137. (insert (concat she-bang "\n"))
  138. (setq she-banged (cons file-name she-banged)))
  139. (org-babel-spec-to-string spec)
  140. ;; We avoid append-to-file as it does not work with tramp.
  141. (let ((content (buffer-string)))
  142. (with-temp-buffer
  143. (if (file-exists-p file-name)
  144. (insert-file-contents file-name))
  145. (goto-char (point-max))
  146. (insert content)
  147. (write-region nil nil file-name))))
  148. ;; if files contain she-bangs, then make the executable
  149. (when she-bang (set-file-modes file-name ?\755))
  150. ;; update counter
  151. (setq block-counter (+ 1 block-counter))
  152. (add-to-list 'path-collector file-name)))))
  153. specs)))
  154. (org-babel-tangle-collect-blocks lang))
  155. (message "tangled %d code block%s" block-counter
  156. (if (= block-counter 1) "" "s"))
  157. ;; run `org-babel-post-tangle-hook' in all tangled files
  158. (when org-babel-post-tangle-hook
  159. (mapc
  160. (lambda (file)
  161. (with-temp-filebuffer file
  162. (run-hooks 'org-babel-post-tangle-hook)))
  163. path-collector))
  164. path-collector)))
  165. (defun org-babel-tangle-clean ()
  166. "Call this function inside of a source-code file generated by
  167. `org-babel-tangle' to remove all comments inserted automatically
  168. by `org-babel-tangle'. Warning, this comment removes any lines
  169. containing constructs which resemble org-mode file links or noweb
  170. references."
  171. (interactive)
  172. (goto-char (point-min))
  173. (while (or (re-search-forward "\\[\\[file:.*\\]\\[.*\\]\\]" nil t)
  174. (re-search-forward "<<[^[:space:]]*>>" nil t))
  175. (delete-region (save-excursion (beginning-of-line 1) (point))
  176. (save-excursion (end-of-line 1) (forward-char 1) (point)))))
  177. (defvar org-stored-links)
  178. (defun org-babel-tangle-collect-blocks (&optional lang)
  179. "Collect all source blocks in the current org-mode file.
  180. Return an association list of source-code block specifications of
  181. the form used by `org-babel-spec-to-string' grouped by language.
  182. Optional argument LANG can be used to limit the collected source
  183. code blocks by language."
  184. (let ((block-counter 0) blocks)
  185. (org-babel-map-source-blocks (buffer-file-name)
  186. (setq block-counter (+ 1 block-counter))
  187. (let* ((link (progn (call-interactively 'org-store-link)
  188. (org-babel-clean-text-properties
  189. (car (pop org-stored-links)))))
  190. (info (org-babel-get-src-block-info))
  191. (source-name (intern (or (nth 4 info)
  192. (format "block-%d" block-counter))))
  193. (src-lang (nth 0 info))
  194. (expand-cmd (intern (concat "org-babel-expand-body:" src-lang)))
  195. (params (nth 2 info))
  196. by-lang)
  197. (unless (string= (cdr (assoc :tangle params)) "no") ;; skip
  198. (unless (and lang (not (string= lang src-lang))) ;; limit by language
  199. ;; add the spec for this block to blocks under it's language
  200. (setq by-lang (cdr (assoc src-lang blocks)))
  201. (setq blocks (delq (assoc src-lang blocks) blocks))
  202. (setq blocks
  203. (cons
  204. (cons src-lang
  205. (cons (list link source-name params
  206. ((lambda (body)
  207. (if (assoc :no-expand params)
  208. body
  209. (funcall
  210. (if (fboundp expand-cmd)
  211. expand-cmd
  212. 'org-babel-expand-body:generic)
  213. body
  214. params)))
  215. (if (and (cdr (assoc :noweb params))
  216. (string=
  217. "yes"
  218. (cdr (assoc :noweb params))))
  219. (org-babel-expand-noweb-references
  220. info)
  221. (nth 1 info))))
  222. by-lang)) blocks))))))
  223. ;; ensure blocks in the correct order
  224. (setq blocks
  225. (mapcar
  226. (lambda (by-lang) (cons (car by-lang) (reverse (cdr by-lang))))
  227. blocks))
  228. blocks))
  229. (defun org-babel-spec-to-string (spec)
  230. "Insert the source-code specified by SPEC into the current
  231. source code file. This function uses `comment-region' which
  232. assumes that the appropriate major-mode is set. SPEC has the
  233. form
  234. (link source-name params body)"
  235. (let ((link (nth 0 spec))
  236. (source-name (nth 1 spec))
  237. (body (nth 3 spec))
  238. (commentable (string= (cdr (assoc :comments (nth 2 spec))) "yes")))
  239. (flet ((insert-comment (text)
  240. (when commentable
  241. (insert "\n")
  242. (comment-region (point)
  243. (progn (insert text) (point)))
  244. (end-of-line nil)
  245. (insert "\n"))))
  246. (insert-comment (format "[[%s][%s]]" (org-link-escape link) source-name))
  247. (insert (format "\n%s\n" (replace-regexp-in-string
  248. "^," "" (org-babel-chomp body))))
  249. (insert-comment (format "%s ends here" source-name)))))
  250. (provide 'ob-tangle)
  251. ;; arch-tag: 413ced93-48f5-4216-86e4-3fc5df8c8f24
  252. ;;; ob-tangle.el ends here