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