ob-tangle.el 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  1. ;;; ob-tangle.el --- Extract Source Code From Org Files -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2009-2022 Free Software Foundation, Inc.
  3. ;; Author: Eric Schulte
  4. ;; Keywords: literate programming, reproducible research
  5. ;; URL: 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--cache-active-p "org-element" ())
  30. (declare-function org-element-lineage "org-element" (datum &optional types with-self))
  31. (declare-function org-element-property "org-element" (property element))
  32. (declare-function org-element-at-point "org-element" (&optional pom cached-only))
  33. (declare-function org-element-type "org-element" (element))
  34. (declare-function org-heading-components "org" ())
  35. (declare-function org-in-commented-heading-p "org" (&optional no-inheritance))
  36. (declare-function org-in-archived-heading-p "org" (&optional no-inheritance))
  37. (declare-function outline-previous-heading "outline" ())
  38. (defvar org-id-link-to-org-use-id) ; Dynamically scoped
  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. (defcustom org-babel-tangle-default-file-mode #o544
  122. "The default mode used for tangled files, as an integer.
  123. The default value 356 correspands to the octal #o544, which is
  124. read-write permissions for the user, read-only for everyone else."
  125. :group 'org-babel
  126. :package-version '(Org . "9.6")
  127. :type 'integer)
  128. (defun org-babel-find-file-noselect-refresh (file)
  129. "Find file ensuring that the latest changes on disk are
  130. represented in the file."
  131. (find-file-noselect file 'nowarn)
  132. (with-current-buffer (get-file-buffer file)
  133. (revert-buffer t t t)))
  134. (defmacro org-babel-with-temp-filebuffer (file &rest body)
  135. "Open FILE into a temporary buffer execute BODY there like
  136. `progn', then kill the FILE buffer returning the result of
  137. evaluating BODY."
  138. (declare (indent 1) (debug t))
  139. (let ((temp-path (make-symbol "temp-path"))
  140. (temp-result (make-symbol "temp-result"))
  141. (temp-file (make-symbol "temp-file"))
  142. (visited-p (make-symbol "visited-p")))
  143. `(let* ((,temp-path ,file)
  144. (,visited-p (get-file-buffer ,temp-path))
  145. ,temp-result ,temp-file)
  146. (org-babel-find-file-noselect-refresh ,temp-path)
  147. (setf ,temp-file (get-file-buffer ,temp-path))
  148. (with-current-buffer ,temp-file
  149. (setf ,temp-result (progn ,@body)))
  150. (unless ,visited-p (kill-buffer ,temp-file))
  151. ,temp-result)))
  152. ;;;###autoload
  153. (defun org-babel-tangle-file (file &optional target-file lang-re)
  154. "Extract the bodies of source code blocks in FILE.
  155. Source code blocks are extracted with `org-babel-tangle'.
  156. Optional argument TARGET-FILE can be used to specify a default
  157. export file for all source blocks.
  158. Optional argument LANG-RE can be used to limit the exported
  159. source code blocks by languages matching a regular expression.
  160. Return a list whose CAR is the tangled file name."
  161. (interactive "fFile to tangle: \nP")
  162. (let* ((visited (find-buffer-visiting file))
  163. (buffer (or visited (find-file-noselect file))))
  164. (prog1
  165. (with-current-buffer buffer
  166. (org-with-wide-buffer
  167. (mapcar #'expand-file-name
  168. (org-babel-tangle nil target-file lang-re))))
  169. (unless visited (kill-buffer buffer)))))
  170. (defun org-babel-tangle-publish (_ filename pub-dir)
  171. "Tangle FILENAME and place the results in PUB-DIR."
  172. (unless (file-exists-p pub-dir)
  173. (make-directory pub-dir t))
  174. (setq pub-dir (file-name-as-directory pub-dir))
  175. (mapc (lambda (el) (copy-file el pub-dir t)) (org-babel-tangle-file filename)))
  176. ;;;###autoload
  177. (defun org-babel-tangle (&optional arg target-file lang-re)
  178. "Write code blocks to source-specific files.
  179. Extract the bodies of all source code blocks from the current
  180. file into their own source-specific files.
  181. With one universal prefix argument, only tangle the block at point.
  182. When two universal prefix arguments, only tangle blocks for the
  183. tangle file of the block at point.
  184. Optional argument TARGET-FILE can be used to specify a default
  185. export file for all source blocks. Optional argument LANG-RE can
  186. be used to limit the exported source code blocks by languages
  187. matching a regular expression."
  188. (interactive "P")
  189. (run-hooks 'org-babel-pre-tangle-hook)
  190. ;; Possibly Restrict the buffer to the current code block
  191. (save-restriction
  192. (save-excursion
  193. (when (equal arg '(4))
  194. (let ((head (org-babel-where-is-src-block-head)))
  195. (if head
  196. (goto-char head)
  197. (user-error "Point is not in a source code block"))))
  198. (let ((block-counter 0)
  199. (org-babel-default-header-args
  200. (if target-file
  201. (org-babel-merge-params org-babel-default-header-args
  202. (list (cons :tangle target-file)))
  203. org-babel-default-header-args))
  204. (tangle-file
  205. (when (equal arg '(16))
  206. (or (cdr (assq :tangle (nth 2 (org-babel-get-src-block-info 'light))))
  207. (user-error "Point is not in a source code block"))))
  208. path-collector)
  209. (mapc ;; map over file-names
  210. (lambda (by-fn)
  211. (let ((file-name (car by-fn)))
  212. (when file-name
  213. (let ((lspecs (cdr by-fn))
  214. (fnd (file-name-directory file-name))
  215. modes make-dir she-banged lang)
  216. ;; drop source-blocks to file
  217. ;; We avoid append-to-file as it does not work with tramp.
  218. (with-temp-buffer
  219. (mapc
  220. (lambda (lspec)
  221. (let* ((block-lang (car lspec))
  222. (spec (cdr lspec))
  223. (get-spec (lambda (name) (cdr (assq name (nth 4 spec)))))
  224. (she-bang (let ((sheb (funcall get-spec :shebang)))
  225. (when (> (length sheb) 0) sheb)))
  226. (tangle-mode (funcall get-spec :tangle-mode)))
  227. (unless (string-equal block-lang lang)
  228. (setq lang block-lang)
  229. (let ((lang-f (org-src-get-lang-mode lang)))
  230. (when (fboundp lang-f) (ignore-errors (funcall lang-f)))))
  231. ;; if file contains she-bangs, then make it executable
  232. (when she-bang
  233. (unless tangle-mode (setq tangle-mode #o755)))
  234. (when tangle-mode
  235. (add-to-list 'modes (org-babel-interpret-file-mode tangle-mode)))
  236. ;; Possibly create the parent directories for file.
  237. (let ((m (funcall get-spec :mkdirp)))
  238. (and m fnd (not (string= m "no"))
  239. (setq make-dir t)))
  240. ;; Handle :padlines unless first line in file
  241. (unless (or (string= "no" (funcall get-spec :padline))
  242. (= (point) (point-min)))
  243. (insert "\n"))
  244. (when (and she-bang (not she-banged))
  245. (insert (concat she-bang "\n"))
  246. (setq she-banged t))
  247. (org-babel-spec-to-string spec)
  248. (setq block-counter (+ 1 block-counter))))
  249. lspecs)
  250. (when make-dir
  251. (make-directory fnd 'parents))
  252. (unless
  253. (and (file-exists-p file-name)
  254. (let ((tangle-buf (current-buffer)))
  255. (with-temp-buffer
  256. (insert-file-contents file-name)
  257. (and
  258. (equal (buffer-size)
  259. (buffer-size tangle-buf))
  260. (= 0
  261. (let (case-fold-search)
  262. (compare-buffer-substrings
  263. nil nil nil
  264. tangle-buf nil nil)))))))
  265. ;; erase previous file
  266. (when (file-exists-p file-name)
  267. (delete-file file-name))
  268. (write-region nil nil file-name)
  269. (mapc (lambda (mode) (set-file-modes file-name mode)) modes))
  270. (push file-name path-collector))))))
  271. (if (equal arg '(4))
  272. (org-babel-tangle-single-block 1 t)
  273. (org-babel-tangle-collect-blocks lang-re 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)
  279. (current-buffer)
  280. (and (org-src-edit-buffer-p)
  281. (org-src-source-buffer))))))
  282. ;; run `org-babel-post-tangle-hook' in all tangled files
  283. (when org-babel-post-tangle-hook
  284. (mapc
  285. (lambda (file)
  286. (org-babel-with-temp-filebuffer file
  287. (run-hooks 'org-babel-post-tangle-hook)))
  288. path-collector))
  289. path-collector))))
  290. (defun org-babel-interpret-file-mode (mode)
  291. "Determine the integer representation of a file MODE specification.
  292. The following forms are currently recognised:
  293. - an integer (returned without modification)
  294. - \"o755\" (chmod style octal)
  295. - \"rwxrw-r--\" (ls style specification)
  296. - \"a=rw,u+x\" (chmod style) *
  297. * The interpretation of these forms relies on `file-modes-symbolic-to-number',
  298. and uses `org-babel-tangle-default-file-mode' as the base mode."
  299. (cond
  300. ((integerp mode)
  301. (if (string-match-p "^[0-7][0-7][0-7]$" (format "%o" mode))
  302. mode
  303. (user-error "%1$o is not a valid file mode octal. \
  304. Did you give the decimal value %1$d by mistake?" mode)))
  305. ((not (stringp mode))
  306. (error "File mode %S not recognised as a valid format." mode))
  307. ((string-match-p "^o0?[0-7][0-7][0-7]$" mode)
  308. (string-to-number (replace-regexp-in-string "^o" "" mode) 8))
  309. ((string-match-p "^[ugoa]*\\(?:[+-=][rwxXstugo]*\\)+\\(,[ugoa]*\\(?:[+-=][rwxXstugo]*\\)+\\)*$" mode)
  310. ;; Match regexp taken from `file-modes-symbolic-to-number'.
  311. (file-modes-symbolic-to-number mode org-babel-tangle-default-file-mode))
  312. ((string-match-p "^[r-][w-][xs-][r-][w-][xs-][r-][w-][x-]$" mode)
  313. (file-modes-symbolic-to-number (concat "u=" (substring mode 0 3)
  314. ",g=" (substring mode 3 6)
  315. ",o=" (substring mode 6 9))
  316. 0))
  317. (t (error "File mode %S not recognised as a valid format. See `org-babel-interpret-file-mode'." mode))))
  318. (defun org-babel-tangle-clean ()
  319. "Remove comments inserted by `org-babel-tangle'.
  320. Call this function inside of a source-code file generated by
  321. `org-babel-tangle' to remove all comments inserted automatically
  322. by `org-babel-tangle'. Warning, this comment removes any lines
  323. containing constructs which resemble Org file links or noweb
  324. references."
  325. (interactive)
  326. (goto-char (point-min))
  327. (while (or (re-search-forward "\\[\\[file:.*\\]\\[.*\\]\\]" nil t)
  328. (re-search-forward (org-babel-noweb-wrap) nil t))
  329. (delete-region (save-excursion (beginning-of-line 1) (point))
  330. (save-excursion (end-of-line 1) (forward-char 1) (point)))))
  331. (defun org-babel-spec-to-string (spec)
  332. "Insert SPEC into the current file.
  333. Insert the source-code specified by SPEC into the current source
  334. code file. This function uses `comment-region' which assumes
  335. that the appropriate major-mode is set. SPEC has the form:
  336. (start-line file link source-name params body comment)"
  337. (pcase-let*
  338. ((`(,start ,file ,link ,source ,info ,body ,comment) spec)
  339. (comments (cdr (assq :comments info)))
  340. (link? (or (string= comments "both") (string= comments "link")
  341. (string= comments "yes") (string= comments "noweb")))
  342. (link-data `(("start-line" . ,(number-to-string start))
  343. ("file" . ,file)
  344. ("link" . ,link)
  345. ("source-name" . ,source)))
  346. (insert-comment (lambda (text)
  347. (when (and comments
  348. (not (string= comments "no"))
  349. (org-string-nw-p text))
  350. (if org-babel-tangle-uncomment-comments
  351. ;; Plain comments: no processing.
  352. (insert text)
  353. ;; Ensure comments are made to be
  354. ;; comments, and add a trailing newline.
  355. ;; Also ignore invisible characters when
  356. ;; commenting.
  357. (comment-region
  358. (point)
  359. (progn (insert (org-no-properties text))
  360. (point)))
  361. (end-of-line)
  362. (insert "\n"))))))
  363. (when comment (funcall insert-comment comment))
  364. (when link?
  365. (funcall insert-comment
  366. (org-fill-template
  367. org-babel-tangle-comment-format-beg link-data)))
  368. (insert body "\n")
  369. (when link?
  370. (funcall insert-comment
  371. (org-fill-template
  372. org-babel-tangle-comment-format-end link-data)))))
  373. (defun org-babel-effective-tangled-filename (buffer-fn src-lang src-tfile)
  374. "Return effective tangled filename of a source-code block.
  375. BUFFER-FN is the name of the buffer, SRC-LANG the language of the
  376. block and SRC-TFILE is the value of the :tangle header argument,
  377. as computed by `org-babel-tangle-single-block'."
  378. (let ((base-name (cond
  379. ((string= "yes" src-tfile)
  380. ;; Use the buffer name
  381. (file-name-sans-extension buffer-fn))
  382. ((string= "no" src-tfile) nil)
  383. ((> (length src-tfile) 0) src-tfile)))
  384. (ext (or (cdr (assoc src-lang org-babel-tangle-lang-exts)) src-lang)))
  385. (when base-name
  386. ;; decide if we want to add ext to base-name
  387. (if (and ext (string= "yes" src-tfile))
  388. (concat base-name "." ext) base-name))))
  389. (defun org-babel-tangle-collect-blocks (&optional lang-re tangle-file)
  390. "Collect source blocks in the current Org file.
  391. Return an association list of language and source-code block
  392. specifications of the form used by `org-babel-spec-to-string'
  393. grouped by tangled file name.
  394. Optional argument LANG-RE can be used to limit the collected
  395. source code blocks by languages matching a regular expression.
  396. Optional argument TANGLE-FILE can be used to limit the collected
  397. code blocks by target file."
  398. (let ((counter 0) last-heading-pos blocks)
  399. (org-babel-map-src-blocks (buffer-file-name)
  400. (let ((current-heading-pos
  401. (if (org-element--cache-active-p)
  402. (or (org-element-property :begin (org-element-lineage (org-element-at-point) '(headline) t)) 1)
  403. (org-with-wide-buffer
  404. (org-with-limited-levels (outline-previous-heading))))))
  405. (if (eq last-heading-pos current-heading-pos) (cl-incf counter)
  406. (setq counter 1)
  407. (setq last-heading-pos current-heading-pos)))
  408. (unless (or (org-in-commented-heading-p)
  409. (org-in-archived-heading-p))
  410. (let* ((info (org-babel-get-src-block-info 'light))
  411. (src-lang (nth 0 info))
  412. (src-tfile (cdr (assq :tangle (nth 2 info)))))
  413. (unless (or (string= src-tfile "no")
  414. (and tangle-file (not (equal tangle-file src-tfile)))
  415. (and lang-re (not (string-match-p lang-re src-lang))))
  416. ;; Add the spec for this block to blocks under its tangled
  417. ;; file name.
  418. (let* ((block (org-babel-tangle-single-block counter))
  419. (src-tfile (cdr (assq :tangle (nth 4 block))))
  420. (file-name (org-babel-effective-tangled-filename
  421. (nth 1 block) src-lang src-tfile))
  422. (by-fn (assoc file-name blocks)))
  423. (if by-fn (setcdr by-fn (cons (cons src-lang block) (cdr by-fn)))
  424. (push (cons file-name (list (cons src-lang block))) blocks)))))))
  425. ;; Ensure blocks are in the correct order.
  426. (mapcar (lambda (b) (cons (car b) (nreverse (cdr b))))
  427. (nreverse blocks))))
  428. (defun org-babel-tangle-single-block (block-counter &optional only-this-block)
  429. "Collect the tangled source for current block.
  430. Return the list of block attributes needed by
  431. `org-babel-tangle-collect-blocks'. When ONLY-THIS-BLOCK is
  432. non-nil, return the full association list to be used by
  433. `org-babel-tangle' directly."
  434. (let* ((info (org-babel-get-src-block-info))
  435. (start-line
  436. (save-restriction (widen)
  437. (+ 1 (line-number-at-pos (point)))))
  438. (file (buffer-file-name (buffer-base-buffer)))
  439. (src-lang (nth 0 info))
  440. (params (nth 2 info))
  441. (extra (nth 3 info))
  442. (coderef (nth 6 info))
  443. (cref-regexp (org-src-coderef-regexp coderef))
  444. (link (let* (
  445. ;; The created link is transient. Using ID is
  446. ;; not necessary, but could have side-effects if
  447. ;; used. An ID property may be added to
  448. ;; existing entries thus creatin unexpected file
  449. ;; modifications.
  450. (org-id-link-to-org-use-id nil)
  451. (l (org-no-properties (org-store-link nil))))
  452. (and (string-match org-link-bracket-re l)
  453. (match-string 1 l))))
  454. (source-name
  455. (or (nth 4 info)
  456. (format "%s:%d"
  457. (or (ignore-errors (nth 4 (org-heading-components)))
  458. "No heading")
  459. block-counter)))
  460. (expand-cmd (intern (concat "org-babel-expand-body:" src-lang)))
  461. (assignments-cmd
  462. (intern (concat "org-babel-variable-assignments:" src-lang)))
  463. (body
  464. ;; Run the tangle-body-hook.
  465. (let ((body (if (org-babel-noweb-p params :tangle)
  466. (org-babel-expand-noweb-references info)
  467. (nth 1 info))))
  468. (with-temp-buffer
  469. (insert
  470. ;; Expand body in language specific manner.
  471. (cond ((assq :no-expand params) body)
  472. ((fboundp expand-cmd) (funcall expand-cmd body params))
  473. (t
  474. (org-babel-expand-body:generic
  475. body params (and (fboundp assignments-cmd)
  476. (funcall assignments-cmd params))))))
  477. (when (string-match "-r" extra)
  478. (goto-char (point-min))
  479. (while (re-search-forward cref-regexp nil t)
  480. (replace-match "")))
  481. (run-hooks 'org-babel-tangle-body-hook)
  482. (buffer-string))))
  483. (comment
  484. (when (or (string= "both" (cdr (assq :comments params)))
  485. (string= "org" (cdr (assq :comments params))))
  486. ;; From the previous heading or code-block end
  487. (funcall
  488. org-babel-process-comment-text
  489. (buffer-substring
  490. (max (condition-case nil
  491. (save-excursion
  492. (org-back-to-heading t) ; Sets match data
  493. (match-end 0))
  494. (error (point-min)))
  495. (save-excursion
  496. (if (re-search-backward
  497. org-babel-src-block-regexp nil t)
  498. (match-end 0)
  499. (point-min))))
  500. (point)))))
  501. (src-tfile (cdr (assq :tangle params)))
  502. (result
  503. (list start-line
  504. (if org-babel-tangle-use-relative-file-links
  505. (file-relative-name file)
  506. file)
  507. (if (and org-babel-tangle-use-relative-file-links
  508. (string-match org-link-types-re link)
  509. (string= (match-string 1 link) "file")
  510. (stringp src-tfile))
  511. (concat "file:"
  512. (file-relative-name (substring link (match-end 0))
  513. (file-name-directory
  514. src-tfile)))
  515. link)
  516. source-name
  517. params
  518. (if org-src-preserve-indentation
  519. (org-trim body t)
  520. (org-trim (org-remove-indentation body)))
  521. comment)))
  522. (if only-this-block
  523. (let* ((file-name (org-babel-effective-tangled-filename
  524. (nth 1 result) src-lang src-tfile)))
  525. (list (cons file-name (list (cons src-lang result)))))
  526. result)))
  527. (defun org-babel-tangle-comment-links (&optional info)
  528. "Return a list of begin and end link comments for the code block at point.
  529. INFO, when non nil, is the source block information, as returned
  530. by `org-babel-get-src-block-info'."
  531. (let ((link-data (pcase (or info (org-babel-get-src-block-info 'light))
  532. (`(,_ ,_ ,_ ,_ ,name ,start ,_)
  533. `(("start-line" . ,(org-with-point-at start
  534. (number-to-string
  535. (line-number-at-pos))))
  536. ("file" . ,(buffer-file-name))
  537. ("link" . ,(let (;; The created link is transient. Using ID is
  538. ;; not necessary, but could have side-effects if
  539. ;; used. An ID property may be added to
  540. ;; existing entries thus creatin unexpected file
  541. ;; modifications.
  542. (org-id-link-to-org-use-id nil))
  543. (org-no-properties (org-store-link nil))))
  544. ("source-name" . ,name))))))
  545. (list (org-fill-template org-babel-tangle-comment-format-beg link-data)
  546. (org-fill-template org-babel-tangle-comment-format-end link-data))))
  547. ;; de-tangling functions
  548. (defun org-babel-detangle (&optional source-code-file)
  549. "Propagate changes in source file back original to Org file.
  550. This requires that code blocks were tangled with link comments
  551. which enable the original code blocks to be found."
  552. (interactive)
  553. (save-excursion
  554. (when source-code-file (find-file source-code-file))
  555. (goto-char (point-min))
  556. (let ((counter 0) new-body end)
  557. (while (re-search-forward org-link-bracket-re nil t)
  558. (if (and (match-string 2)
  559. (re-search-forward
  560. (concat " " (regexp-quote (match-string 2)) " ends here") nil t))
  561. (progn (setq end (match-end 0))
  562. (forward-line -1)
  563. (save-excursion
  564. (when (setq new-body (org-babel-tangle-jump-to-org))
  565. (org-babel-update-block-body new-body)))
  566. (setq counter (+ 1 counter)))
  567. (setq end (point)))
  568. (goto-char end))
  569. (prog1 counter (message "Detangled %d code blocks" counter)))))
  570. (defun org-babel-tangle-jump-to-org ()
  571. "Jump from a tangled code file to the related Org mode file."
  572. (interactive)
  573. (let ((mid (point))
  574. start body-start end target-buffer target-char link block-name body)
  575. (save-window-excursion
  576. (save-excursion
  577. (while (and (re-search-backward org-link-bracket-re nil t)
  578. (not ; ever wider searches until matching block comments
  579. (and (setq start (line-beginning-position))
  580. (setq body-start (line-beginning-position 2))
  581. (setq link (match-string 0))
  582. (setq block-name (match-string 2))
  583. (save-excursion
  584. (save-match-data
  585. (re-search-forward
  586. (concat " " (regexp-quote block-name)
  587. " ends here")
  588. nil t)
  589. (setq end (line-beginning-position))))))))
  590. (unless (and start (< start mid) (< mid end))
  591. (error "Not in tangled code"))
  592. (setq body (buffer-substring body-start end)))
  593. ;; Go to the beginning of the relative block in Org file.
  594. ;; Explicitly allow fuzzy search even if user customized
  595. ;; otherwise.
  596. (let (org-link-search-must-match-exact-headline)
  597. (org-link-open-from-string link))
  598. (setq target-buffer (current-buffer))
  599. (if (string-match "[^ \t\n\r]:\\([[:digit:]]+\\)" block-name)
  600. (let ((n (string-to-number (match-string 1 block-name))))
  601. (if (org-before-first-heading-p) (goto-char (point-min))
  602. (org-back-to-heading t))
  603. ;; Do not skip the first block if it begins at point min.
  604. (cond ((or (org-at-heading-p)
  605. (not (eq (org-element-type (org-element-at-point))
  606. 'src-block)))
  607. (org-babel-next-src-block n))
  608. ((= n 1))
  609. (t (org-babel-next-src-block (1- n)))))
  610. (org-babel-goto-named-src-block block-name))
  611. (goto-char (org-babel-where-is-src-block-head))
  612. (forward-line 1)
  613. ;; Try to preserve location of point within the source code in
  614. ;; tangled code file.
  615. (let ((offset (- mid body-start)))
  616. (when (> end (+ offset (point)))
  617. (forward-char offset)))
  618. (setq target-char (point)))
  619. (org-src-switch-to-buffer target-buffer t)
  620. (goto-char target-char)
  621. body))
  622. (provide 'ob-tangle)
  623. ;; Local variables:
  624. ;; generated-autoload-file: "org-loaddefs.el"
  625. ;; End:
  626. ;;; ob-tangle.el ends here