Adding own answer, since diff-apply-hunk
didn't do exactly what I wanted.
This is a stripped down diff-apply-hunk
with some modified behavior, to revert hunks without changing the context.
- The buffer is saved after reverting.
- The hunk is removed.
- No new windows open.
It allows for quickly navigating over a diff and reverting hunks, without having to switch buffers and save each time.
(defun diff-apply-hunk-reverse-and-save (&optional _arg)
"Revert the current hunk, removing it from the diff, saving the buffer immediately."
(interactive "P")
(diff-beginning-of-hunk t)
(pcase-let
(
(`(,buf ,line-offset ,pos ,_old ,new ,switched)
(diff-find-source-location nil t))) ;; last arg is 't for always reversed.
(cond
((null line-offset)
(error "Can't find the text to patch"))
(switched
(error "Patch is already removed"))
(t ;; Apply the hunk
(with-current-buffer buf
(goto-char (car pos))
(delete-region (car pos) (cdr pos))
(insert (car new))
(save-buffer))
(diff-hunk-kill)))))