ob-tangle.el 23 KB

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