ob-tangle.el 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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. (declare-function org-back-to-heading "org" (invisible-ok))
  28. (declare-function org-fill-template "org" (template alist))
  29. (defcustom org-babel-tangle-lang-exts
  30. '(("emacs-lisp" . "el"))
  31. "Alist mapping languages to their file extensions.
  32. The key is the language name, the value is the string that should
  33. be inserted as the extension commonly used to identify files
  34. written in this language. If no entry is found in this list,
  35. then the name of the language is used."
  36. :group 'org-babel-tangle
  37. :type '(repeat
  38. (cons
  39. (string "Language name")
  40. (string "File Extension"))))
  41. (defcustom org-babel-post-tangle-hook nil
  42. "Hook run in code files tangled by `org-babel-tangle'."
  43. :group 'org-babel
  44. :type 'hook)
  45. (defcustom org-babel-pre-tangle-hook '(save-buffer)
  46. "Hook run at the beginning of `org-babel-tangle'."
  47. :group 'org-babel
  48. :type 'hook)
  49. (defcustom org-babel-tangle-pad-newline t
  50. "Switch indicating whether to pad tangled code with newlines."
  51. :group 'org-babel
  52. :type 'boolean)
  53. (defcustom org-babel-tangle-comment-format-beg "[[%link][%sourcename]]"
  54. "Format of inserted comments in tangled code files.
  55. The following format strings can be used to insert special
  56. information into the output using `org-fill-template'.
  57. %start-line --- the line number at the start of the code block
  58. %file --------- the file from which the code block was tangled
  59. %link --------- Org-mode style link to the code block
  60. %source-name -- name of the code block"
  61. :group 'org-babel
  62. :type 'string)
  63. (defcustom org-babel-tangle-comment-format-end "%sourcename ends here"
  64. "Format of inserted comments in tangled code files.
  65. The following format strings can be used to insert special
  66. information into the output using `org-fill-template'.
  67. %start-line --- the line number at the start of the code block
  68. %file --------- the file from which the code block was tangled
  69. %link --------- Org-mode style link to the code block
  70. %source-name -- name of the code block"
  71. :group 'org-babel
  72. :type 'string)
  73. (defun org-babel-find-file-noselect-refresh (file)
  74. "Find file ensuring that the latest changes on disk are
  75. represented in the file."
  76. (find-file-noselect file)
  77. (with-current-buffer (get-file-buffer file)
  78. (revert-buffer t t t)))
  79. (defmacro org-babel-with-temp-filebuffer (file &rest body)
  80. "Open FILE into a temporary buffer execute BODY there like
  81. `progn', then kill the FILE buffer returning the result of
  82. evaluating BODY."
  83. (declare (indent 1))
  84. (let ((temp-result (make-symbol "temp-result"))
  85. (temp-file (make-symbol "temp-file"))
  86. (visited-p (make-symbol "visited-p")))
  87. `(let (,temp-result ,temp-file
  88. (,visited-p (get-file-buffer ,file)))
  89. (org-babel-find-file-noselect-refresh ,file)
  90. (setf ,temp-file (get-file-buffer ,file))
  91. (with-current-buffer ,temp-file
  92. (setf ,temp-result (progn ,@body)))
  93. (unless ,visited-p (kill-buffer ,temp-file))
  94. ,temp-result)))
  95. ;;;###autoload
  96. (defun org-babel-load-file (file)
  97. "Load Emacs Lisp source code blocks in the Org-mode FILE.
  98. This function exports the source code using
  99. `org-babel-tangle' and then loads the resulting file using
  100. `load-file'."
  101. (flet ((age (file)
  102. (float-time
  103. (time-subtract (current-time)
  104. (nth 5 (or (file-attributes (file-truename file))
  105. (file-attributes file)))))))
  106. (let* ((base-name (file-name-sans-extension file))
  107. (exported-file (concat base-name ".el")))
  108. ;; tangle if the org-mode file is newer than the elisp file
  109. (unless (and (file-exists-p exported-file)
  110. (> (age file) (age exported-file)))
  111. (org-babel-tangle-file file exported-file "emacs-lisp"))
  112. (load-file exported-file)
  113. (message "loaded %s" exported-file))))
  114. ;;;###autoload
  115. (defun org-babel-tangle-file (file &optional target-file lang)
  116. "Extract the bodies of source code blocks in FILE.
  117. Source code blocks are extracted with `org-babel-tangle'.
  118. Optional argument TARGET-FILE can be used to specify a default
  119. export file for all source blocks. Optional argument LANG can be
  120. used to limit the exported source code blocks by language."
  121. (interactive "fFile to tangle: \nP")
  122. (let ((visited-p (get-file-buffer (expand-file-name file)))
  123. to-be-removed)
  124. (save-window-excursion
  125. (find-file file)
  126. (setq to-be-removed (current-buffer))
  127. (org-babel-tangle target-file lang))
  128. (unless visited-p
  129. (kill-buffer to-be-removed))))
  130. (defun org-babel-tangle-publish (_ filename pub-dir)
  131. "Tangle FILENAME and place the results in PUB-DIR."
  132. (mapc (lambda (el) (copy-file el pub-dir t)) (org-babel-tangle-file filename)))
  133. ;;;###autoload
  134. (defun org-babel-tangle (&optional target-file lang)
  135. "Write code blocks to source-specific files.
  136. Extract the bodies of all source code blocks from the current
  137. file into their own source-specific files. Optional argument
  138. TARGET-FILE can be used to specify a default export file for all
  139. source blocks. Optional argument LANG can be used to limit the
  140. exported source code blocks by language."
  141. (interactive)
  142. (run-hooks 'org-babel-pre-tangle-hook)
  143. (save-excursion
  144. (let ((block-counter 0)
  145. (org-babel-default-header-args
  146. (if target-file
  147. (org-babel-merge-params org-babel-default-header-args
  148. (list (cons :tangle target-file)))
  149. org-babel-default-header-args))
  150. path-collector)
  151. (mapc ;; map over all languages
  152. (lambda (by-lang)
  153. (let* ((lang (car by-lang))
  154. (specs (cdr by-lang))
  155. (ext (or (cdr (assoc lang org-babel-tangle-lang-exts)) lang))
  156. (lang-f (intern
  157. (concat
  158. (or (and (cdr (assoc lang org-src-lang-modes))
  159. (symbol-name
  160. (cdr (assoc lang org-src-lang-modes))))
  161. lang)
  162. "-mode")))
  163. she-banged)
  164. (mapc
  165. (lambda (spec)
  166. (flet ((get-spec (name)
  167. (cdr (assoc name (nth 4 spec)))))
  168. (let* ((tangle (get-spec :tangle))
  169. (she-bang ((lambda (sheb) (when (> (length sheb) 0) sheb))
  170. (get-spec :shebang)))
  171. (base-name (cond
  172. ((string= "yes" tangle)
  173. (file-name-sans-extension
  174. (buffer-file-name)))
  175. ((string= "no" tangle) nil)
  176. ((> (length tangle) 0) tangle)))
  177. (file-name (when base-name
  178. ;; decide if we want to add ext to base-name
  179. (if (and ext (string= "yes" tangle))
  180. (concat base-name "." ext) base-name))))
  181. (when file-name
  182. ;; delete any old versions of file
  183. (when (and (file-exists-p file-name)
  184. (not (member file-name path-collector)))
  185. (delete-file file-name))
  186. ;; drop source-block to file
  187. (with-temp-buffer
  188. (when (fboundp lang-f) (funcall lang-f))
  189. (when (and she-bang (not (member file-name she-banged)))
  190. (insert (concat she-bang "\n"))
  191. (setq she-banged (cons file-name she-banged)))
  192. (org-babel-spec-to-string spec)
  193. ;; We avoid append-to-file as it does not work with tramp.
  194. (let ((content (buffer-string)))
  195. (with-temp-buffer
  196. (if (file-exists-p file-name)
  197. (insert-file-contents file-name))
  198. (goto-char (point-max))
  199. (insert content)
  200. (write-region nil nil file-name))))
  201. ;; if files contain she-bangs, then make the executable
  202. (when she-bang (set-file-modes file-name #o755))
  203. ;; update counter
  204. (setq block-counter (+ 1 block-counter))
  205. (add-to-list 'path-collector file-name)))))
  206. specs)))
  207. (org-babel-tangle-collect-blocks lang))
  208. (message "tangled %d code block%s" block-counter
  209. (if (= block-counter 1) "" "s"))
  210. ;; run `org-babel-post-tangle-hook' in all tangled files
  211. (when org-babel-post-tangle-hook
  212. (mapc
  213. (lambda (file)
  214. (org-babel-with-temp-filebuffer file
  215. (run-hooks 'org-babel-post-tangle-hook)))
  216. path-collector))
  217. path-collector)))
  218. (defun org-babel-tangle-clean ()
  219. "Remove comments inserted by `org-babel-tangle'.
  220. Call this function inside of a source-code file generated by
  221. `org-babel-tangle' to remove all comments inserted automatically
  222. by `org-babel-tangle'. Warning, this comment removes any lines
  223. containing constructs which resemble org-mode file links or noweb
  224. references."
  225. (interactive)
  226. (goto-char (point-min))
  227. (while (or (re-search-forward "\\[\\[file:.*\\]\\[.*\\]\\]" nil t)
  228. (re-search-forward "<<[^[:space:]]*>>" nil t))
  229. (delete-region (save-excursion (beginning-of-line 1) (point))
  230. (save-excursion (end-of-line 1) (forward-char 1) (point)))))
  231. (defvar org-stored-links)
  232. (defun org-babel-tangle-collect-blocks (&optional language)
  233. "Collect source blocks in the current Org-mode file.
  234. Return an association list of source-code block specifications of
  235. the form used by `org-babel-spec-to-string' grouped by language.
  236. Optional argument LANG can be used to limit the collected source
  237. code blocks by language."
  238. (let ((block-counter 1) (current-heading "") blocks)
  239. (org-babel-map-src-blocks (buffer-file-name)
  240. ((lambda (new-heading)
  241. (if (not (string= new-heading current-heading))
  242. (progn
  243. (setq block-counter 1)
  244. (setq current-heading new-heading))
  245. (setq block-counter (+ 1 block-counter))))
  246. (replace-regexp-in-string "[ \t]" "-"
  247. (condition-case nil
  248. (nth 4 (org-heading-components))
  249. (error (buffer-file-name)))))
  250. (let* ((start-line (save-restriction (widen)
  251. (+ 1 (line-number-at-pos (point)))))
  252. (file (buffer-file-name))
  253. (link (progn (call-interactively 'org-store-link)
  254. (org-babel-clean-text-properties
  255. (car (pop org-stored-links)))))
  256. (info (org-babel-get-src-block-info))
  257. (params (nth 2 info))
  258. (source-name (intern (or (nth 4 info)
  259. (format "%s:%d"
  260. current-heading block-counter))))
  261. (src-lang (nth 0 info))
  262. (expand-cmd (intern (concat "org-babel-expand-body:" src-lang)))
  263. (body ((lambda (body)
  264. (if (assoc :no-expand params)
  265. body
  266. (funcall (if (fboundp expand-cmd)
  267. expand-cmd
  268. 'org-babel-expand-body:generic)
  269. body params)))
  270. (if (and (cdr (assoc :noweb params))
  271. (string= "yes" (cdr (assoc :noweb params))))
  272. (org-babel-expand-noweb-references info)
  273. (nth 1 info))))
  274. (comment (when (or (string= "both" (cdr (assoc :comments params)))
  275. (string= "org" (cdr (assoc :comments params))))
  276. ;; from the previous heading or code-block end
  277. (buffer-substring
  278. (max (condition-case nil
  279. (save-excursion
  280. (org-back-to-heading t) (point))
  281. (error 0))
  282. (save-excursion (re-search-backward
  283. org-babel-src-block-regexp nil t)
  284. (match-end 0)))
  285. (point))))
  286. by-lang)
  287. (unless (string= (cdr (assoc :tangle params)) "no")
  288. (unless (and language (not (string= language src-lang)))
  289. ;; add the spec for this block to blocks under it's language
  290. (setq by-lang (cdr (assoc src-lang blocks)))
  291. (setq blocks (delq (assoc src-lang blocks) blocks))
  292. (setq blocks (cons
  293. (cons src-lang
  294. (cons (list start-line file link
  295. source-name params body comment)
  296. by-lang)) blocks))))))
  297. ;; ensure blocks in the correct order
  298. (setq blocks
  299. (mapcar
  300. (lambda (by-lang) (cons (car by-lang) (reverse (cdr by-lang))))
  301. blocks))
  302. blocks))
  303. (defun org-babel-spec-to-string (spec)
  304. "Insert SPEC into the current file.
  305. Insert the source-code specified by SPEC into the current
  306. source code file. This function uses `comment-region' which
  307. assumes that the appropriate major-mode is set. SPEC has the
  308. form
  309. (start-line file link source-name params body comment)"
  310. (let* ((start-line (nth 0 spec))
  311. (file (nth 1 spec))
  312. (link (org-link-escape (nth 2 spec)))
  313. (source-name (nth 3 spec))
  314. (body (nth 5 spec))
  315. (comment (nth 6 spec))
  316. (comments (cdr (assoc :comments (nth 4 spec))))
  317. (link-p (or (string= comments "both") (string= comments "link")
  318. (string= comments "yes")))
  319. (link-data (mapcar (lambda (el)
  320. (cons (symbol-name el)
  321. ((lambda (le)
  322. (if (stringp le) le (format "%S" le)))
  323. (eval el))))
  324. '(start-line file link source-name))))
  325. (flet ((insert-comment (text)
  326. (let ((text (org-babel-trim text)))
  327. (when (and comments (not (string= comments "no"))
  328. (> (length text) 0))
  329. (when org-babel-tangle-pad-newline (insert "\n"))
  330. (comment-region (point) (progn (insert text) (point)))
  331. (end-of-line nil) (insert "\n")))))
  332. (when comment (insert-comment comment))
  333. (when link-p
  334. (insert-comment
  335. (org-fill-template org-babel-tangle-comment-format-beg link-data)))
  336. (when org-babel-tangle-pad-newline (insert "\n"))
  337. (insert (format "%s\n" (replace-regexp-in-string
  338. "^," "" (org-babel-trim body))))
  339. (when link-p
  340. (insert-comment
  341. (org-fill-template org-babel-tangle-comment-format-end link-data))))))
  342. (provide 'ob-tangle)
  343. ;; arch-tag: 413ced93-48f5-4216-86e4-3fc5df8c8f24
  344. ;;; ob-tangle.el ends here