ob-tangle.el 23 KB

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