+#ifdef NCURSES_VERSION
+/*
+ * Cancel xterm's alternate-screen mode (from dialog -TD)
+ */
+#define isprivate(s) ((s) != 0 && strstr(s, "\033[?") != 0)
+static void
+cancel_altscreen(void)
+{
+ if (isatty(fileno(stdout))
+ && key_mouse != 0 /* xterm and kindred */
+ && isprivate(enter_ca_mode)
+ && isprivate(exit_ca_mode)) {
+ /*
+ * initscr() or newterm() already wrote enter_ca_mode as a side effect
+ * of initializing the screen. It would be nice to not even do that,
+ * but we do not really have access to the correct copy of the
+ * terminfo description until those functions have been invoked.
+ */
+ (void) refresh();
+ (void) putp(exit_ca_mode);
+ (void) fflush(stdout);
+ /*
+ * Prevent ncurses from switching "back" to the normal screen when
+ * exiting from this program. That would move the cursor to the
+ * original location saved in xterm. Normally curses sets the cursor
+ * position to the first line after the display, but the alternate
+ * screen switching is done after that point.
+ *
+ * Cancelling the strings altogether also works around the buggy
+ * implementation of alternate-screen in rxvt, etc., which clear more
+ * of the display than they should.
+ */
+ enter_ca_mode = 0;
+ exit_ca_mode = 0;
+ }
+}
+#endif
+