ob-tangle.el 20 KB

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