ob-tangle.el 20 KB

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