ob-tangle.el 23 KB

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