ob-tangle.el 23 KB

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