ob-tangle.el 27 KB

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