Subject: emacs -nw doesn't always restore the terminal screen

From: "Andries E. Brouwer" <[email-masked]>
Date: Tue, 28 May 2013 20:22:01 +0200

Sometimes after exiting "emacs -nw" the cursor is left
in the middle of a former terminal buffer, so that one
has to search for the bash prompt among former buffer text.
Sometimes the cursor position is OK, but the screen is not restored.

On my old computer I saw this sporadically, now I see it regularly.
It feels like a timing issue.

Probably the same issue was reported by Vincent Lefevre
in bug#10959 for emacs 23.3. That was also my working emacs,
but I verified that emacs 24.3 has the same issue.

Running the session under script shows what emacs sends to the
xterm pseudoterminal.

When all works as expected one sees something like
^[[?12l^[[?25h^[[?12;25h^[[>4m^[[48d^[[?1l^[>^[[?12l^[[?25h^[[?1049l^[[39;49m^M
upon exit. In the cases that fail it is something like
^[[?12l^[[?25h^[[?12;25h^[[>4m^[[48d^[[K

The essential difference for the purposes of this bug is ^[[?1049l,
the "te" capability ("rmcup" in terminfo terms), that restores
terminal state.

First solution:

Replace the invocation "emacs -nw --no-splash file" by
"emacs -nw --no-splash file; tput rmcup".
Now all is fine.

Second solution:

The "^[[>4m" here is from xterm-remove-modify-other-keys
which is attached to kill-emacs-hook. If I remove it,
I no longer see the problem. (Maybe only the timing is changed,
maybe this really helps. One could imagine that the same terminal
is approached via several buffered output streams, and that a
second simultaneous invocation of a terminal write kills the first.)

The ^[[?1l^[>^[[?12l^[[?25h^[[?1049l^[[39;49m^M" comes from
tty_reset_terminal_modes();
It contains a fflush (tty->output); Adding an fsync() there
does not help. An additional sleep for a few seconds does not
help either.

Third solution:

If I add another
OUTPUT_IF (tty, tty->TS_end_termcap_modes); fflush (tty->output);
at the end of tty_reset_terminal_modes();
I no longer see the problem.

Proper solution: no idea.
What sources of concurrency are there? Does emacs use threads?
Does emacs write to several file descriptors that ultimately
refer to the same pty?

Since this is tested via script, the properties of xterm do not seem
to play a role.

Andries