Subject: 25.1; completion: display-sort-function=identity shows reverse

From: Kyle Meyer <[email-masked]>
Date: Thu, 30 Mar 2017 14:34:47 -0400

I'm trying to make the *Completions* help buffer display the collection
in the original order passed to completing-read.  I found a question
about this on Emacs StackExchange [*1*], and Stefan's advice was to
specify display-sort-function for the completion table.

  (defun my-presorted-completion-table (completions)
    (lambda (string pred action)
      (if (eq action 'metadata)
          `(metadata (display-sort-function . ,#'identity))
        (complete-with-action action completions string pred))))

  (completing-read "test: " (my-presorted-completion-table
                             '("d" "e" "a" "r")))

Hitting tab to bring up the help buffer shows that this does override
the default alphabetical sorting, but it displays the list in reverse,
with "r" as the first item [*2*].

Replacing "identity" with "nreverse" shows the list in the expected
order.  It seems that the collection needs to be reversed to get the
original order because completion-pcm--all-completions returns the items
in reverse, constructing the list with "(dolist _ (push ...))".

However, using nreverse for the display-sort-function messes up the
order displayed for partial completions because
completion-pcm--all-completions returns the result of all-completions
rather than following the "dolist" path described above.  For example,

  (completing-read "test: " (my-presorted-completion-table
                             '("db" "dd" "da" "e" "a" "r")))

with "d<TAB>" now shows "da dd db" instead of "db dd da".

Should completion-pcm--all-completions reverse the list before returning
it?  With identity as the display-sort-function, this change appears to
give the correct order for both cases above (empty input and partial
input).

--8<---------------cut here---------------start------------->8---
diff --git a/lisp/minibuffer.el b/lisp/minibuffer.el
index 355d2ee6af..2e2c55db5e 100644
--- a/lisp/minibuffer.el
+++ b/lisp/minibuffer.el
@@ -2994,7 +2994,7 @@ completion-pcm--all-completions
 	(let ((poss ()))
 	  (dolist (c compl)
 	    (when (string-match-p regex c) (push c poss)))
-	  poss)))))
+	  (nreverse poss))))))
 
 (defun completion-pcm--hilit-commonality (pattern completions)
   (when completions
--8<---------------cut here---------------end--------------->8---

[*1*] http://emacs.stackexchange.com/questions/8115/make-completing-read-respect-sorting-order-of-a-collection/8177#8177

[*2*] Evaluated in a buffer visited with "emacs -Q", Emacs 25.1.1

-- 
Kyle