ob-tangle.el 12 KB

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