ob-tangle.el 11 KB

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