ob-tangle.el 26 KB

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