ob-tangle.el 22 KB

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