Subject: Re: bug#37782: Emacs 27 client adding [I] to the beginning of the buffer

From: Carlos Pita <[email-masked]>
Date: Fri, 18 Oct 2019 01:29:41 -0300

> Most probably (which is why I pointed to the corresponding escape
> sequences), but the question is exactly why does this not work as
> expected?  Is the terminal you are using too fast or too slow to
> respond?  Is something else wrong?  We need to answer these questions
> to make some progress with this issue.
>
> Maybe someone else can reproduce and debug this.

I've had a hard time debugging this issue but the cause is still unclear to me.

I can easily reproduce the problem with an empty configuration, see
the attached screencast. There I'm just running

emacs --daemon
emacsclient -t

with an empty configuration. Since the behavior is not very
"deterministic" I was many times mislead to believe that the cause was
this or that theme or package, and maybe some packages that make heavy
use of color or other escape sequences do might tend to produce the
artifact more often, I don't know.

Things that I can say for (99%) sure:

1. It only happens in a terminal.
2. It only happens in client/server mode.
3. It only happens the first time I open a client in the terminal.
4. Commenting the  `(send-string-to-terminal "\e[?1004h")` line in
xterm.el suppresses the `[I` sequence (but this of course by disabling
focus tracking).
5. After the initial artifact, focus is indeed tracked correctly, i.e.
xterm-translate-focus-in/out are called as expected for `[I` and `[O`
sequences. But the first time xterm-translate-focus-in is NOT called.
6. When focus tracking is activated xterm-function-map was already
pushed to input-decode-map so AFAICS focus handlers should already be
properly installed.
7. Sometimes it is `[I`, sometimes it is `[I]`.

My hunch is that the escape sequence is not correctly parsed, that the
`[I` part is taken as normal input from the keyboard because the
escape prefix got lost or was interspersed with another sequence.
Probably the answer is in some part of read_key_sequence, but the
combination of client/server mode and low-level tty input is beyond my
debugging abilities.

Best regards
--
Carlos