Subject: Re: bug#62700: 29.0.60; minibuffer-{previous,next,choose}-completion behave unintuitively when point is not at end of buffer

From: [email-masked]
Date: Fri, 07 Apr 2023 21:02:47 +0000 (UTC)

Juri Linkov <[email-masked]> writes:
> Changing the API will definitely cause problems with backwards-compatibility.
> But maybe you could find a simple heuristic that would decide what base-suffix
> to set in minibuffer-completion-help?  Then no API changes will be needed.

Thank you for the guidance and suggestion.

Here's one heuristic which works decently well:

diff --git a/lisp/minibuffer.el b/lisp/minibuffer.el
index 21d4607e7cf..dfb06b5b88f 100644
--- a/lisp/minibuffer.el
+++ b/lisp/minibuffer.el
@@ -2374,7 +2374,11 @@ minibuffer-completion-help
              (prefix (unless (zerop base-size) (substring string 0 base-size)))
              (base-prefix (buffer-substring (minibuffer--completion-prompt-end)
                                             (+ start base-size)))
-             (base-suffix (buffer-substring (point) (point-max)))
+             (base-suffix
+              (if (eq (alist-get 'category (cdr md)) 'file)
+                  (buffer-substring (save-excursion (search-forward "/" nil t) (point))
+                                    (point-max))
+                ""))
              (all-md (completion--metadata (buffer-substring-no-properties
                                             start (point))
                                            base-size md

The reasoning here is that if completion returns the full string which
should be in the minibuffer, then we should replace the minibuffer with
that string, so base-suffix should be "".  But if we're completing only
part of the string, base-suffix should be something else.  AFAIK only
file completion falls into the latter category, and it always completes
just one component of a path, so I set base-suffix to not include the
component of the path that point is in, so that completion replaces it
entirely.

I think this is basically a satisfactory heuristic, although I'm sure
I'm missing some categories of completion besides file completion which
complete only part of the string.

Regardless of whether this is a satisfactory heuristic, it's revealed to
me an unexpected behavior of a solution to this bug using base-suffix,
which may or may not be fine: Point is moved to the end of the
completion inserted.

So e.g. if point is at | and I'm completing |-path, then when I choose
the completion load-path, point will be at load-path| rather than
load|-path.  This isn't a huge issue but it might be a little annoying?
I don't know if there's any way to fix this.