ob-tangle.el 19 KB

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