ob-tangle.el 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. ;;; ob-tangle.el --- Extract Source Code From Org Files -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2009-2021 Free Software Foundation, Inc.
  3. ;; Author: Eric Schulte
  4. ;; Keywords: literate programming, reproducible research
  5. ;; Homepage: https://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 <https://www.gnu.org/licenses/>.
  17. ;;; Commentary:
  18. ;; Extract the code from source blocks out into raw source-code files.
  19. ;;; Code:
  20. (require 'cl-lib)
  21. (require 'org-src)
  22. (require 'org-macs)
  23. (require 'ol)
  24. (declare-function make-directory "files" (dir &optional parents))
  25. (declare-function org-at-heading-p "org" (&optional ignored))
  26. (declare-function org-babel-update-block-body "ob-core" (new-body))
  27. (declare-function org-back-to-heading "org" (&optional invisible-ok))
  28. (declare-function org-before-first-heading-p "org" ())
  29. (declare-function org-element-at-point "org-element" ())
  30. (declare-function org-element-type "org-element" (element))
  31. (declare-function org-heading-components "org" ())
  32. (declare-function org-in-commented-heading-p "org" (&optional no-inheritance))
  33. (declare-function org-in-archived-heading-p "org" (&optional no-inheritance))
  34. (declare-function outline-previous-heading "outline" ())
  35. (defvar org-id-link-to-org-use-id nil) ; Dynamically scoped
  36. (defcustom org-babel-tangle-lang-exts
  37. '(("emacs-lisp" . "el")
  38. ("elisp" . "el"))
  39. "Alist mapping languages to their file extensions.
  40. The key is the language name, the value is the string that should
  41. be inserted as the extension commonly used to identify files
  42. written in this language. If no entry is found in this list,
  43. then the name of the language is used."
  44. :group 'org-babel-tangle
  45. :version "24.1"
  46. :type '(repeat
  47. (cons
  48. (string "Language name")
  49. (string "File Extension"))))
  50. (defcustom org-babel-tangle-use-relative-file-links t
  51. "Use relative path names in links from tangled source back the Org file."
  52. :group 'org-babel-tangle
  53. :type 'boolean)
  54. (defcustom org-babel-post-tangle-hook nil
  55. "Hook run in code files tangled by `org-babel-tangle'."
  56. :group 'org-babel
  57. :version "24.1"
  58. :type 'hook)
  59. (defcustom org-babel-pre-tangle-hook '(save-buffer)
  60. "Hook run at the beginning of `org-babel-tangle'."
  61. :group 'org-babel
  62. :version "24.1"
  63. :type 'hook)
  64. (defcustom org-babel-tangle-body-hook nil
  65. "Hook run over the contents of each code block body."
  66. :group 'org-babel
  67. :version "24.1"
  68. :type 'hook)
  69. (defcustom org-babel-tangle-comment-format-beg "[[%link][%source-name]]"
  70. "Format of inserted comments in tangled code files.
  71. The following format strings can be used to insert special
  72. information into the output using `org-fill-template'.
  73. %start-line --- the line number at the start of the code block
  74. %file --------- the file from which the code block was tangled
  75. %link --------- Org style link to the code block
  76. %source-name -- name of the code block
  77. Upon insertion the formatted comment will be commented out, and
  78. followed by a newline. To inhibit this post-insertion processing
  79. set the `org-babel-tangle-uncomment-comments' variable to a
  80. non-nil value.
  81. Whether or not comments are inserted during tangling is
  82. controlled by the :comments header argument."
  83. :group 'org-babel
  84. :version "24.1"
  85. :type 'string)
  86. (defcustom org-babel-tangle-comment-format-end "%source-name ends here"
  87. "Format of inserted comments in tangled code files.
  88. The following format strings can be used to insert special
  89. information into the output using `org-fill-template'.
  90. %start-line --- the line number at the start of the code block
  91. %file --------- the file from which the code block was tangled
  92. %link --------- Org style link to the code block
  93. %source-name -- name of the code block
  94. Upon insertion the formatted comment will be commented out, and
  95. followed by a newline. To inhibit this post-insertion processing
  96. set the `org-babel-tangle-uncomment-comments' variable to a
  97. non-nil value.
  98. Whether or not comments are inserted during tangling is
  99. controlled by the :comments header argument."
  100. :group 'org-babel
  101. :version "24.1"
  102. :type 'string)
  103. (defcustom org-babel-tangle-uncomment-comments nil
  104. "Inhibits automatic commenting and addition of trailing newline
  105. of tangle comments. Use `org-babel-tangle-comment-format-beg'
  106. and `org-babel-tangle-comment-format-end' to customize the format
  107. of tangled comments."
  108. :group 'org-babel
  109. :type 'boolean)
  110. (defcustom org-babel-process-comment-text 'org-remove-indentation
  111. "Function called to process raw Org text collected to be
  112. inserted as comments in tangled source-code files. The function
  113. should take a single string argument and return a string
  114. result. The default value is `org-remove-indentation'."
  115. :group 'org-babel
  116. :version "24.1"
  117. :type 'function)
  118. (defun org-babel-find-file-noselect-refresh (file)
  119. "Find file ensuring that the latest changes on disk are
  120. represented in the file."
  121. (find-file-noselect file 'nowarn)
  122. (with-current-buffer (get-file-buffer file)
  123. (revert-buffer t t t)))
  124. (defmacro org-babel-with-temp-filebuffer (file &rest body)
  125. "Open FILE into a temporary buffer execute BODY there like
  126. `progn', then kill the FILE buffer returning the result of
  127. evaluating BODY."
  128. (declare (indent 1) (debug t))
  129. (let ((temp-path (make-symbol "temp-path"))
  130. (temp-result (make-symbol "temp-result"))
  131. (temp-file (make-symbol "temp-file"))
  132. (visited-p (make-symbol "visited-p")))
  133. `(let* ((,temp-path ,file)
  134. (,visited-p (get-file-buffer ,temp-path))
  135. ,temp-result ,temp-file)
  136. (org-babel-find-file-noselect-refresh ,temp-path)
  137. (setf ,temp-file (get-file-buffer ,temp-path))
  138. (with-current-buffer ,temp-file
  139. (setf ,temp-result (progn ,@body)))
  140. (unless ,visited-p (kill-buffer ,temp-file))
  141. ,temp-result)))
  142. ;;;###autoload
  143. (defun org-babel-tangle-file (file &optional target-file lang-re)
  144. "Extract the bodies of source code blocks in FILE.
  145. Source code blocks are extracted with `org-babel-tangle'.
  146. Optional argument TARGET-FILE can be used to specify a default
  147. export file for all source blocks.
  148. Optional argument LANG-RE can be used to limit the exported
  149. source code blocks by languages matching a regular expression.
  150. Return a list whose CAR is the tangled file name."
  151. (interactive "fFile to tangle: \nP")
  152. (let ((visited-p (find-buffer-visiting (expand-file-name file)))
  153. to-be-removed)
  154. (prog1
  155. (save-window-excursion
  156. (find-file file)
  157. (setq to-be-removed (current-buffer))
  158. (mapcar #'expand-file-name (org-babel-tangle nil target-file lang-re)))
  159. (unless visited-p
  160. (kill-buffer to-be-removed)))))
  161. (defun org-babel-tangle-publish (_ filename pub-dir)
  162. "Tangle FILENAME and place the results in PUB-DIR."
  163. (unless (file-exists-p pub-dir)
  164. (make-directory pub-dir t))
  165. (setq pub-dir (file-name-as-directory pub-dir))
  166. (mapc (lambda (el) (copy-file el pub-dir t)) (org-babel-tangle-file filename)))
  167. ;;;###autoload
  168. (defun org-babel-tangle (&optional arg target-file lang-re)
  169. "Write code blocks to source-specific files.
  170. Extract the bodies of all source code blocks from the current
  171. file into their own source-specific files.
  172. With one universal prefix argument, only tangle the block at point.
  173. When two universal prefix arguments, only tangle blocks for the
  174. tangle file of the block at point.
  175. Optional argument TARGET-FILE can be used to specify a default
  176. export file for all source blocks. Optional argument LANG-RE can
  177. be used to limit the exported source code blocks by languages
  178. matching a regular expression."
  179. (interactive "P")
  180. (run-hooks 'org-babel-pre-tangle-hook)
  181. ;; Possibly Restrict the buffer to the current code block
  182. (save-restriction
  183. (save-excursion
  184. (when (equal arg '(4))
  185. (let ((head (org-babel-where-is-src-block-head)))
  186. (if head
  187. (goto-char head)
  188. (user-error "Point is not in a source code block"))))
  189. (let ((block-counter 0)
  190. (org-babel-default-header-args
  191. (if target-file
  192. (org-babel-merge-params org-babel-default-header-args
  193. (list (cons :tangle target-file)))
  194. org-babel-default-header-args))
  195. (tangle-file
  196. (when (equal arg '(16))
  197. (or (cdr (assq :tangle (nth 2 (org-babel-get-src-block-info 'light))))
  198. (user-error "Point is not in a source code block"))))
  199. path-collector)
  200. (mapc ;; map over file-names
  201. (lambda (by-fn)
  202. (let ((file-name (car by-fn)))
  203. (when file-name
  204. (let ((lspecs (cdr by-fn))
  205. (fnd (file-name-directory file-name))
  206. modes make-dir she-banged lang)
  207. ;; drop source-blocks to file
  208. ;; We avoid append-to-file as it does not work with tramp.
  209. (with-temp-buffer
  210. (mapc
  211. (lambda (lspec)
  212. (let* ((block-lang (car lspec))
  213. (spec (cdr lspec))
  214. (get-spec (lambda (name) (cdr (assq name (nth 4 spec)))))
  215. (she-bang (let ((sheb (funcall get-spec :shebang)))
  216. (when (> (length sheb) 0) sheb)))
  217. (tangle-mode (funcall get-spec :tangle-mode)))
  218. (unless (string-equal block-lang lang)
  219. (setq lang block-lang)
  220. (let ((lang-f (org-src-get-lang-mode lang)))
  221. (when (fboundp lang-f) (ignore-errors (funcall lang-f)))))
  222. ;; if file contains she-bangs, then make it executable
  223. (when she-bang
  224. (unless tangle-mode (setq tangle-mode #o755)))
  225. (when tangle-mode
  226. (add-to-list 'modes tangle-mode))
  227. ;; Possibly create the parent directories for file.
  228. (let ((m (funcall get-spec :mkdirp)))
  229. (and m fnd (not (string= m "no"))
  230. (setq make-dir t)))
  231. ;; Handle :padlines unless first line in file
  232. (unless (or (string= "no" (funcall get-spec :padline))
  233. (= (point) (point-min)))
  234. (insert "\n"))
  235. (when (and she-bang (not she-banged))
  236. (insert (concat she-bang "\n"))
  237. (setq she-banged t))
  238. (org-babel-spec-to-string spec)
  239. (setq block-counter (+ 1 block-counter))))
  240. lspecs)
  241. (when make-dir
  242. (make-directory fnd 'parents))
  243. ;; erase previous file
  244. (when (file-exists-p file-name)
  245. (delete-file file-name))
  246. (write-region nil nil file-name)
  247. (mapc (lambda (mode) (set-file-modes file-name mode)) modes)
  248. (push file-name path-collector))))))
  249. (if (equal arg '(4))
  250. (org-babel-tangle-single-block 1 t)
  251. (org-babel-tangle-collect-blocks lang-re tangle-file)))
  252. (message "Tangled %d code block%s from %s" block-counter
  253. (if (= block-counter 1) "" "s")
  254. (file-name-nondirectory
  255. (buffer-file-name
  256. (or (buffer-base-buffer)
  257. (current-buffer)
  258. (and (org-src-edit-buffer-p)
  259. (org-src-source-buffer))))))
  260. ;; run `org-babel-post-tangle-hook' in all tangled files
  261. (when org-babel-post-tangle-hook
  262. (mapc
  263. (lambda (file)
  264. (org-babel-with-temp-filebuffer file
  265. (run-hooks 'org-babel-post-tangle-hook)))
  266. path-collector))
  267. path-collector))))
  268. (defun org-babel-tangle-clean ()
  269. "Remove comments inserted by `org-babel-tangle'.
  270. Call this function inside of a source-code file generated by
  271. `org-babel-tangle' to remove all comments inserted automatically
  272. by `org-babel-tangle'. Warning, this comment removes any lines
  273. containing constructs which resemble Org file links or noweb
  274. references."
  275. (interactive)
  276. (goto-char (point-min))
  277. (while (or (re-search-forward "\\[\\[file:.*\\]\\[.*\\]\\]" nil t)
  278. (re-search-forward (org-babel-noweb-wrap) nil t))
  279. (delete-region (save-excursion (beginning-of-line 1) (point))
  280. (save-excursion (end-of-line 1) (forward-char 1) (point)))))
  281. (defun org-babel-spec-to-string (spec)
  282. "Insert SPEC into the current file.
  283. Insert the source-code specified by SPEC into the current source
  284. code file. This function uses `comment-region' which assumes
  285. that the appropriate major-mode is set. SPEC has the form:
  286. (start-line file link source-name params body comment)"
  287. (pcase-let*
  288. ((`(,start ,file ,link ,source ,info ,body ,comment) spec)
  289. (comments (cdr (assq :comments info)))
  290. (link? (or (string= comments "both") (string= comments "link")
  291. (string= comments "yes") (string= comments "noweb")))
  292. (link-data `(("start-line" . ,(number-to-string start))
  293. ("file" . ,file)
  294. ("link" . ,link)
  295. ("source-name" . ,source)))
  296. (insert-comment (lambda (text)
  297. (when (and comments
  298. (not (string= comments "no"))
  299. (org-string-nw-p text))
  300. (if org-babel-tangle-uncomment-comments
  301. ;; Plain comments: no processing.
  302. (insert text)
  303. ;; Ensure comments are made to be
  304. ;; comments, and add a trailing newline.
  305. ;; Also ignore invisible characters when
  306. ;; commenting.
  307. (comment-region
  308. (point)
  309. (progn (insert (org-no-properties text))
  310. (point)))
  311. (end-of-line)
  312. (insert "\n"))))))
  313. (when comment (funcall insert-comment comment))
  314. (when link?
  315. (funcall insert-comment
  316. (org-fill-template
  317. org-babel-tangle-comment-format-beg link-data)))
  318. (insert body "\n")
  319. (when link?
  320. (funcall insert-comment
  321. (org-fill-template
  322. org-babel-tangle-comment-format-end link-data)))))
  323. (defun org-babel-effective-tangled-filename (buffer-fn src-lang src-tfile)
  324. "Return effective tangled filename of a source-code block.
  325. BUFFER-FN is the name of the buffer, SRC-LANG the language of the
  326. block and SRC-TFILE is the value of the :tangle header argument,
  327. as computed by `org-babel-tangle-single-block'."
  328. (let ((base-name (cond
  329. ((string= "yes" src-tfile)
  330. ;; Use the buffer name
  331. (file-name-sans-extension buffer-fn))
  332. ((string= "no" src-tfile) nil)
  333. ((> (length src-tfile) 0) src-tfile)))
  334. (ext (or (cdr (assoc src-lang org-babel-tangle-lang-exts)) src-lang)))
  335. (when base-name
  336. ;; decide if we want to add ext to base-name
  337. (if (and ext (string= "yes" src-tfile))
  338. (concat base-name "." ext) base-name))))
  339. (defun org-babel-tangle-collect-blocks (&optional lang-re tangle-file)
  340. "Collect source blocks in the current Org file.
  341. Return an association list of language and source-code block
  342. specifications of the form used by `org-babel-spec-to-string'
  343. grouped by tangled file name.
  344. Optional argument LANG-RE can be used to limit the collected
  345. source code blocks by languages matching a regular expression.
  346. Optional argument TANGLE-FILE can be used to limit the collected
  347. code blocks by target file."
  348. (let ((counter 0) last-heading-pos blocks)
  349. (org-babel-map-src-blocks (buffer-file-name)
  350. (let ((current-heading-pos
  351. (org-with-wide-buffer
  352. (org-with-limited-levels (outline-previous-heading)))))
  353. (if (eq last-heading-pos current-heading-pos) (cl-incf counter)
  354. (setq counter 1)
  355. (setq last-heading-pos current-heading-pos)))
  356. (unless (or (org-in-commented-heading-p)
  357. (org-in-archived-heading-p))
  358. (let* ((info (org-babel-get-src-block-info 'light))
  359. (src-lang (nth 0 info))
  360. (src-tfile (cdr (assq :tangle (nth 2 info)))))
  361. (unless (or (string= src-tfile "no")
  362. (and tangle-file (not (equal tangle-file src-tfile)))
  363. (and lang-re (not (string-match-p lang-re src-lang))))
  364. ;; Add the spec for this block to blocks under its tangled
  365. ;; file name.
  366. (let* ((block (org-babel-tangle-single-block counter))
  367. (src-tfile (cdr (assq :tangle (nth 4 block))))
  368. (file-name (org-babel-effective-tangled-filename
  369. (nth 1 block) src-lang src-tfile))
  370. (by-fn (assoc file-name blocks)))
  371. (if by-fn (setcdr by-fn (cons (cons src-lang block) (cdr by-fn)))
  372. (push (cons file-name (list (cons src-lang block))) blocks)))))))
  373. ;; Ensure blocks are in the correct order.
  374. (mapcar (lambda (b) (cons (car b) (nreverse (cdr b))))
  375. (nreverse blocks))))
  376. (defun org-babel-tangle-single-block (block-counter &optional only-this-block)
  377. "Collect the tangled source for current block.
  378. Return the list of block attributes needed by
  379. `org-babel-tangle-collect-blocks'. When ONLY-THIS-BLOCK is
  380. non-nil, return the full association list to be used by
  381. `org-babel-tangle' directly."
  382. (let* ((info (org-babel-get-src-block-info))
  383. (start-line
  384. (save-restriction (widen)
  385. (+ 1 (line-number-at-pos (point)))))
  386. (file (buffer-file-name (buffer-base-buffer)))
  387. (src-lang (nth 0 info))
  388. (params (nth 2 info))
  389. (extra (nth 3 info))
  390. (coderef (nth 6 info))
  391. (cref-regexp (org-src-coderef-regexp coderef))
  392. (link (let* (
  393. ;; The created link is transient. Using ID is
  394. ;; not necessary, but could have side-effects if
  395. ;; used. An ID property may be added to
  396. ;; existing entries thus creatin unexpected file
  397. ;; modifications.
  398. (org-id-link-to-org-use-id nil)
  399. (l (org-no-properties (org-store-link nil))))
  400. (and (string-match org-link-bracket-re l)
  401. (match-string 1 l))))
  402. (source-name
  403. (or (nth 4 info)
  404. (format "%s:%d"
  405. (or (ignore-errors (nth 4 (org-heading-components)))
  406. "No heading")
  407. block-counter)))
  408. (expand-cmd (intern (concat "org-babel-expand-body:" src-lang)))
  409. (assignments-cmd
  410. (intern (concat "org-babel-variable-assignments:" src-lang)))
  411. (body
  412. ;; Run the tangle-body-hook.
  413. (let ((body (if (org-babel-noweb-p params :tangle)
  414. (org-babel-expand-noweb-references info)
  415. (nth 1 info))))
  416. (with-temp-buffer
  417. (insert
  418. ;; Expand body in language specific manner.
  419. (cond ((assq :no-expand params) body)
  420. ((fboundp expand-cmd) (funcall expand-cmd body params))
  421. (t
  422. (org-babel-expand-body:generic
  423. body params (and (fboundp assignments-cmd)
  424. (funcall assignments-cmd params))))))
  425. (when (string-match "-r" extra)
  426. (goto-char (point-min))
  427. (while (re-search-forward cref-regexp nil t)
  428. (replace-match "")))
  429. (run-hooks 'org-babel-tangle-body-hook)
  430. (buffer-string))))
  431. (comment
  432. (when (or (string= "both" (cdr (assq :comments params)))
  433. (string= "org" (cdr (assq :comments params))))
  434. ;; From the previous heading or code-block end
  435. (funcall
  436. org-babel-process-comment-text
  437. (buffer-substring
  438. (max (condition-case nil
  439. (save-excursion
  440. (org-back-to-heading t) ; Sets match data
  441. (match-end 0))
  442. (error (point-min)))
  443. (save-excursion
  444. (if (re-search-backward
  445. org-babel-src-block-regexp nil t)
  446. (match-end 0)
  447. (point-min))))
  448. (point)))))
  449. (result
  450. (list start-line
  451. (if org-babel-tangle-use-relative-file-links
  452. (file-relative-name file)
  453. file)
  454. (if (and org-babel-tangle-use-relative-file-links
  455. (string-match org-link-types-re link)
  456. (string= (match-string 1 link) "file"))
  457. (concat "file:"
  458. (file-relative-name (substring link (match-end 0))
  459. (file-name-directory
  460. (cdr (assq :tangle params)))))
  461. link)
  462. source-name
  463. params
  464. (if org-src-preserve-indentation
  465. (org-trim body t)
  466. (org-trim (org-remove-indentation body)))
  467. comment)))
  468. (if only-this-block
  469. (let* ((src-tfile (cdr (assq :tangle (nth 4 result))))
  470. (file-name (org-babel-effective-tangled-filename
  471. (nth 1 result) src-lang src-tfile)))
  472. (list (cons file-name (list (cons src-lang result)))))
  473. result)))
  474. (defun org-babel-tangle-comment-links (&optional info)
  475. "Return a list of begin and end link comments for the code block at point.
  476. INFO, when non nil, is the source block information, as returned
  477. by `org-babel-get-src-block-info'."
  478. (let ((link-data (pcase (or info (org-babel-get-src-block-info 'light))
  479. (`(,_ ,_ ,_ ,_ ,name ,start ,_)
  480. `(("start-line" . ,(org-with-point-at start
  481. (number-to-string
  482. (line-number-at-pos))))
  483. ("file" . ,(buffer-file-name))
  484. ("link" . ,(let (;; The created link is transient. Using ID is
  485. ;; not necessary, but could have side-effects if
  486. ;; used. An ID property may be added to
  487. ;; existing entries thus creatin unexpected file
  488. ;; modifications.
  489. (org-id-link-to-org-use-id nil))
  490. (org-no-properties (org-store-link nil))))
  491. ("source-name" . ,name))))))
  492. (list (org-fill-template org-babel-tangle-comment-format-beg link-data)
  493. (org-fill-template org-babel-tangle-comment-format-end link-data))))
  494. ;; de-tangling functions
  495. (defun org-babel-detangle (&optional source-code-file)
  496. "Propagate changes in source file back original to Org file.
  497. This requires that code blocks were tangled with link comments
  498. which enable the original code blocks to be found."
  499. (interactive)
  500. (save-excursion
  501. (when source-code-file (find-file source-code-file))
  502. (goto-char (point-min))
  503. (let ((counter 0) new-body end)
  504. (while (re-search-forward org-link-bracket-re nil t)
  505. (if (and (match-string 2)
  506. (re-search-forward
  507. (concat " " (regexp-quote (match-string 2)) " ends here") nil t))
  508. (progn (setq end (match-end 0))
  509. (forward-line -1)
  510. (save-excursion
  511. (when (setq new-body (org-babel-tangle-jump-to-org))
  512. (org-babel-update-block-body new-body)))
  513. (setq counter (+ 1 counter)))
  514. (setq end (point)))
  515. (goto-char end))
  516. (prog1 counter (message "Detangled %d code blocks" counter)))))
  517. (defun org-babel-tangle-jump-to-org ()
  518. "Jump from a tangled code file to the related Org mode file."
  519. (interactive)
  520. (let ((mid (point))
  521. start body-start end target-buffer target-char link block-name body)
  522. (save-window-excursion
  523. (save-excursion
  524. (while (and (re-search-backward org-link-bracket-re nil t)
  525. (not ; ever wider searches until matching block comments
  526. (and (setq start (line-beginning-position))
  527. (setq body-start (line-beginning-position 2))
  528. (setq link (match-string 0))
  529. (setq block-name (match-string 2))
  530. (save-excursion
  531. (save-match-data
  532. (re-search-forward
  533. (concat " " (regexp-quote block-name)
  534. " ends here")
  535. nil t)
  536. (setq end (line-beginning-position))))))))
  537. (unless (and start (< start mid) (< mid end))
  538. (error "Not in tangled code"))
  539. (setq body (buffer-substring body-start end)))
  540. ;; Go to the beginning of the relative block in Org file.
  541. (org-link-open-from-string link)
  542. (setq target-buffer (current-buffer))
  543. (if (string-match "[^ \t\n\r]:\\([[:digit:]]+\\)" block-name)
  544. (let ((n (string-to-number (match-string 1 block-name))))
  545. (if (org-before-first-heading-p) (goto-char (point-min))
  546. (org-back-to-heading t))
  547. ;; Do not skip the first block if it begins at point min.
  548. (cond ((or (org-at-heading-p)
  549. (not (eq (org-element-type (org-element-at-point))
  550. 'src-block)))
  551. (org-babel-next-src-block n))
  552. ((= n 1))
  553. (t (org-babel-next-src-block (1- n)))))
  554. (org-babel-goto-named-src-block block-name))
  555. (goto-char (org-babel-where-is-src-block-head))
  556. (forward-line 1)
  557. ;; Try to preserve location of point within the source code in
  558. ;; tangled code file.
  559. (let ((offset (- mid body-start)))
  560. (when (> end (+ offset (point)))
  561. (forward-char offset)))
  562. (setq target-char (point)))
  563. (org-src-switch-to-buffer target-buffer t)
  564. (goto-char target-char)
  565. body))
  566. (provide 'ob-tangle)
  567. ;; Local variables:
  568. ;; generated-autoload-file: "org-loaddefs.el"
  569. ;; End:
  570. ;;; ob-tangle.el ends here