ob-tangle.el 11 KB

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