Subject: Re: bug#42145: vc-git file order mismatch between vc-dir and vc-diff

From: Juri Linkov <[email-masked]>
Date: Tue, 30 Mar 2021 22:23:59 +0300

>> There is an old usability problem in vc-dir.
>> Typing ‘=’ in a vc-dir buffer displays a vc-diff buffer where files are
>> sorted by different order than files are sorted in the vc-dir buffer.
>
> vc-dir has its own presentation logic, it's pretty complex.
>
> 'git diff' has a '-O' argument, which accepts <orderfile>. Maybe it'll
> help, but I kind of doubt that. Ideas welcome.

I solved this problem by adding two advises:

1. vc-dir-deduce-fileset - create orderfile
2. vc-git-diff - use orderfile

#+begin_src emacs-lisp
(defvar vc-git-orderfile nil)

(advice-add 'vc-dir-deduce-fileset :after
            (lambda (&rest _)
              (when (and vc-ewoc (eq this-command 'vc-diff))
                (let* ((tmpfile (make-temp-file "vc-git-orderfile-"))
                       files)
                  (ewoc-map (lambda (filearg)
                              (push (vc-dir-fileinfo->name filearg) files))
                            vc-ewoc)
                  (with-temp-file tmpfile
                    (mapcar (lambda (file) (insert file "\n")) (nreverse files)))
                  (setq vc-git-orderfile tmpfile))))
            '((name . vc-dir-create-orderfile)))

(advice-add 'vc-git-diff :around
            (lambda (orig-fun &rest args)
              (if (and vc-git-orderfile (file-exists-p vc-git-orderfile))
                  (let ((vc-git-diff-switches
                         (append (list (format "-O%s" vc-git-orderfile))
                                 vc-git-diff-switches)))
                    (unwind-protect
	                (apply orig-fun args)
	              (delete-file vc-git-orderfile)
                      (setq vc-git-orderfile nil)))
                (apply orig-fun args)))
            '((name . vc-git-diff-use-orderfile)))
#+end_src

Ideas welcome how to integrate this nicely to the vc package.

Also it has one limitation: revert-buffer in the *vc-diff* buffer
doesn't keep the original order, but this is a very minor problem.