1 ;;; ob-tangle.el --- Extract Source Code From Org Files -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2009-2018 Free Software Foundation, Inc.
5 ;; Author: Eric Schulte
6 ;; Keywords: literate programming, reproducible research
7 ;; Homepage: https://orgmode.org
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
26 ;; Extract the code from source blocks out into raw source-code files.
34 (declare-function make-directory
"files" (dir &optional parents
))
35 (declare-function org-at-heading-p
"org" (&optional ignored
))
36 (declare-function org-babel-update-block-body
"ob-core" (new-body))
37 (declare-function org-back-to-heading
"org" (&optional invisible-ok
))
38 (declare-function org-before-first-heading-p
"org" ())
39 (declare-function org-element-at-point
"org-element" ())
40 (declare-function org-element-type
"org-element" (element))
41 (declare-function org-fill-template
"org" (template alist
))
42 (declare-function org-heading-components
"org" ())
43 (declare-function org-id-find
"org-id" (id &optional markerp
))
44 (declare-function org-in-commented-heading-p
"org" (&optional no-inheritance
))
45 (declare-function org-link-escape
"org" (text &optional table merge
))
46 (declare-function org-open-link-from-string
"org" (s &optional arg reference-buffer
))
47 (declare-function org-store-link
"org" (arg &optional interactive?
))
48 (declare-function outline-previous-heading
"outline" ())
50 (defvar org-link-types-re
)
52 (defcustom org-babel-tangle-lang-exts
53 '(("emacs-lisp" .
"el")
55 "Alist mapping languages to their file extensions.
56 The key is the language name, the value is the string that should
57 be inserted as the extension commonly used to identify files
58 written in this language. If no entry is found in this list,
59 then the name of the language is used."
60 :group
'org-babel-tangle
64 (string "Language name")
65 (string "File Extension"))))
67 (defcustom org-babel-tangle-use-relative-file-links t
68 "Use relative path names in links from tangled source back the Org file."
69 :group
'org-babel-tangle
72 (defcustom org-babel-post-tangle-hook nil
73 "Hook run in code files tangled by `org-babel-tangle'."
78 (defcustom org-babel-pre-tangle-hook
'(save-buffer)
79 "Hook run at the beginning of `org-babel-tangle'."
84 (defcustom org-babel-tangle-body-hook nil
85 "Hook run over the contents of each code block body."
90 (defcustom org-babel-tangle-comment-format-beg
"[[%link][%source-name]]"
91 "Format of inserted comments in tangled code files.
92 The following format strings can be used to insert special
93 information into the output using `org-fill-template'.
94 %start-line --- the line number at the start of the code block
95 %file --------- the file from which the code block was tangled
96 %link --------- Org style link to the code block
97 %source-name -- name of the code block
99 Upon insertion the formatted comment will be commented out, and
100 followed by a newline. To inhibit this post-insertion processing
101 set the `org-babel-tangle-uncomment-comments' variable to a
104 Whether or not comments are inserted during tangling is
105 controlled by the :comments header argument."
110 (defcustom org-babel-tangle-comment-format-end
"%source-name ends here"
111 "Format of inserted comments in tangled code files.
112 The following format strings can be used to insert special
113 information into the output using `org-fill-template'.
114 %start-line --- the line number at the start of the code block
115 %file --------- the file from which the code block was tangled
116 %link --------- Org style link to the code block
117 %source-name -- name of the code block
119 Upon insertion the formatted comment will be commented out, and
120 followed by a newline. To inhibit this post-insertion processing
121 set the `org-babel-tangle-uncomment-comments' variable to a
124 Whether or not comments are inserted during tangling is
125 controlled by the :comments header argument."
130 (defcustom org-babel-tangle-uncomment-comments nil
131 "Inhibits automatic commenting and addition of trailing newline
132 of tangle comments. Use `org-babel-tangle-comment-format-beg'
133 and `org-babel-tangle-comment-format-end' to customize the format
134 of tangled comments."
138 (defcustom org-babel-process-comment-text
'org-remove-indentation
139 "Function called to process raw Org text collected to be
140 inserted as comments in tangled source-code files. The function
141 should take a single string argument and return a string
142 result. The default value is `org-remove-indentation'."
147 (defun org-babel-find-file-noselect-refresh (file)
148 "Find file ensuring that the latest changes on disk are
149 represented in the file."
150 (find-file-noselect file
'nowarn
)
151 (with-current-buffer (get-file-buffer file
)
152 (revert-buffer t t t
)))
154 (defmacro org-babel-with-temp-filebuffer
(file &rest body
)
155 "Open FILE into a temporary buffer execute BODY there like
156 `progn', then kill the FILE buffer returning the result of
159 (let ((temp-path (make-symbol "temp-path"))
160 (temp-result (make-symbol "temp-result"))
161 (temp-file (make-symbol "temp-file"))
162 (visited-p (make-symbol "visited-p")))
163 `(let* ((,temp-path
,file
)
164 (,visited-p
(get-file-buffer ,temp-path
))
165 ,temp-result
,temp-file
)
166 (org-babel-find-file-noselect-refresh ,temp-path
)
167 (setf ,temp-file
(get-file-buffer ,temp-path
))
168 (with-current-buffer ,temp-file
169 (setf ,temp-result
(progn ,@body
)))
170 (unless ,visited-p
(kill-buffer ,temp-file
))
172 (def-edebug-spec org-babel-with-temp-filebuffer
(form body
))
175 (defun org-babel-tangle-file (file &optional target-file lang
)
176 "Extract the bodies of source code blocks in FILE.
177 Source code blocks are extracted with `org-babel-tangle'.
178 Optional argument TARGET-FILE can be used to specify a default
179 export file for all source blocks. Optional argument LANG can be
180 used to limit the exported source code blocks by language.
181 Return a list whose CAR is the tangled file name."
182 (interactive "fFile to tangle: \nP")
183 (let ((visited-p (get-file-buffer (expand-file-name file
)))
186 (save-window-excursion
188 (setq to-be-removed
(current-buffer))
189 (mapcar #'expand-file-name
(org-babel-tangle nil target-file lang
)))
191 (kill-buffer to-be-removed
)))))
193 (defun org-babel-tangle-publish (_ filename pub-dir
)
194 "Tangle FILENAME and place the results in PUB-DIR."
195 (unless (file-exists-p pub-dir
)
196 (make-directory pub-dir t
))
197 (setq pub-dir
(file-name-as-directory pub-dir
))
198 (mapc (lambda (el) (copy-file el pub-dir t
)) (org-babel-tangle-file filename
)))
201 (defun org-babel-tangle (&optional arg target-file lang
)
202 "Write code blocks to source-specific files.
203 Extract the bodies of all source code blocks from the current
204 file into their own source-specific files.
205 With one universal prefix argument, only tangle the block at point.
206 When two universal prefix arguments, only tangle blocks for the
207 tangle file of the block at point.
208 Optional argument TARGET-FILE can be used to specify a default
209 export file for all source blocks. Optional argument LANG can be
210 used to limit the exported source code blocks by language."
212 (run-hooks 'org-babel-pre-tangle-hook
)
213 ;; Possibly Restrict the buffer to the current code block
216 (when (equal arg
'(4))
217 (let ((head (org-babel-where-is-src-block-head)))
220 (user-error "Point is not in a source code block"))))
221 (let ((block-counter 0)
222 (org-babel-default-header-args
224 (org-babel-merge-params org-babel-default-header-args
225 (list (cons :tangle target-file
)))
226 org-babel-default-header-args
))
228 (when (equal arg
'(16))
229 (or (cdr (assq :tangle
(nth 2 (org-babel-get-src-block-info 'light
))))
230 (user-error "Point is not in a source code block"))))
232 (mapc ;; map over all languages
234 (let* ((lang (car by-lang
))
235 (specs (cdr by-lang
))
236 (ext (or (cdr (assoc lang org-babel-tangle-lang-exts
)) lang
))
239 (or (and (cdr (assoc lang org-src-lang-modes
))
241 (cdr (assoc lang org-src-lang-modes
))))
247 (let ((get-spec (lambda (name) (cdr (assoc name
(nth 4 spec
))))))
248 (let* ((tangle (funcall get-spec
:tangle
))
249 (she-bang (let ((sheb (funcall get-spec
:shebang
)))
250 (when (> (length sheb
) 0) sheb
)))
251 (tangle-mode (funcall get-spec
:tangle-mode
))
253 ((string= "yes" tangle
)
254 (file-name-sans-extension
256 ((string= "no" tangle
) nil
)
257 ((> (length tangle
) 0) tangle
)))
258 (file-name (when base-name
259 ;; decide if we want to add ext to base-name
260 (if (and ext
(string= "yes" tangle
))
261 (concat base-name
"." ext
) base-name
))))
263 ;; Possibly create the parent directories for file.
264 (let ((m (funcall get-spec
:mkdirp
))
265 (fnd (file-name-directory file-name
)))
266 (and m fnd
(not (string= m
"no"))
267 (make-directory fnd
'parents
)))
268 ;; delete any old versions of file
269 (and (file-exists-p file-name
)
270 (not (member file-name
(mapcar #'car path-collector
)))
271 (delete-file file-name
))
272 ;; drop source-block to file
274 (when (fboundp lang-f
) (ignore-errors (funcall lang-f
)))
275 (when (and she-bang
(not (member file-name she-banged
)))
276 (insert (concat she-bang
"\n"))
277 (setq she-banged
(cons file-name she-banged
)))
278 (org-babel-spec-to-string spec
)
279 ;; We avoid append-to-file as it does not work with tramp.
280 (let ((content (buffer-string)))
282 (when (file-exists-p file-name
)
283 (insert-file-contents file-name
))
284 (goto-char (point-max))
285 ;; Handle :padlines unless first line in file
286 (unless (or (string= "no" (cdr (assq :padline
(nth 4 spec
))))
287 (= (point) (point-min)))
290 (write-region nil nil file-name
))))
291 ;; if files contain she-bangs, then make the executable
293 (unless tangle-mode
(setq tangle-mode
#o755
)))
295 (setq block-counter
(+ 1 block-counter
))
296 (unless (assoc file-name path-collector
)
297 (push (cons file-name tangle-mode
) path-collector
))))))
300 (org-babel-tangle-single-block 1 t
)
301 (org-babel-tangle-collect-blocks lang tangle-file
)))
302 (message "Tangled %d code block%s from %s" block-counter
303 (if (= block-counter
1) "" "s")
304 (file-name-nondirectory
306 (or (buffer-base-buffer) (current-buffer)))))
307 ;; run `org-babel-post-tangle-hook' in all tangled files
308 (when org-babel-post-tangle-hook
311 (org-babel-with-temp-filebuffer file
312 (run-hooks 'org-babel-post-tangle-hook
)))
313 (mapcar #'car path-collector
)))
314 ;; set permissions on tangled files
316 (when (cdr pair
) (set-file-modes (car pair
) (cdr pair
))))
318 (mapcar #'car path-collector
)))))
320 (defun org-babel-tangle-clean ()
321 "Remove comments inserted by `org-babel-tangle'.
322 Call this function inside of a source-code file generated by
323 `org-babel-tangle' to remove all comments inserted automatically
324 by `org-babel-tangle'. Warning, this comment removes any lines
325 containing constructs which resemble Org file links or noweb
328 (goto-char (point-min))
329 (while (or (re-search-forward "\\[\\[file:.*\\]\\[.*\\]\\]" nil t
)
330 (re-search-forward (org-babel-noweb-wrap) nil t
))
331 (delete-region (save-excursion (beginning-of-line 1) (point))
332 (save-excursion (end-of-line 1) (forward-char 1) (point)))))
334 (defvar org-stored-links
)
335 (defvar org-bracket-link-regexp
)
336 (defun org-babel-spec-to-string (spec)
337 "Insert SPEC into the current file.
339 Insert the source-code specified by SPEC into the current source
340 code file. This function uses `comment-region' which assumes
341 that the appropriate major-mode is set. SPEC has the form:
343 (start-line file link source-name params body comment)"
345 ((`(,start
,file
,link
,source
,info
,body
,comment
) spec
)
346 (comments (cdr (assq :comments info
)))
347 (link?
(or (string= comments
"both") (string= comments
"link")
348 (string= comments
"yes") (string= comments
"noweb")))
349 (link-data `(("start-line" .
,(number-to-string start
))
352 ("source-name" .
,source
)))
353 (insert-comment (lambda (text)
355 (not (string= comments
"no"))
356 (org-string-nw-p text
))
357 (if org-babel-tangle-uncomment-comments
358 ;; Plain comments: no processing.
360 ;; Ensure comments are made to be
361 ;; comments, and add a trailing newline.
362 ;; Also ignore invisible characters when
366 (progn (insert (org-no-properties text
))
370 (when comment
(funcall insert-comment comment
))
372 (funcall insert-comment
374 org-babel-tangle-comment-format-beg link-data
)))
377 (funcall insert-comment
379 org-babel-tangle-comment-format-end link-data
)))))
381 (defun org-babel-tangle-collect-blocks (&optional language tangle-file
)
382 "Collect source blocks in the current Org file.
383 Return an association list of source-code block specifications of
384 the form used by `org-babel-spec-to-string' grouped by language.
385 Optional argument LANGUAGE can be used to limit the collected
386 source code blocks by language. Optional argument TANGLE-FILE
387 can be used to limit the collected code blocks by target file."
388 (let ((counter 0) last-heading-pos blocks
)
389 (org-babel-map-src-blocks (buffer-file-name)
390 (let ((current-heading-pos
391 (org-with-wide-buffer
392 (org-with-limited-levels (outline-previous-heading)))))
393 (if (eq last-heading-pos current-heading-pos
) (cl-incf counter
)
395 (setq last-heading-pos current-heading-pos
)))
396 (unless (org-in-commented-heading-p)
397 (let* ((info (org-babel-get-src-block-info 'light
))
398 (src-lang (nth 0 info
))
399 (src-tfile (cdr (assq :tangle
(nth 2 info
)))))
400 (unless (or (string= src-tfile
"no")
401 (and tangle-file
(not (equal tangle-file src-tfile
)))
402 (and language
(not (string= language src-lang
))))
403 ;; Add the spec for this block to blocks under its
405 (let ((by-lang (assoc src-lang blocks
))
406 (block (org-babel-tangle-single-block counter
)))
407 (if by-lang
(setcdr by-lang
(cons block
(cdr by-lang
)))
408 (push (cons src-lang
(list block
)) blocks
)))))))
409 ;; Ensure blocks are in the correct order.
410 (mapcar (lambda (b) (cons (car b
) (nreverse (cdr b
)))) blocks
)))
412 (defun org-babel-tangle-single-block (block-counter &optional only-this-block
)
413 "Collect the tangled source for current block.
414 Return the list of block attributes needed by
415 `org-babel-tangle-collect-blocks'. When ONLY-THIS-BLOCK is
416 non-nil, return the full association list to be used by
417 `org-babel-tangle' directly."
418 (let* ((info (org-babel-get-src-block-info))
420 (save-restriction (widen)
421 (+ 1 (line-number-at-pos (point)))))
422 (file (buffer-file-name (buffer-base-buffer)))
423 (src-lang (nth 0 info
))
424 (params (nth 2 info
))
426 (cref-fmt (or (and (string-match "-l \"\\(.+\\)\"" extra
)
427 (match-string 1 extra
))
428 org-coderef-label-format
))
429 (link (let ((l (org-no-properties (org-store-link nil
))))
430 (and (string-match org-bracket-link-regexp l
)
431 (match-string 1 l
))))
435 (or (ignore-errors (nth 4 (org-heading-components)))
438 (expand-cmd (intern (concat "org-babel-expand-body:" src-lang
)))
440 (intern (concat "org-babel-variable-assignments:" src-lang
)))
442 ;; Run the tangle-body-hook.
443 (let ((body (if (org-babel-noweb-p params
:tangle
)
444 (org-babel-expand-noweb-references info
)
448 ;; Expand body in language specific manner.
449 (cond ((assq :no-expand params
) body
)
450 ((fboundp expand-cmd
) (funcall expand-cmd body params
))
452 (org-babel-expand-body:generic
453 body params
(and (fboundp assignments-cmd
)
454 (funcall assignments-cmd params
))))))
455 (when (string-match "-r" extra
)
456 (goto-char (point-min))
457 (while (re-search-forward
458 (replace-regexp-in-string "%s" ".+" cref-fmt
) nil t
)
460 (run-hooks 'org-babel-tangle-body-hook
)
463 (when (or (string= "both" (cdr (assq :comments params
)))
464 (string= "org" (cdr (assq :comments params
))))
465 ;; From the previous heading or code-block end
467 org-babel-process-comment-text
469 (max (condition-case nil
471 (org-back-to-heading t
) ; Sets match data
475 (if (re-search-backward
476 org-babel-src-block-regexp nil t
)
482 (if org-babel-tangle-use-relative-file-links
483 (file-relative-name file
)
485 (if (and org-babel-tangle-use-relative-file-links
486 (string-match org-link-types-re link
)
487 (string= (match-string 0 link
) "file"))
489 (file-relative-name (match-string 1 link
)
491 (cdr (assq :tangle params
)))))
495 (if org-src-preserve-indentation
497 (org-trim (org-remove-indentation body
)))
500 (list (cons src-lang
(list result
)))
503 (defun org-babel-tangle-comment-links (&optional info
)
504 "Return a list of begin and end link comments for the code block at point."
506 `(("start-line" .
,(number-to-string
507 (org-babel-where-is-src-block-head)))
508 ("file" .
,(buffer-file-name))
509 ("link" .
,(org-link-escape
511 (call-interactively #'org-store-link
)
512 (org-no-properties (car (pop org-stored-links
))))))
514 ,(nth 4 (or info
(org-babel-get-src-block-info 'light
)))))))
515 (list (org-fill-template org-babel-tangle-comment-format-beg link-data
)
516 (org-fill-template org-babel-tangle-comment-format-end link-data
))))
518 ;; de-tangling functions
519 (defvar org-bracket-link-analytic-regexp
)
520 (defun org-babel-detangle (&optional source-code-file
)
521 "Propagate changes in source file back original to Org file.
522 This requires that code blocks were tangled with link comments
523 which enable the original code blocks to be found."
526 (when source-code-file
(find-file source-code-file
))
527 (goto-char (point-min))
528 (let ((counter 0) new-body end
)
529 (while (re-search-forward org-bracket-link-analytic-regexp nil t
)
530 (when (re-search-forward
531 (concat " " (regexp-quote (match-string 5)) " ends here"))
532 (setq end
(match-end 0))
535 (when (setq new-body
(org-babel-tangle-jump-to-org))
536 (org-babel-update-block-body new-body
)))
537 (setq counter
(+ 1 counter
)))
539 (prog1 counter
(message "Detangled %d code blocks" counter
)))))
541 (defun org-babel-tangle-jump-to-org ()
542 "Jump from a tangled code file to the related Org mode file."
546 target-buffer target-char link path block-name body
)
547 (save-window-excursion
549 (while (and (re-search-backward org-bracket-link-analytic-regexp nil t
)
550 (not ; ever wider searches until matching block comments
551 (and (setq start
(line-beginning-position))
552 (setq body-start
(line-beginning-position 2))
553 (setq link
(match-string 0))
554 (setq path
(match-string 3))
555 (setq block-name
(match-string 5))
559 (concat " " (regexp-quote block-name
)
561 (setq end
(line-beginning-position))))))))
562 (unless (and start
(< start mid
) (< mid end
))
563 (error "Not in tangled code"))
564 (setq body
(buffer-substring body-start end
)))
565 (when (string-match "::" path
)
566 (setq path
(substring path
0 (match-beginning 0))))
567 (find-file (or (car (org-id-find path
)) path
))
568 (setq target-buffer
(current-buffer))
569 ;; Go to the beginning of the relative block in Org file.
570 (org-open-link-from-string link
)
571 (if (string-match "[^ \t\n\r]:\\([[:digit:]]+\\)" block-name
)
572 (let ((n (string-to-number (match-string 1 block-name
))))
573 (if (org-before-first-heading-p) (goto-char (point-min))
574 (org-back-to-heading t
))
575 ;; Do not skip the first block if it begins at point min.
576 (cond ((or (org-at-heading-p)
577 (not (eq (org-element-type (org-element-at-point))
579 (org-babel-next-src-block n
))
581 (t (org-babel-next-src-block (1- n
)))))
582 (org-babel-goto-named-src-block block-name
))
583 (goto-char (org-babel-where-is-src-block-head))
585 ;; Try to preserve location of point within the source code in
586 ;; tangled code file.
587 (let ((offset (- mid body-start
)))
588 (when (> end
(+ offset
(point)))
589 (forward-char offset
)))
590 (setq target-char
(point)))
591 (org-src-switch-to-buffer target-buffer t
)
592 (goto-char target-char
)
598 ;; generated-autoload-file: "org-loaddefs.el"
601 ;;; ob-tangle.el ends here