Subject: Re: bug#53053: 28.0.90; Tramp completion bug of path /sudo::~/

From: Stefan Monnier <[email-masked]>
Date: Mon, 07 Feb 2022 16:51:32 -0500

> For example both
>
> (completion-boundaries "/sudo::~/" #'read-file-name-internal nil "")
> (completion-boundaries "/sudo::/" #'read-file-name-internal nil "")
>
> incorrectly return (8 . 0) as boundaries.

The problem comes from the quoting/unquoting.

`read-file-name-internal` is used for file names that will pass through
`substitute-in-file-name` (as is the case for file names read from
`read-file-name`).

So when you ask to complete "/sudo::~/", Emacs first expands it with
`substitute-in-file-name` and then asks for the completion.
The problem is that the expansion of "/sudo::~/" is exactly the same as
the expansion of "/sudo::~"

So maybe the "right fix" is to change Tramp's handling of
`substitute-in-file-name` such that
"/sudo::~" returns "/sudo:root@<host>:~" instead of
"/sudo:root@<host>:~/",
but in the mean time I installed the patch below which should avoid
this problem at least in the original recipe.  You can still bump into
side effects of the underlying problem, of course.

As pointed out in the comment in `completion--sifn-requote`, this
function is fundamentally asked to do the impossible.

        Stefan

diff --git a/lisp/minibuffer.el b/lisp/minibuffer.el
index c9f58239403..36b8d808417 100644
--- a/lisp/minibuffer.el
+++ b/lisp/minibuffer.el
@@ -2932,6 +2932,10 @@
   (let* ((ustr (substitute-in-file-name qstr))
          (uprefix (substring ustr 0 upos))
          qprefix)
+    (if (eq upos (length ustr))
+        ;; Easy and common case.  This not only speed things up in a very
+        ;; common case but it also avoids problems in some cases (bug#53053).
+        (cons (length qstr) #'minibuffer-maybe-quote-filename)
     ;; Main assumption: nothing after qpos should affect the text before upos,
     ;; so we can work our way backward from the end of qstr, one character
     ;; at a time.
@@ -2951,7 +2955,7 @@
                                    (substitute-in-file-name
                                     (substring qstr 0 (1- qpos)))))
         (setq qpos (1- qpos)))
-      (cons qpos #'minibuffer-maybe-quote-filename))))
+        (cons qpos #'minibuffer-maybe-quote-filename)))))
 
 (defalias 'completion--file-name-table
   (completion-table-with-quoting #'completion-file-name-table