ob-tangle.el 14 KB

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