"Charles C. Berry" <ccbe...@ucsd.edu> writes:
[...] > It sounds like you are re-inventing version control and wanting it to be > implemented in org-babel-tangle. > > `org-babel-tangle' can do a lot of work to assemble the files that result > from tangling. Modifying `org-babel-tangle' to do what you ask would be > far from trivial and make a complicated function even more tortuous. Yes, I agree it is not an easy task. > IMHO, it is better to solve your problem as follows: Set up a separate > directory into which files are tangled. Use version control on that > directory. Inspect changes after each tangle using the version control > system's diff tools, commit good changes, and revert unwanted ones. Then > run a script that uses the VC's data to identify changed files and copy > those files to the location on your system where they will be used. I found 'C-x s' ('save-some-buffers') can be used as the "version control", so I made a wrapper command for 'org-babel-tangle' using it. The wrapper command is not perfect (I guess it doesn't support remote-file and doesn't always respect tangle-mode, for example), but I am OK with it and it already does what I want. #+BEGIN_SRC emacs-lisp :results silent :lexical yes (defun chunyang-org-babel-tangle (&optional arg target-file lang) "Like `org-babel-tangle' but don't override without permission." (declare (interactive-only org-babel-tangle)) (interactive "P") (require 'ob-tangle) (require 'seq) (require 'cl-lib) (save-some-buffers) (let* ((tmpdir (let ((dir "/tmp/org-babel-tangle/")) (or (file-exists-p dir) (make-directory dir)) dir)) (mkbak (lambda (filename) (expand-file-name (replace-regexp-in-string "/" "!" (expand-file-name filename)) tmpdir))) (diffp (lambda (file-a file-b) (/= 0 (call-process diff-command nil nil nil (expand-file-name file-a) file-b)))) (swap (lambda (file-a file-b) (let ((tmp (make-temp-name tmpdir))) (copy-file file-a tmp t t t t) (copy-file file-b file-a t t t t) (copy-file tmp file-b t t t t)))) deleted-files tangled-files (advice (define-advice delete-file (:around (old-fun filename &rest args) dont-delete) (push filename deleted-files) (copy-file filename (funcall mkbak filename) t t t t) (apply old-fun filename args)))) (unwind-protect (progn (setq tangled-files (org-babel-tangle arg target-file lang) deleted-files (nreverse deleted-files)) (cl-loop for f in (seq-intersection deleted-files tangled-files) for bak = (funcall mkbak f) do (funcall swap f bak) (if (funcall diffp f bak) (with-current-buffer (find-file-noselect f) (message "Diff %s..." f) (delete-region (point-min) (point-max)) (insert-file-contents bak)) (message "Skip %s..." f)) finally (save-some-buffers))) (advice-remove 'delete-file advice)))) #+END_SRC [...]