Hi all,

Emacs-23.2 occasionally loses parts of terminal escape sequences, confusing xt-mouse.el and dumping garbage text in the user's buffer.

Steps to reproduce:
  1. ssh to a machine with emacs-23 installed (I suspect slower networks would expose this more, but the bug bites me even over intranet)
  2. compile tee-input.c (see below) into a shared library (on solaris: `cc -g -G -xcode=pic13 -ldl -hlibtee-input.so tee-input.c -g -o libtee-input.so')
  3. invoke `LD_PRELOAD=libtee-input.so emacs -nw -Q 2>input.txt'
  4. M-x xterm-mouse-mode
  5. flick the mouse scroll wheel hard, so it generates many ticks in quick succession (note the garbage that results)
  6. M-x show-lossage (note the mangled escape sequences)
  7. C-x C-c
  8. Examine input.txt (note the intact escape sequences)
Doing the above with emacs-22.3.1 always works fine, but emacs-23.2.2 mangles one or more escape sequences (input.txt is not corrupted). I suspect this and bug #6920 are symptoms of the same problem.

The number of characters missing ranges from 1 (only ESC missing) to all but one (only [ present); I don't think I've yet seen an entire sequence disappear. The harder the flick the more numerous the mangled escape sequences. It's not an OS issue because I can reproduce it on three very different machines (32-bit cygwin, 64-bit redhat, 32-bit solaris). It's also not a problem with the terminal because the intercepted input is correct. Finally, it's not a problem with xt-mouse.el because show-lossage is incorrect.

To give one example I generated using the above steps, emacs *scratch* buffer shows:
`b[[M`b[

The output of show-lossage is (note the orphaned ` b [, and later the orphaned [, and finally the orphaned M ` b [):
ESC [ > 7 7 ; 9 0 0 ; 0 c ESC x x t e r m - m o u s
e TAB RET ESC [ M ` b [ ` b [ ESC [ M ` b [ ESC [ M
` b [ ESC [ M ` b [ ESC [ M ` b [ ESC [ M ` b [ [ M
` b [ ESC [ M ` b [ ESC O P l

The relevant snippet of input.txt is:
;;;;;ESC[M`b[ESC[M`b[ESC[M`b[ESC[M`b[ESC[M`b[ESC[M`b[ESC[M`b[ESC[M`b[ESC[M`b[ESC[M`b[ESC[M`b[ESCOPl

Thoughts?
Ryan

===== tee-input.c ====
#include <dlfcn.h>
#include <unistd.h>
typedef ssize_t (*read_func)(int fildes, void *buf, size_t nbyte);
ssize_t read(int fildes, void *buf, size_t nbyte) {
    static read_func old_read = 0;
    if(!old_read)
        old_read = (read_func) dlsym(RTLD_NEXT, "read");
    ssize_t rval = old_read(fildes, buf, nbyte);
    if(rval > 0)
        write(2, buf, rval);
    return rval;
}
=================